AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / user-2423906

SedJ601's questions

Martin Hope
SedJ601
Asked: 2024-10-01 04:58:07 +0800 CST

O try-with-resources chama o método discard()? [duplicado]

  • 9
Esta pergunta já tem respostas aqui :
detalhes do try-with-resources [duplicado] (2 respostas)
Fechado há 17 horas .

Tenho usado try-with-resourcesmuito. Uso para tipos de recursos de banco de dados ou Filecoisas assim o tempo todo para fechar o recurso.

Agora, estou usando POI para arquivos grandes do Excel e estou percebendo que devo chamar workbook.dispose(). O try-with-resources chamará o dispose()método? Tudo o que pesquisei abrange apenas close().

Não estou convencido de que a duplicata seja a mesma pergunta. Minha pergunta pergunta especificamente se Disposeis handled by try-with-resource. Nenhuma das outras perguntas menciona Dispose.

java
  • 2 respostas
  • 68 Views
Martin Hope
SedJ601
Asked: 2023-09-09 00:05:13 +0800 CST

Comportamento estranho javafx.concurrent.Task

  • 5

Criei um aplicativo para responder a uma pergunta. Na maior parte, o aplicativo é executado corretamente, mas estou tendo um comportamento estranho no ScheduledService updateMessage. Minha compreensão de udpateMessagepode estar errada, o que pode estar me desencaminhando. Meu entendimento é que updateMessagedeve ser atualizado messagePropertytoda vez updateMessageque for chamado. Neste caso, isso deve ocorrer a cada três segundos. Neste aplicativo, isso não está acontecendo. updateValuee System.out.printlnambos estão atualizando conforme esperado. Esse comportamento é defeituoso ou meu pensamento está errado sobre como updateMessagefunciona?

Principal

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.util.Duration;
import org.controlsfx.control.Notifications;

public class App extends Application {
    
    static List<MyNotification> myNotifications = new ArrayList();
    static FakeDatabaseHandler fakeDatabaseHandler = new FakeDatabaseHandler();
    
    @Override
    public void start(Stage stage) {
        
        Button btnGenerateNotification = new Button("Generate!");
        btnGenerateNotification.setOnAction(actionEvent ->{            
             fakeDatabaseHandler.addFakeNotificationsToDb();
        });

        Label lblUpdateMessage = new Label("Update Message: ");
        
        ScheduledService<List<MyNotification>> checkForScheduledService = new CheckForNotificationsScheduledService();
        checkForScheduledService.setPeriod(Duration.seconds(5));
        checkForScheduledService.messageProperty().addListener((ov, oldValue, newValue) -> {
            if(newValue != null)
            {
                lblUpdateMessage.setText("Update Message: " + newValue);
            }
        });
        
        checkForScheduledService.valueProperty().addListener((ov, oldValue, newValue) -> {
            if(newValue != null && !newValue.isEmpty())
            {
                myNotifications.clear();
                myNotifications.addAll(newValue);
                checkForScheduledService.cancel();
                
                AtomicInteger index = new AtomicInteger(0);
                checkForScheduledService.cancel();
                Timeline threeSecondsWonder = new Timeline(
                    new KeyFrame(Duration.seconds(3),  event -> {    
                        MyNotification myNotification = myNotifications.get(index.getAndIncrement());
                        Notifications.create().title(myNotification.department()+ " - " + myNotification.title()).text(myNotification.message()).hideAfter(Duration.seconds(3)).showWarning();
                    })
                );
                threeSecondsWonder.setCycleCount(myNotifications.size());
                threeSecondsWonder.play();
                threeSecondsWonder.setOnFinished((t) -> {
                    checkForScheduledService.restart();
                });
            }
        });
        checkForScheduledService.start();
        
        StackPane root = new StackPane(new VBox(btnGenerateNotification, lblUpdateMessage));

        stage.setScene(new Scene(root, 500, 500));
        stage.setTitle("Facilities");
        stage.show();        
    }

    public static void main(String[] args) {
        launch(args);
    }
    
    private static class CheckForNotificationsScheduledService extends ScheduledService<List<MyNotification>> {

    @Override
    protected Task<List<MyNotification>> createTask() {
        return new Task<List<MyNotification>>() {
            @Override
            protected List<MyNotification> call() throws Exception {
                List<MyNotification> fakeNotificationList = fakeDatabaseHandler.getFakeNotificationsFromDB();
                
                System.out.println("Checking for notifications. Notifications Found: " + fakeNotificationList.size());
                updateMessage("Checking for notifications. Notifications Found: " + fakeNotificationList.size());             
                updateValue(fakeNotificationList);                
                
                return fakeNotificationList; 
            }
        };
    }
  }
}

FakeDatabaseHandler

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 *
 * @author Sed
 */
public class FakeDatabaseHandler {
    private final List<MyNotification> fakeDBData = new ArrayList();    
    
    public FakeDatabaseHandler() {}
    
    public void addFakeNotificationsToDb(){
        List<String> departmentList = Arrays.asList("A", "B", "C", "D");
              
        for(int i = 0; i < ThreadLocalRandom.current().nextInt(1, 6); i++)
        {
            int notificationID = ThreadLocalRandom.current().nextInt( 1000000);
            fakeDBData.add(new MyNotification("Department: " + departmentList.get(ThreadLocalRandom.current().nextInt(4)), "Title " + notificationID, "Message: " + notificationID));
        }
    }
    
    public List<MyNotification> getFakeNotificationsFromDB(){
        List<MyNotification> returnList = new ArrayList(fakeDBData);
        fakeDBData.clear();
        
        return returnList;
    }
}

Minha Notificação

public record MyNotification(String department, String title, String message) {}

Informações do módulo

module com.mycompany.javafxsimpletest {  
    requires org.controlsfx.controls;
    exports com.mycompany.javafxsimpletest;
}

Saída

insira a descrição da imagem aqui

Informações técnicas

Product Version: Apache NetBeans IDE 18
Java: 19.0.2; OpenJDK 64-Bit Server VM 19.0.2+7-jvmci-22.3-b12
Runtime: OpenJDK Runtime Environment 19.0.2+7-jvmci-22.3-b12
System: Windows 11 version 10.0 running on amd64; UTF-8; en_US (nb)
java
  • 1 respostas
  • 41 Views

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve