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 / coding / Perguntas / 77068398
Accepted
SedJ601
SedJ601
Asked: 2023-09-09 00:05:13 +0800 CST2023-09-09 00:05:13 +0800 CST 2023-09-09 00:05:13 +0800 CST

Comportamento estranho javafx.concurrent.Task

  • 772

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 1 respostas
  • 41 Views

1 respostas

  • Voted
  1. Best Answer
    James_D
    2023-09-09T02:14:25+08:002023-09-09T02:14:25+08:00

    Observe que existem duas mensagens: uma pertencente às tarefas criadas e outra pertencente ao serviço. Quando o serviço está no processo de execução de uma tarefa, sua mensagem é vinculada à mensagem da tarefa, mas quando a tarefa é concluída, a mensagem do serviço é redefinida como nula.

    Conseqüentemente, sua tarefa define sua mensagem (e consequentemente a mensagem do serviço), com base nos valores gerados ao pressionar o botão, mas a tarefa é encerrada imediatamente, fazendo com que a mensagem do serviço seja definida como nula.

    Observe que essas duas alterações podem ser combinadas, dependendo da implementação do serviço. Mas mesmo que não sejam, a mudança para nulo seguirá imediatamente a mudança explicitamente codificada na tarefa, antes que o próximo quadro seja renderizado. Portanto, em ambos os casos, o rótulo exibirá apenas texto nulo.

    Existem vários outros problemas com o seu código, conforme apontado nos comentários abaixo da pergunta (a classe do modelo não é thread-safe, mas é acessada por vários threads e é reiniciada repetidamente, tornando-a redundante ScheduledService).

    • 1

relate perguntas

  • Lock Condition.notify está lançando java.lang.IllegalMonitorStateException

  • Resposta de microsserviço Muitos para Um não aparece no carteiro

  • Validação personalizada do SpringBoot Bean

  • Os soquetes Java são FIFO?

  • Por que não é possível / desencorajado definir um lado do servidor de tempo limite de solicitação?

Sidebar

Stats

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

    destaque o código em HTML usando <font color="#xxx">

    • 2 respostas
  • Marko Smith

    Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}?

    • 1 respostas
  • Marko Smith

    Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)?

    • 2 respostas
  • Marko Smith

    Por que as compreensões de lista criam uma função internamente?

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Marko Smith

    java.lang.NoSuchMethodError: 'void org.openqa.selenium.remote.http.ClientConfig.<init>(java.net.URI, java.time.Duration, java.time.Duratio

    • 3 respostas
  • Marko Smith

    Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)?

    • 4 respostas
  • Marko Smith

    Por que o construtor de uma variável global não é chamado em uma biblioteca?

    • 1 respostas
  • Marko Smith

    Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto?

    • 1 respostas
  • Marko Smith

    Somente operações bit a bit para std::byte em C++ 17?

    • 1 respostas
  • Martin Hope
    fbrereto Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}? 2023-12-21 00:31:04 +0800 CST
  • Martin Hope
    比尔盖子 Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)? 2023-12-17 10:02:06 +0800 CST
  • Martin Hope
    Amir reza Riahi Por que as compreensões de lista criam uma função internamente? 2023-11-16 20:53:19 +0800 CST
  • Martin Hope
    Michael A formato fmt %H:%M:%S sem decimais 2023-11-11 01:13:05 +0800 CST
  • Martin Hope
    God I Hate Python std::views::filter do C++20 não filtrando a visualização corretamente 2023-08-27 18:40:35 +0800 CST
  • Martin Hope
    LiDa Cute Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)? 2023-08-24 20:46:59 +0800 CST
  • Martin Hope
    jabaa Por que o construtor de uma variável global não é chamado em uma biblioteca? 2023-08-18 07:15:20 +0800 CST
  • Martin Hope
    Panagiotis Syskakis Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto? 2023-08-17 21:24:06 +0800 CST
  • Martin Hope
    Alex Guteniev Por que os compiladores perdem a vetorização aqui? 2023-08-17 18:58:07 +0800 CST
  • Martin Hope
    wimalopaan Somente operações bit a bit para std::byte em C++ 17? 2023-08-17 17:13:58 +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