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 udpateMessage
pode estar errada, o que pode estar me desencaminhando. Meu entendimento é que updateMessage
deve ser atualizado messageProperty
toda vez updateMessage
que for chamado. Neste caso, isso deve ocorrer a cada três segundos. Neste aplicativo, isso não está acontecendo. updateValue
e System.out.println
ambos estão atualizando conforme esperado. Esse comportamento é defeituoso ou meu pensamento está errado sobre como updateMessage
funciona?
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
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)
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
).