Updating HBox's children while animating causes IllegalStateException [duplicate] - java

I try to run in JavaFX application background thread periodically, which modifies some GUI property.
I think I know how to use Task and Service classes from javafx.concurrent and can't figure it out how to run such periodic task without using Thread#sleep() method. It would be nice if I can use some Executor from Executors fabricate methods (Executors.newSingleThreadScheduledExecutor())
I tried to run Runnable every 5 sec, which restarts javafx.concurrent.Service but it hangs immediately as service.restart or even service.getState() is called.
So finally I use Executors.newSingleThreadScheduledExecutor(), which fires my Runnable every 5 sec and that Runnable runs another Runnable using:
Platform.runLater(new Runnable() {
//here i can modify GUI properties
}
It looks very nasty :( Is there a better way to do this using Task or Service classes?

You can use Timeline for that task:
Timeline fiveSecondsWonder = new Timeline(
new KeyFrame(Duration.seconds(5),
new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("this is called every 5 seconds on UI thread");
}
}));
fiveSecondsWonder.setCycleCount(Timeline.INDEFINITE);
fiveSecondsWonder.play();
for the background processes (which don't do anything to the UI) you can use old good java.util.Timer:
new Timer().schedule(
new TimerTask() {
#Override
public void run() {
System.out.println("ping");
}
}, 0, 5000);

Preface: This question is often the duplicate target for questions which ask how to perform periodic actions in JavaFX, whether the action should be done in the background or not. While there are already great answers to this question, this answer attempts to consolidate all the given information (and more) into a single answer and explain/show the differences between each approach.
This answer focuses on the APIs available in JavaSE and JavaFX and not third-party libraries such as ReactFX (showcased in Tomas Mikula's answer).
Background Information: JavaFX & Threads
Like most mainstream GUI frameworks, JavaFX is single-threaded. This means there's a single thread dedicated to reading and writing the state of the UI and processing user-generated events (e.g. mouse events, key events, etc.). In JavaFX this thread is called the "JavaFX Application Thread", sometimes shortened to just "FX thread", but other frameworks may call it something else. Some other names include "UI thread", "event-dispatch thread", and "main thread".
It is absolutely paramount that anything connected to the GUI showing on screen is only ever accessed or manipulated on the JavaFX Application Thread. The JavaFX framework is not thread-safe and using a different thread to improperly read or write the state of the UI can lead to undefined behavior. Even if you don't see any externally-visible problems, access to state shared between threads without the necessary synchronization is broken code.
Many GUI objects, however, can be manipulated on any thread as long as they aren't "live". From the documentation of javafx.scene.Node:
Node objects may be constructed and modified on any thread as long they are not yet attached to a Scene in a Window that is showing [emphasis added]. An application must attach nodes to such a Scene or modify them on the JavaFX Application Thread.
But other GUI objects, such as Window and even some subclasses of Node (e.g. WebView), are more strict. For instance, from the documentation of javafx.stage.Window:
Window objects must be constructed and modified on the JavaFX Application Thread.
If you're unsure about the threading rules of a GUI object, its documentation should provide the needed information.
Since JavaFX is single-threaded you also have to make sure never to block or otherwise monopolize the FX thread. If the thread is not free to do its job then the UI is never redrawn and new user-generated events can't be processed. Not following this rule can lead to the infamous unresponsive/frozen UI and your users are not happy.
It's virtually always wrong to sleep the JavaFX Application Thread.
Periodic Tasks
There are two different kinds of periodic tasks, at least for the purposes of this answer:
Periodic foreground "tasks".
This could include things such as a "blinking" node or periodically switching between images.
Periodic background tasks.
An example might be periodically checking a remote server for updates and, if there are any, downloading the new information and displaying it to the user.
Periodic Foreground Tasks
If your periodic task is short and simple then using a background thread is overkill and just adds unnecessary complexity. The more appropriate solution is to use the javafx.animation API. Animations are asynchronous but stay entirely within the JavaFX Application Thread. In other words, animations provide a way to "loop" on the FX thread, with delays between each iteration, without actually using loops.
There are three classes uniquely suited to periodic foreground tasks.
Timeline
A Timeline is made up of one or more KeyFrames. Each KeyFrame has a specified time of when it should complete. Each one can also have an "on finished" handler which is invoked after the specified amount of time has elapsed. This means you can create a Timeline with a single KeyFrame that periodically executes an action, looping as many times as you want (including forever).
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class App extends Application {
#Override
public void start(Stage primaryStage) {
Rectangle rect = new Rectangle(100, 100);
// toggle the visibility of 'rect' every 500ms
Timeline timeline =
new Timeline(new KeyFrame(Duration.millis(500), e -> rect.setVisible(!rect.isVisible())));
timeline.setCycleCount(Animation.INDEFINITE); // loop forever
timeline.play();
primaryStage.setScene(new Scene(new StackPane(rect), 200, 200));
primaryStage.show();
}
}
Since a Timeline can have more than one KeyFrame it's possible to have actions being executed at different intervals. Just keep in mind that the times of each KeyFrame do not stack. If you have one KeyFrame with a time of two seconds followed by another KeyFrame with a time of two seconds, both KeyFrames will finish two seconds after the animation is started. To have the second KeyFrame finish two seconds after the first one, its time needs to be four seconds.
PauseTransition
Unlike the other animation classes, a PauseTransition is not used to actually animate anything. It's main purpose is to be used as a child of SequentialTransition to put a pause between two other animations. However, like all subclassses of Animation it can have an "on finished" handler that's executed after it completes, allowing it to be used for periodic tasks.
import javafx.animation.PauseTransition;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class App extends Application {
#Override
public void start(Stage primaryStage) {
Rectangle rect = new Rectangle(100, 100);
// toggle the visibility of 'rect' every 500ms
PauseTransition pause = new PauseTransition(Duration.millis(500));
pause.setOnFinished(
e -> {
rect.setVisible(!rect.isVisible());
pause.playFromStart(); // loop again
});
pause.play();
primaryStage.setScene(new Scene(new StackPane(rect), 200, 200));
primaryStage.show();
}
}
Notice the on-finished handler invokes playFromStart(). This is necessary to "loop" the animation again. The cycleCount property can't be used since the on-finished handler is not invoked at the end of each cycle, it's only invoked at the end of the last cycle. The same thing is true of Timeline; the reason it works with Timeline above is because the on-finished handler isn't registered with the Timeline but with the KeyFrame.
Since the cycleCount property can't be used for PauseTransition for multiple cycles it makes it more difficult to loop only a certain number of times (rather than forever). You have to keep track of the state yourself and only invoke playFromStart() when appropriate. Keep in mind that local variables declared outside a lambda expression or anonymous class but used inside said lambda expression or anonymous class must be final or effectively final.
AnimationTimer
The AnimationTimer class is the lowest level of JavaFX's animation API. It's not a subclass of Animation and thus doesn't have any of the properties that were used above. Instead, it has an abstract method that, when the timer is started, is invoked once per frame with the timestamp (in nanoseconds) of the current frame: #handle(long). In order to execute something periodically with AnimationTimer (other than once per frame) will require manually calculating the time differences between invocations of handle using the method's argument.
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class App extends Application {
#Override
public void start(Stage primaryStage) {
Rectangle rect = new Rectangle(100, 100);
// toggle the visibility of 'rect' every 500ms
AnimationTimer timer =
new AnimationTimer() {
private long lastToggle;
#Override
public void handle(long now) {
if (lastToggle == 0L) {
lastToggle = now;
} else {
long diff = now - lastToggle;
if (diff >= 500_000_000L) { // 500,000,000ns == 500ms
rect.setVisible(!rect.isVisible());
lastToggle = now;
}
}
}
};
timer.start();
primaryStage.setScene(new Scene(new StackPane(rect), 200, 200));
primaryStage.show();
}
}
For most use cases similar to the above, using either Timeline or PauseTransition would be the better option.
Periodic Background Tasks
If your periodic task is time-consuming (e.g. expensive computations) or blocking (e.g. I/O) then a background thread needs to be used. JavaFX comes with some concurrency utilities built-in to aid with communication between background threads and the FX thread. These utilities are described in:
The Concurrency in JavaFX tutorial, and
The documentation of the classes in the javafx.concurrent package.
For periodic background tasks that need to communicate with the FX thread, the class to use is javafx.concurrent.ScheduledService. That class will execute its task periodically, restarting after successful execution, based on a specified period. If configured to do so it will even retry a configurable amount of times after failed executions.
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;
import javafx.concurrent.Worker.State;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;
public class App extends Application {
// maintain a strong reference to the service
private UpdateCheckService service;
#Override
public void start(Stage primaryStage) {
service = new UpdateCheckService();
service.setPeriod(Duration.seconds(5));
Label resultLabel = new Label();
service.setOnRunning(e -> resultLabel.setText(null));
service.setOnSucceeded(
e -> {
if (service.getValue()) {
resultLabel.setText("UPDATES AVAILABLE");
} else {
resultLabel.setText("UP-TO-DATE");
}
});
Label msgLabel = new Label();
msgLabel.textProperty().bind(service.messageProperty());
ProgressBar progBar = new ProgressBar();
progBar.setMaxWidth(Double.MAX_VALUE);
progBar.progressProperty().bind(service.progressProperty());
progBar.visibleProperty().bind(service.stateProperty().isEqualTo(State.RUNNING));
VBox box = new VBox(3, msgLabel, progBar);
box.setMaxHeight(Region.USE_PREF_SIZE);
box.setPadding(new Insets(3));
StackPane root = new StackPane(resultLabel, box);
StackPane.setAlignment(box, Pos.BOTTOM_LEFT);
primaryStage.setScene(new Scene(root, 400, 200));
primaryStage.show();
service.start();
}
private static class UpdateCheckService extends ScheduledService<Boolean> {
#Override
protected Task<Boolean> createTask() {
return new Task<>() {
#Override
protected Boolean call() throws Exception {
updateMessage("Checking for updates...");
for (int i = 0; i < 1000; i++) {
updateProgress(i + 1, 1000);
Thread.sleep(1L); // fake time-consuming work
}
return Math.random() < 0.5; // 50-50 chance updates are "available"
}
};
}
}
}
Here's a note from the documentation of ScheduledService:
Timing for this class is not absolutely reliable. A very busy event thread might introduce some timing lag into the beginning of the execution of the background Task, so very small values for the period or delay are likely to be inaccurate. A delay or period in the hundreds of milliseconds or larger should be fairly reliable.
And another:
The ScheduledService introduces a new property called lastValue. The lastValue is the value that was last successfully computed. Because a Service clears its value property on each run, and because the ScheduledService will reschedule a run immediately after completion (unless it enters the cancelled or failed states), the value property is not overly useful on a ScheduledService. In most cases you will want to instead use the value returned by lastValue.
The last note means binding to the value property of a ScheduledService is in all likelihood useless. The example above works despite querying the value property because the property is queried in the onSucceeded handler, before the service is rescheduled.
No Interaction with UI
If the periodic background task does not need to interact with the UI then you can use the standard APIs of Java instead. More specifically, either:
The java.util.Timer class (not javax.swing.Timer),
Or the more modern java.util.concurrent.ScheduledExecutorService interface.
Note that ScheduledExecutorService supports thread pools, unlike Timer which only supports a single thread.
ScheduledService is not an Option
If for whatever reason you can't use ScheduledService, but need to need to interact with the UI anyway, then you need to make sure the code interacting with the UI, and only that code, is executed on the FX thread. This can be accomplished by using Platform#runLater(Runnable).
Run the specified Runnable on the JavaFX Application Thread at some unspecified time in the future. This method, which may be called from any thread, will post the Runnable to an event queue and then return immediately to the caller. The Runnables are executed in the order they are posted. A runnable passed into the runLater method will be executed before any Runnable passed into a subsequent call to runLater. If this method is called after the JavaFX runtime has been shutdown, the call will be ignored: the Runnable will not be executed and no exception will be thrown.
NOTE: applications should avoid flooding JavaFX with too many pending Runnables. Otherwise, the application may become unresponsive. Applications are encouraged to batch up multiple operations into fewer runLater calls. Additionally, long-running operations should be done on a background thread where possible, freeing up the JavaFX Application Thread for GUI operations.
[...]
Heed the note from the above documentation. The javafx.concurent.Task class avoids this by coalescing updates to its message, progress, and value properties. This is currently implemented by using an AtomicReference and strategic get-and-set operations. If interested, you can take a look at the implementation (JavaFX is open source).

I would Prefer the PauseTransition:
PauseTransition wait = new PauseTransition(Duration.seconds(5));
wait.setOnFinished((e) -> {
/*YOUR METHOD*/
wait.playFromStart();
});
wait.play();

Here is a solution using Java 8 and ReactFX. Say that you want to periodically recompute the value of Label.textProperty().
Label label = ...;
EventStreams.ticks(Duration.ofSeconds(5)) // emits periodic ticks
.supplyCompletionStage(() -> getStatusAsync()) // starts a background task on each tick
.await() // emits task results, when ready
.subscribe(label::setText); // performs label.setText() for each result
CompletionStage<String> getStatusAsync() {
return CompletableFuture.supplyAsync(() -> getStatusFromNetwork());
}
String getStatusFromNetwork() {
// ...
}
Compared to Sergey's solution, you don't dedicate the whole thread to getting status from the network, but instead use the shared thread pool for that.

You can use ScheduledService too. I am using this alternative after noticing that during the use of Timeline and PauseTransition occurred some UI freezes in my application, especially when the user interacts with the elements of a MenuBar (on JavaFX 12). Using the ScheduledService these problems no longer occurred.
class UpdateLabel extends ScheduledService<Void> {
private Label label;
public UpdateLabel(Label label){
this.label = label;
}
#Override
protected Task<Void> createTask(){
return new Task<Void>(){
#Override
protected Void call(){
Platform.runLater(() -> {
/* Modify you GUI properties... */
label.setText(new Random().toString());
});
return null;
}
}
}
}
And then, use it:
class WindowController implements Initializable {
private #FXML Label randomNumber;
#Override
public void initialize(URL u, ResourceBundle res){
var service = new UpdateLabel(randomNumber);
service.setPeriod(Duration.seconds(2)); // The interval between executions.
service.play()
}
}

Was not easy find the way to programing this kind of behavior may be because my process reads I/O, works in milliseconds and I felt was often interrupted by GUI thread, but I made it by creating a BackgroundProcess class & with the help of ScheduledExecutorService.
In the controlle side, I use PauseTransition to read volatile (no contention) info only.
Sample code :
public class HelloApplication extends Application {
final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
final BackgroundProcess backgroundProcess = new BackgroundProcess();
#Override
public void start(Stage stage) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("hello-view.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 720, 610);
HelloController helloController = fxmlLoader.getController();
helloController.setBackgroundProcess(backgroundProcess);
stage.setTitle("Hello!");
stage.setScene(scene);
stage.show();
scheduledExecutor.scheduleWithFixedDelay(
backgroundProcess,
0, 111, TimeUnit.MILLISECONDS);
}
#Override
public void stop() throws Exception {
super.stop();
scheduledExecutor.shutdown();
}
...
}
public class BackgroundProcess implements Runnable{
volatile String status = "";
#Override
public void run() {
status = newStatus();
}
...
}
public class HelloController {
#FXML
protected void initialize() {
PauseTransition refresh = new PauseTransition(Duration.millis(111));
wait.setOnFinished((e) -> {
statusLabel.setText(backgroundProcess.status);
refresh.playFromStart();
});
refresh.play();
}
...
}
To read synchronized (contention) info I use ScheduledService to prepare the info and prevent interruptions in the JavaFX thread.
This is a more complex sample code:
public class HelloApplication extends Application {
final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
final BackgroundProcess backgroundProcess = new BackgroundProcess();
#Override
public void start(Stage stage) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("hello-view.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 720, 610);
HelloController helloController = fxmlLoader.getController();
helloController.setBackgroundProcess(backgroundProcess);
stage.setTitle("Hello!");
stage.setScene(scene);
stage.show();
scheduledExecutor.scheduleWithFixedDelay(
backgroundProcess,
0, 111, TimeUnit.MILLISECONDS);
}
#Override
public void stop() throws Exception {
super.stop();
scheduledExecutor.shutdown();
}
...
}
public class BackgroundProcess implements Runnable{
volatile String status = "";
LinkedTransferQueue<String> queue = new LinkedTransferQueue();
#Override
public void run() {
status = newStatus();
addToQueue();
}
...
}
public class HelloController {
static class SynchronizedInformation {
ArrayList<String> list;
}
private SynchronizedInformation prepareSynchronizedInformation() {
if (backgroundProcess.queue.isEmpty()) {
return null;
}
final SynchronizedInformation r = new SynchronizedInformation();
int size = backgroundProcess.queue.size();
r.list = new ArrayList<>(size);
String line;
while (r.list.size() < size && null != (line = backgroundProcess.queue.poll())) {
r.list.add(line);
}
return r;
}
private void refreshSynchronizedInformation(SynchronizedInformation synchronizedInformation) {
if (null != synchronizedInformation) {
synchronizedInformation.list.forEach(textArea::appendText);
}
statusLabel.setText(backgroundProcess.incoming);
}
#FXML
protected void initialize() {
ScheduledService<SynchronizedInformation> svc = new ScheduledService<>() {
#Override
protected Task<SynchronizedInformation> createTask() {
return new Task<SynchronizedInformation>() {
#Override
protected SynchronizedInformation call() throws Exception {
return prepareSynchronizedInformation();
}
};
}
};
svc.setDelay(Duration.millis(111));
svc.setOnSucceeded(e -> refreshSynchronizedInformation(svc.getValue()));
svc.start();
...
}

Related

Need javafx to slow down and reflect changes in button colors at runtime [duplicate]

I try to run in JavaFX application background thread periodically, which modifies some GUI property.
I think I know how to use Task and Service classes from javafx.concurrent and can't figure it out how to run such periodic task without using Thread#sleep() method. It would be nice if I can use some Executor from Executors fabricate methods (Executors.newSingleThreadScheduledExecutor())
I tried to run Runnable every 5 sec, which restarts javafx.concurrent.Service but it hangs immediately as service.restart or even service.getState() is called.
So finally I use Executors.newSingleThreadScheduledExecutor(), which fires my Runnable every 5 sec and that Runnable runs another Runnable using:
Platform.runLater(new Runnable() {
//here i can modify GUI properties
}
It looks very nasty :( Is there a better way to do this using Task or Service classes?
You can use Timeline for that task:
Timeline fiveSecondsWonder = new Timeline(
new KeyFrame(Duration.seconds(5),
new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("this is called every 5 seconds on UI thread");
}
}));
fiveSecondsWonder.setCycleCount(Timeline.INDEFINITE);
fiveSecondsWonder.play();
for the background processes (which don't do anything to the UI) you can use old good java.util.Timer:
new Timer().schedule(
new TimerTask() {
#Override
public void run() {
System.out.println("ping");
}
}, 0, 5000);
Preface: This question is often the duplicate target for questions which ask how to perform periodic actions in JavaFX, whether the action should be done in the background or not. While there are already great answers to this question, this answer attempts to consolidate all the given information (and more) into a single answer and explain/show the differences between each approach.
This answer focuses on the APIs available in JavaSE and JavaFX and not third-party libraries such as ReactFX (showcased in Tomas Mikula's answer).
Background Information: JavaFX & Threads
Like most mainstream GUI frameworks, JavaFX is single-threaded. This means there's a single thread dedicated to reading and writing the state of the UI and processing user-generated events (e.g. mouse events, key events, etc.). In JavaFX this thread is called the "JavaFX Application Thread", sometimes shortened to just "FX thread", but other frameworks may call it something else. Some other names include "UI thread", "event-dispatch thread", and "main thread".
It is absolutely paramount that anything connected to the GUI showing on screen is only ever accessed or manipulated on the JavaFX Application Thread. The JavaFX framework is not thread-safe and using a different thread to improperly read or write the state of the UI can lead to undefined behavior. Even if you don't see any externally-visible problems, access to state shared between threads without the necessary synchronization is broken code.
Many GUI objects, however, can be manipulated on any thread as long as they aren't "live". From the documentation of javafx.scene.Node:
Node objects may be constructed and modified on any thread as long they are not yet attached to a Scene in a Window that is showing [emphasis added]. An application must attach nodes to such a Scene or modify them on the JavaFX Application Thread.
But other GUI objects, such as Window and even some subclasses of Node (e.g. WebView), are more strict. For instance, from the documentation of javafx.stage.Window:
Window objects must be constructed and modified on the JavaFX Application Thread.
If you're unsure about the threading rules of a GUI object, its documentation should provide the needed information.
Since JavaFX is single-threaded you also have to make sure never to block or otherwise monopolize the FX thread. If the thread is not free to do its job then the UI is never redrawn and new user-generated events can't be processed. Not following this rule can lead to the infamous unresponsive/frozen UI and your users are not happy.
It's virtually always wrong to sleep the JavaFX Application Thread.
Periodic Tasks
There are two different kinds of periodic tasks, at least for the purposes of this answer:
Periodic foreground "tasks".
This could include things such as a "blinking" node or periodically switching between images.
Periodic background tasks.
An example might be periodically checking a remote server for updates and, if there are any, downloading the new information and displaying it to the user.
Periodic Foreground Tasks
If your periodic task is short and simple then using a background thread is overkill and just adds unnecessary complexity. The more appropriate solution is to use the javafx.animation API. Animations are asynchronous but stay entirely within the JavaFX Application Thread. In other words, animations provide a way to "loop" on the FX thread, with delays between each iteration, without actually using loops.
There are three classes uniquely suited to periodic foreground tasks.
Timeline
A Timeline is made up of one or more KeyFrames. Each KeyFrame has a specified time of when it should complete. Each one can also have an "on finished" handler which is invoked after the specified amount of time has elapsed. This means you can create a Timeline with a single KeyFrame that periodically executes an action, looping as many times as you want (including forever).
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class App extends Application {
#Override
public void start(Stage primaryStage) {
Rectangle rect = new Rectangle(100, 100);
// toggle the visibility of 'rect' every 500ms
Timeline timeline =
new Timeline(new KeyFrame(Duration.millis(500), e -> rect.setVisible(!rect.isVisible())));
timeline.setCycleCount(Animation.INDEFINITE); // loop forever
timeline.play();
primaryStage.setScene(new Scene(new StackPane(rect), 200, 200));
primaryStage.show();
}
}
Since a Timeline can have more than one KeyFrame it's possible to have actions being executed at different intervals. Just keep in mind that the times of each KeyFrame do not stack. If you have one KeyFrame with a time of two seconds followed by another KeyFrame with a time of two seconds, both KeyFrames will finish two seconds after the animation is started. To have the second KeyFrame finish two seconds after the first one, its time needs to be four seconds.
PauseTransition
Unlike the other animation classes, a PauseTransition is not used to actually animate anything. It's main purpose is to be used as a child of SequentialTransition to put a pause between two other animations. However, like all subclassses of Animation it can have an "on finished" handler that's executed after it completes, allowing it to be used for periodic tasks.
import javafx.animation.PauseTransition;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class App extends Application {
#Override
public void start(Stage primaryStage) {
Rectangle rect = new Rectangle(100, 100);
// toggle the visibility of 'rect' every 500ms
PauseTransition pause = new PauseTransition(Duration.millis(500));
pause.setOnFinished(
e -> {
rect.setVisible(!rect.isVisible());
pause.playFromStart(); // loop again
});
pause.play();
primaryStage.setScene(new Scene(new StackPane(rect), 200, 200));
primaryStage.show();
}
}
Notice the on-finished handler invokes playFromStart(). This is necessary to "loop" the animation again. The cycleCount property can't be used since the on-finished handler is not invoked at the end of each cycle, it's only invoked at the end of the last cycle. The same thing is true of Timeline; the reason it works with Timeline above is because the on-finished handler isn't registered with the Timeline but with the KeyFrame.
Since the cycleCount property can't be used for PauseTransition for multiple cycles it makes it more difficult to loop only a certain number of times (rather than forever). You have to keep track of the state yourself and only invoke playFromStart() when appropriate. Keep in mind that local variables declared outside a lambda expression or anonymous class but used inside said lambda expression or anonymous class must be final or effectively final.
AnimationTimer
The AnimationTimer class is the lowest level of JavaFX's animation API. It's not a subclass of Animation and thus doesn't have any of the properties that were used above. Instead, it has an abstract method that, when the timer is started, is invoked once per frame with the timestamp (in nanoseconds) of the current frame: #handle(long). In order to execute something periodically with AnimationTimer (other than once per frame) will require manually calculating the time differences between invocations of handle using the method's argument.
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class App extends Application {
#Override
public void start(Stage primaryStage) {
Rectangle rect = new Rectangle(100, 100);
// toggle the visibility of 'rect' every 500ms
AnimationTimer timer =
new AnimationTimer() {
private long lastToggle;
#Override
public void handle(long now) {
if (lastToggle == 0L) {
lastToggle = now;
} else {
long diff = now - lastToggle;
if (diff >= 500_000_000L) { // 500,000,000ns == 500ms
rect.setVisible(!rect.isVisible());
lastToggle = now;
}
}
}
};
timer.start();
primaryStage.setScene(new Scene(new StackPane(rect), 200, 200));
primaryStage.show();
}
}
For most use cases similar to the above, using either Timeline or PauseTransition would be the better option.
Periodic Background Tasks
If your periodic task is time-consuming (e.g. expensive computations) or blocking (e.g. I/O) then a background thread needs to be used. JavaFX comes with some concurrency utilities built-in to aid with communication between background threads and the FX thread. These utilities are described in:
The Concurrency in JavaFX tutorial, and
The documentation of the classes in the javafx.concurrent package.
For periodic background tasks that need to communicate with the FX thread, the class to use is javafx.concurrent.ScheduledService. That class will execute its task periodically, restarting after successful execution, based on a specified period. If configured to do so it will even retry a configurable amount of times after failed executions.
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;
import javafx.concurrent.Worker.State;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;
public class App extends Application {
// maintain a strong reference to the service
private UpdateCheckService service;
#Override
public void start(Stage primaryStage) {
service = new UpdateCheckService();
service.setPeriod(Duration.seconds(5));
Label resultLabel = new Label();
service.setOnRunning(e -> resultLabel.setText(null));
service.setOnSucceeded(
e -> {
if (service.getValue()) {
resultLabel.setText("UPDATES AVAILABLE");
} else {
resultLabel.setText("UP-TO-DATE");
}
});
Label msgLabel = new Label();
msgLabel.textProperty().bind(service.messageProperty());
ProgressBar progBar = new ProgressBar();
progBar.setMaxWidth(Double.MAX_VALUE);
progBar.progressProperty().bind(service.progressProperty());
progBar.visibleProperty().bind(service.stateProperty().isEqualTo(State.RUNNING));
VBox box = new VBox(3, msgLabel, progBar);
box.setMaxHeight(Region.USE_PREF_SIZE);
box.setPadding(new Insets(3));
StackPane root = new StackPane(resultLabel, box);
StackPane.setAlignment(box, Pos.BOTTOM_LEFT);
primaryStage.setScene(new Scene(root, 400, 200));
primaryStage.show();
service.start();
}
private static class UpdateCheckService extends ScheduledService<Boolean> {
#Override
protected Task<Boolean> createTask() {
return new Task<>() {
#Override
protected Boolean call() throws Exception {
updateMessage("Checking for updates...");
for (int i = 0; i < 1000; i++) {
updateProgress(i + 1, 1000);
Thread.sleep(1L); // fake time-consuming work
}
return Math.random() < 0.5; // 50-50 chance updates are "available"
}
};
}
}
}
Here's a note from the documentation of ScheduledService:
Timing for this class is not absolutely reliable. A very busy event thread might introduce some timing lag into the beginning of the execution of the background Task, so very small values for the period or delay are likely to be inaccurate. A delay or period in the hundreds of milliseconds or larger should be fairly reliable.
And another:
The ScheduledService introduces a new property called lastValue. The lastValue is the value that was last successfully computed. Because a Service clears its value property on each run, and because the ScheduledService will reschedule a run immediately after completion (unless it enters the cancelled or failed states), the value property is not overly useful on a ScheduledService. In most cases you will want to instead use the value returned by lastValue.
The last note means binding to the value property of a ScheduledService is in all likelihood useless. The example above works despite querying the value property because the property is queried in the onSucceeded handler, before the service is rescheduled.
No Interaction with UI
If the periodic background task does not need to interact with the UI then you can use the standard APIs of Java instead. More specifically, either:
The java.util.Timer class (not javax.swing.Timer),
Or the more modern java.util.concurrent.ScheduledExecutorService interface.
Note that ScheduledExecutorService supports thread pools, unlike Timer which only supports a single thread.
ScheduledService is not an Option
If for whatever reason you can't use ScheduledService, but need to need to interact with the UI anyway, then you need to make sure the code interacting with the UI, and only that code, is executed on the FX thread. This can be accomplished by using Platform#runLater(Runnable).
Run the specified Runnable on the JavaFX Application Thread at some unspecified time in the future. This method, which may be called from any thread, will post the Runnable to an event queue and then return immediately to the caller. The Runnables are executed in the order they are posted. A runnable passed into the runLater method will be executed before any Runnable passed into a subsequent call to runLater. If this method is called after the JavaFX runtime has been shutdown, the call will be ignored: the Runnable will not be executed and no exception will be thrown.
NOTE: applications should avoid flooding JavaFX with too many pending Runnables. Otherwise, the application may become unresponsive. Applications are encouraged to batch up multiple operations into fewer runLater calls. Additionally, long-running operations should be done on a background thread where possible, freeing up the JavaFX Application Thread for GUI operations.
[...]
Heed the note from the above documentation. The javafx.concurent.Task class avoids this by coalescing updates to its message, progress, and value properties. This is currently implemented by using an AtomicReference and strategic get-and-set operations. If interested, you can take a look at the implementation (JavaFX is open source).
I would Prefer the PauseTransition:
PauseTransition wait = new PauseTransition(Duration.seconds(5));
wait.setOnFinished((e) -> {
/*YOUR METHOD*/
wait.playFromStart();
});
wait.play();
Here is a solution using Java 8 and ReactFX. Say that you want to periodically recompute the value of Label.textProperty().
Label label = ...;
EventStreams.ticks(Duration.ofSeconds(5)) // emits periodic ticks
.supplyCompletionStage(() -> getStatusAsync()) // starts a background task on each tick
.await() // emits task results, when ready
.subscribe(label::setText); // performs label.setText() for each result
CompletionStage<String> getStatusAsync() {
return CompletableFuture.supplyAsync(() -> getStatusFromNetwork());
}
String getStatusFromNetwork() {
// ...
}
Compared to Sergey's solution, you don't dedicate the whole thread to getting status from the network, but instead use the shared thread pool for that.
You can use ScheduledService too. I am using this alternative after noticing that during the use of Timeline and PauseTransition occurred some UI freezes in my application, especially when the user interacts with the elements of a MenuBar (on JavaFX 12). Using the ScheduledService these problems no longer occurred.
class UpdateLabel extends ScheduledService<Void> {
private Label label;
public UpdateLabel(Label label){
this.label = label;
}
#Override
protected Task<Void> createTask(){
return new Task<Void>(){
#Override
protected Void call(){
Platform.runLater(() -> {
/* Modify you GUI properties... */
label.setText(new Random().toString());
});
return null;
}
}
}
}
And then, use it:
class WindowController implements Initializable {
private #FXML Label randomNumber;
#Override
public void initialize(URL u, ResourceBundle res){
var service = new UpdateLabel(randomNumber);
service.setPeriod(Duration.seconds(2)); // The interval between executions.
service.play()
}
}
Was not easy find the way to programing this kind of behavior may be because my process reads I/O, works in milliseconds and I felt was often interrupted by GUI thread, but I made it by creating a BackgroundProcess class & with the help of ScheduledExecutorService.
In the controlle side, I use PauseTransition to read volatile (no contention) info only.
Sample code :
public class HelloApplication extends Application {
final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
final BackgroundProcess backgroundProcess = new BackgroundProcess();
#Override
public void start(Stage stage) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("hello-view.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 720, 610);
HelloController helloController = fxmlLoader.getController();
helloController.setBackgroundProcess(backgroundProcess);
stage.setTitle("Hello!");
stage.setScene(scene);
stage.show();
scheduledExecutor.scheduleWithFixedDelay(
backgroundProcess,
0, 111, TimeUnit.MILLISECONDS);
}
#Override
public void stop() throws Exception {
super.stop();
scheduledExecutor.shutdown();
}
...
}
public class BackgroundProcess implements Runnable{
volatile String status = "";
#Override
public void run() {
status = newStatus();
}
...
}
public class HelloController {
#FXML
protected void initialize() {
PauseTransition refresh = new PauseTransition(Duration.millis(111));
wait.setOnFinished((e) -> {
statusLabel.setText(backgroundProcess.status);
refresh.playFromStart();
});
refresh.play();
}
...
}
To read synchronized (contention) info I use ScheduledService to prepare the info and prevent interruptions in the JavaFX thread.
This is a more complex sample code:
public class HelloApplication extends Application {
final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
final BackgroundProcess backgroundProcess = new BackgroundProcess();
#Override
public void start(Stage stage) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("hello-view.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 720, 610);
HelloController helloController = fxmlLoader.getController();
helloController.setBackgroundProcess(backgroundProcess);
stage.setTitle("Hello!");
stage.setScene(scene);
stage.show();
scheduledExecutor.scheduleWithFixedDelay(
backgroundProcess,
0, 111, TimeUnit.MILLISECONDS);
}
#Override
public void stop() throws Exception {
super.stop();
scheduledExecutor.shutdown();
}
...
}
public class BackgroundProcess implements Runnable{
volatile String status = "";
LinkedTransferQueue<String> queue = new LinkedTransferQueue();
#Override
public void run() {
status = newStatus();
addToQueue();
}
...
}
public class HelloController {
static class SynchronizedInformation {
ArrayList<String> list;
}
private SynchronizedInformation prepareSynchronizedInformation() {
if (backgroundProcess.queue.isEmpty()) {
return null;
}
final SynchronizedInformation r = new SynchronizedInformation();
int size = backgroundProcess.queue.size();
r.list = new ArrayList<>(size);
String line;
while (r.list.size() < size && null != (line = backgroundProcess.queue.poll())) {
r.list.add(line);
}
return r;
}
private void refreshSynchronizedInformation(SynchronizedInformation synchronizedInformation) {
if (null != synchronizedInformation) {
synchronizedInformation.list.forEach(textArea::appendText);
}
statusLabel.setText(backgroundProcess.incoming);
}
#FXML
protected void initialize() {
ScheduledService<SynchronizedInformation> svc = new ScheduledService<>() {
#Override
protected Task<SynchronizedInformation> createTask() {
return new Task<SynchronizedInformation>() {
#Override
protected SynchronizedInformation call() throws Exception {
return prepareSynchronizedInformation();
}
};
}
};
svc.setDelay(Duration.millis(111));
svc.setOnSucceeded(e -> refreshSynchronizedInformation(svc.getValue()));
svc.start();
...
}

JavaFX - alternative to Thread.sleep to prevent program from freezing/not responding? [duplicate]

I try to run in JavaFX application background thread periodically, which modifies some GUI property.
I think I know how to use Task and Service classes from javafx.concurrent and can't figure it out how to run such periodic task without using Thread#sleep() method. It would be nice if I can use some Executor from Executors fabricate methods (Executors.newSingleThreadScheduledExecutor())
I tried to run Runnable every 5 sec, which restarts javafx.concurrent.Service but it hangs immediately as service.restart or even service.getState() is called.
So finally I use Executors.newSingleThreadScheduledExecutor(), which fires my Runnable every 5 sec and that Runnable runs another Runnable using:
Platform.runLater(new Runnable() {
//here i can modify GUI properties
}
It looks very nasty :( Is there a better way to do this using Task or Service classes?
You can use Timeline for that task:
Timeline fiveSecondsWonder = new Timeline(
new KeyFrame(Duration.seconds(5),
new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("this is called every 5 seconds on UI thread");
}
}));
fiveSecondsWonder.setCycleCount(Timeline.INDEFINITE);
fiveSecondsWonder.play();
for the background processes (which don't do anything to the UI) you can use old good java.util.Timer:
new Timer().schedule(
new TimerTask() {
#Override
public void run() {
System.out.println("ping");
}
}, 0, 5000);
Preface: This question is often the duplicate target for questions which ask how to perform periodic actions in JavaFX, whether the action should be done in the background or not. While there are already great answers to this question, this answer attempts to consolidate all the given information (and more) into a single answer and explain/show the differences between each approach.
This answer focuses on the APIs available in JavaSE and JavaFX and not third-party libraries such as ReactFX (showcased in Tomas Mikula's answer).
Background Information: JavaFX & Threads
Like most mainstream GUI frameworks, JavaFX is single-threaded. This means there's a single thread dedicated to reading and writing the state of the UI and processing user-generated events (e.g. mouse events, key events, etc.). In JavaFX this thread is called the "JavaFX Application Thread", sometimes shortened to just "FX thread", but other frameworks may call it something else. Some other names include "UI thread", "event-dispatch thread", and "main thread".
It is absolutely paramount that anything connected to the GUI showing on screen is only ever accessed or manipulated on the JavaFX Application Thread. The JavaFX framework is not thread-safe and using a different thread to improperly read or write the state of the UI can lead to undefined behavior. Even if you don't see any externally-visible problems, access to state shared between threads without the necessary synchronization is broken code.
Many GUI objects, however, can be manipulated on any thread as long as they aren't "live". From the documentation of javafx.scene.Node:
Node objects may be constructed and modified on any thread as long they are not yet attached to a Scene in a Window that is showing [emphasis added]. An application must attach nodes to such a Scene or modify them on the JavaFX Application Thread.
But other GUI objects, such as Window and even some subclasses of Node (e.g. WebView), are more strict. For instance, from the documentation of javafx.stage.Window:
Window objects must be constructed and modified on the JavaFX Application Thread.
If you're unsure about the threading rules of a GUI object, its documentation should provide the needed information.
Since JavaFX is single-threaded you also have to make sure never to block or otherwise monopolize the FX thread. If the thread is not free to do its job then the UI is never redrawn and new user-generated events can't be processed. Not following this rule can lead to the infamous unresponsive/frozen UI and your users are not happy.
It's virtually always wrong to sleep the JavaFX Application Thread.
Periodic Tasks
There are two different kinds of periodic tasks, at least for the purposes of this answer:
Periodic foreground "tasks".
This could include things such as a "blinking" node or periodically switching between images.
Periodic background tasks.
An example might be periodically checking a remote server for updates and, if there are any, downloading the new information and displaying it to the user.
Periodic Foreground Tasks
If your periodic task is short and simple then using a background thread is overkill and just adds unnecessary complexity. The more appropriate solution is to use the javafx.animation API. Animations are asynchronous but stay entirely within the JavaFX Application Thread. In other words, animations provide a way to "loop" on the FX thread, with delays between each iteration, without actually using loops.
There are three classes uniquely suited to periodic foreground tasks.
Timeline
A Timeline is made up of one or more KeyFrames. Each KeyFrame has a specified time of when it should complete. Each one can also have an "on finished" handler which is invoked after the specified amount of time has elapsed. This means you can create a Timeline with a single KeyFrame that periodically executes an action, looping as many times as you want (including forever).
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class App extends Application {
#Override
public void start(Stage primaryStage) {
Rectangle rect = new Rectangle(100, 100);
// toggle the visibility of 'rect' every 500ms
Timeline timeline =
new Timeline(new KeyFrame(Duration.millis(500), e -> rect.setVisible(!rect.isVisible())));
timeline.setCycleCount(Animation.INDEFINITE); // loop forever
timeline.play();
primaryStage.setScene(new Scene(new StackPane(rect), 200, 200));
primaryStage.show();
}
}
Since a Timeline can have more than one KeyFrame it's possible to have actions being executed at different intervals. Just keep in mind that the times of each KeyFrame do not stack. If you have one KeyFrame with a time of two seconds followed by another KeyFrame with a time of two seconds, both KeyFrames will finish two seconds after the animation is started. To have the second KeyFrame finish two seconds after the first one, its time needs to be four seconds.
PauseTransition
Unlike the other animation classes, a PauseTransition is not used to actually animate anything. It's main purpose is to be used as a child of SequentialTransition to put a pause between two other animations. However, like all subclassses of Animation it can have an "on finished" handler that's executed after it completes, allowing it to be used for periodic tasks.
import javafx.animation.PauseTransition;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class App extends Application {
#Override
public void start(Stage primaryStage) {
Rectangle rect = new Rectangle(100, 100);
// toggle the visibility of 'rect' every 500ms
PauseTransition pause = new PauseTransition(Duration.millis(500));
pause.setOnFinished(
e -> {
rect.setVisible(!rect.isVisible());
pause.playFromStart(); // loop again
});
pause.play();
primaryStage.setScene(new Scene(new StackPane(rect), 200, 200));
primaryStage.show();
}
}
Notice the on-finished handler invokes playFromStart(). This is necessary to "loop" the animation again. The cycleCount property can't be used since the on-finished handler is not invoked at the end of each cycle, it's only invoked at the end of the last cycle. The same thing is true of Timeline; the reason it works with Timeline above is because the on-finished handler isn't registered with the Timeline but with the KeyFrame.
Since the cycleCount property can't be used for PauseTransition for multiple cycles it makes it more difficult to loop only a certain number of times (rather than forever). You have to keep track of the state yourself and only invoke playFromStart() when appropriate. Keep in mind that local variables declared outside a lambda expression or anonymous class but used inside said lambda expression or anonymous class must be final or effectively final.
AnimationTimer
The AnimationTimer class is the lowest level of JavaFX's animation API. It's not a subclass of Animation and thus doesn't have any of the properties that were used above. Instead, it has an abstract method that, when the timer is started, is invoked once per frame with the timestamp (in nanoseconds) of the current frame: #handle(long). In order to execute something periodically with AnimationTimer (other than once per frame) will require manually calculating the time differences between invocations of handle using the method's argument.
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class App extends Application {
#Override
public void start(Stage primaryStage) {
Rectangle rect = new Rectangle(100, 100);
// toggle the visibility of 'rect' every 500ms
AnimationTimer timer =
new AnimationTimer() {
private long lastToggle;
#Override
public void handle(long now) {
if (lastToggle == 0L) {
lastToggle = now;
} else {
long diff = now - lastToggle;
if (diff >= 500_000_000L) { // 500,000,000ns == 500ms
rect.setVisible(!rect.isVisible());
lastToggle = now;
}
}
}
};
timer.start();
primaryStage.setScene(new Scene(new StackPane(rect), 200, 200));
primaryStage.show();
}
}
For most use cases similar to the above, using either Timeline or PauseTransition would be the better option.
Periodic Background Tasks
If your periodic task is time-consuming (e.g. expensive computations) or blocking (e.g. I/O) then a background thread needs to be used. JavaFX comes with some concurrency utilities built-in to aid with communication between background threads and the FX thread. These utilities are described in:
The Concurrency in JavaFX tutorial, and
The documentation of the classes in the javafx.concurrent package.
For periodic background tasks that need to communicate with the FX thread, the class to use is javafx.concurrent.ScheduledService. That class will execute its task periodically, restarting after successful execution, based on a specified period. If configured to do so it will even retry a configurable amount of times after failed executions.
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;
import javafx.concurrent.Worker.State;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;
public class App extends Application {
// maintain a strong reference to the service
private UpdateCheckService service;
#Override
public void start(Stage primaryStage) {
service = new UpdateCheckService();
service.setPeriod(Duration.seconds(5));
Label resultLabel = new Label();
service.setOnRunning(e -> resultLabel.setText(null));
service.setOnSucceeded(
e -> {
if (service.getValue()) {
resultLabel.setText("UPDATES AVAILABLE");
} else {
resultLabel.setText("UP-TO-DATE");
}
});
Label msgLabel = new Label();
msgLabel.textProperty().bind(service.messageProperty());
ProgressBar progBar = new ProgressBar();
progBar.setMaxWidth(Double.MAX_VALUE);
progBar.progressProperty().bind(service.progressProperty());
progBar.visibleProperty().bind(service.stateProperty().isEqualTo(State.RUNNING));
VBox box = new VBox(3, msgLabel, progBar);
box.setMaxHeight(Region.USE_PREF_SIZE);
box.setPadding(new Insets(3));
StackPane root = new StackPane(resultLabel, box);
StackPane.setAlignment(box, Pos.BOTTOM_LEFT);
primaryStage.setScene(new Scene(root, 400, 200));
primaryStage.show();
service.start();
}
private static class UpdateCheckService extends ScheduledService<Boolean> {
#Override
protected Task<Boolean> createTask() {
return new Task<>() {
#Override
protected Boolean call() throws Exception {
updateMessage("Checking for updates...");
for (int i = 0; i < 1000; i++) {
updateProgress(i + 1, 1000);
Thread.sleep(1L); // fake time-consuming work
}
return Math.random() < 0.5; // 50-50 chance updates are "available"
}
};
}
}
}
Here's a note from the documentation of ScheduledService:
Timing for this class is not absolutely reliable. A very busy event thread might introduce some timing lag into the beginning of the execution of the background Task, so very small values for the period or delay are likely to be inaccurate. A delay or period in the hundreds of milliseconds or larger should be fairly reliable.
And another:
The ScheduledService introduces a new property called lastValue. The lastValue is the value that was last successfully computed. Because a Service clears its value property on each run, and because the ScheduledService will reschedule a run immediately after completion (unless it enters the cancelled or failed states), the value property is not overly useful on a ScheduledService. In most cases you will want to instead use the value returned by lastValue.
The last note means binding to the value property of a ScheduledService is in all likelihood useless. The example above works despite querying the value property because the property is queried in the onSucceeded handler, before the service is rescheduled.
No Interaction with UI
If the periodic background task does not need to interact with the UI then you can use the standard APIs of Java instead. More specifically, either:
The java.util.Timer class (not javax.swing.Timer),
Or the more modern java.util.concurrent.ScheduledExecutorService interface.
Note that ScheduledExecutorService supports thread pools, unlike Timer which only supports a single thread.
ScheduledService is not an Option
If for whatever reason you can't use ScheduledService, but need to need to interact with the UI anyway, then you need to make sure the code interacting with the UI, and only that code, is executed on the FX thread. This can be accomplished by using Platform#runLater(Runnable).
Run the specified Runnable on the JavaFX Application Thread at some unspecified time in the future. This method, which may be called from any thread, will post the Runnable to an event queue and then return immediately to the caller. The Runnables are executed in the order they are posted. A runnable passed into the runLater method will be executed before any Runnable passed into a subsequent call to runLater. If this method is called after the JavaFX runtime has been shutdown, the call will be ignored: the Runnable will not be executed and no exception will be thrown.
NOTE: applications should avoid flooding JavaFX with too many pending Runnables. Otherwise, the application may become unresponsive. Applications are encouraged to batch up multiple operations into fewer runLater calls. Additionally, long-running operations should be done on a background thread where possible, freeing up the JavaFX Application Thread for GUI operations.
[...]
Heed the note from the above documentation. The javafx.concurent.Task class avoids this by coalescing updates to its message, progress, and value properties. This is currently implemented by using an AtomicReference and strategic get-and-set operations. If interested, you can take a look at the implementation (JavaFX is open source).
I would Prefer the PauseTransition:
PauseTransition wait = new PauseTransition(Duration.seconds(5));
wait.setOnFinished((e) -> {
/*YOUR METHOD*/
wait.playFromStart();
});
wait.play();
Here is a solution using Java 8 and ReactFX. Say that you want to periodically recompute the value of Label.textProperty().
Label label = ...;
EventStreams.ticks(Duration.ofSeconds(5)) // emits periodic ticks
.supplyCompletionStage(() -> getStatusAsync()) // starts a background task on each tick
.await() // emits task results, when ready
.subscribe(label::setText); // performs label.setText() for each result
CompletionStage<String> getStatusAsync() {
return CompletableFuture.supplyAsync(() -> getStatusFromNetwork());
}
String getStatusFromNetwork() {
// ...
}
Compared to Sergey's solution, you don't dedicate the whole thread to getting status from the network, but instead use the shared thread pool for that.
You can use ScheduledService too. I am using this alternative after noticing that during the use of Timeline and PauseTransition occurred some UI freezes in my application, especially when the user interacts with the elements of a MenuBar (on JavaFX 12). Using the ScheduledService these problems no longer occurred.
class UpdateLabel extends ScheduledService<Void> {
private Label label;
public UpdateLabel(Label label){
this.label = label;
}
#Override
protected Task<Void> createTask(){
return new Task<Void>(){
#Override
protected Void call(){
Platform.runLater(() -> {
/* Modify you GUI properties... */
label.setText(new Random().toString());
});
return null;
}
}
}
}
And then, use it:
class WindowController implements Initializable {
private #FXML Label randomNumber;
#Override
public void initialize(URL u, ResourceBundle res){
var service = new UpdateLabel(randomNumber);
service.setPeriod(Duration.seconds(2)); // The interval between executions.
service.play()
}
}
Was not easy find the way to programing this kind of behavior may be because my process reads I/O, works in milliseconds and I felt was often interrupted by GUI thread, but I made it by creating a BackgroundProcess class & with the help of ScheduledExecutorService.
In the controlle side, I use PauseTransition to read volatile (no contention) info only.
Sample code :
public class HelloApplication extends Application {
final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
final BackgroundProcess backgroundProcess = new BackgroundProcess();
#Override
public void start(Stage stage) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("hello-view.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 720, 610);
HelloController helloController = fxmlLoader.getController();
helloController.setBackgroundProcess(backgroundProcess);
stage.setTitle("Hello!");
stage.setScene(scene);
stage.show();
scheduledExecutor.scheduleWithFixedDelay(
backgroundProcess,
0, 111, TimeUnit.MILLISECONDS);
}
#Override
public void stop() throws Exception {
super.stop();
scheduledExecutor.shutdown();
}
...
}
public class BackgroundProcess implements Runnable{
volatile String status = "";
#Override
public void run() {
status = newStatus();
}
...
}
public class HelloController {
#FXML
protected void initialize() {
PauseTransition refresh = new PauseTransition(Duration.millis(111));
wait.setOnFinished((e) -> {
statusLabel.setText(backgroundProcess.status);
refresh.playFromStart();
});
refresh.play();
}
...
}
To read synchronized (contention) info I use ScheduledService to prepare the info and prevent interruptions in the JavaFX thread.
This is a more complex sample code:
public class HelloApplication extends Application {
final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
final BackgroundProcess backgroundProcess = new BackgroundProcess();
#Override
public void start(Stage stage) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("hello-view.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 720, 610);
HelloController helloController = fxmlLoader.getController();
helloController.setBackgroundProcess(backgroundProcess);
stage.setTitle("Hello!");
stage.setScene(scene);
stage.show();
scheduledExecutor.scheduleWithFixedDelay(
backgroundProcess,
0, 111, TimeUnit.MILLISECONDS);
}
#Override
public void stop() throws Exception {
super.stop();
scheduledExecutor.shutdown();
}
...
}
public class BackgroundProcess implements Runnable{
volatile String status = "";
LinkedTransferQueue<String> queue = new LinkedTransferQueue();
#Override
public void run() {
status = newStatus();
addToQueue();
}
...
}
public class HelloController {
static class SynchronizedInformation {
ArrayList<String> list;
}
private SynchronizedInformation prepareSynchronizedInformation() {
if (backgroundProcess.queue.isEmpty()) {
return null;
}
final SynchronizedInformation r = new SynchronizedInformation();
int size = backgroundProcess.queue.size();
r.list = new ArrayList<>(size);
String line;
while (r.list.size() < size && null != (line = backgroundProcess.queue.poll())) {
r.list.add(line);
}
return r;
}
private void refreshSynchronizedInformation(SynchronizedInformation synchronizedInformation) {
if (null != synchronizedInformation) {
synchronizedInformation.list.forEach(textArea::appendText);
}
statusLabel.setText(backgroundProcess.incoming);
}
#FXML
protected void initialize() {
ScheduledService<SynchronizedInformation> svc = new ScheduledService<>() {
#Override
protected Task<SynchronizedInformation> createTask() {
return new Task<SynchronizedInformation>() {
#Override
protected SynchronizedInformation call() throws Exception {
return prepareSynchronizedInformation();
}
};
}
};
svc.setDelay(Duration.millis(111));
svc.setOnSucceeded(e -> refreshSynchronizedInformation(svc.getValue()));
svc.start();
...
}

Why is my (smaller) project running so slowly while my bigger project runs fine? [duplicate]

I try to run in JavaFX application background thread periodically, which modifies some GUI property.
I think I know how to use Task and Service classes from javafx.concurrent and can't figure it out how to run such periodic task without using Thread#sleep() method. It would be nice if I can use some Executor from Executors fabricate methods (Executors.newSingleThreadScheduledExecutor())
I tried to run Runnable every 5 sec, which restarts javafx.concurrent.Service but it hangs immediately as service.restart or even service.getState() is called.
So finally I use Executors.newSingleThreadScheduledExecutor(), which fires my Runnable every 5 sec and that Runnable runs another Runnable using:
Platform.runLater(new Runnable() {
//here i can modify GUI properties
}
It looks very nasty :( Is there a better way to do this using Task or Service classes?
You can use Timeline for that task:
Timeline fiveSecondsWonder = new Timeline(
new KeyFrame(Duration.seconds(5),
new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("this is called every 5 seconds on UI thread");
}
}));
fiveSecondsWonder.setCycleCount(Timeline.INDEFINITE);
fiveSecondsWonder.play();
for the background processes (which don't do anything to the UI) you can use old good java.util.Timer:
new Timer().schedule(
new TimerTask() {
#Override
public void run() {
System.out.println("ping");
}
}, 0, 5000);
Preface: This question is often the duplicate target for questions which ask how to perform periodic actions in JavaFX, whether the action should be done in the background or not. While there are already great answers to this question, this answer attempts to consolidate all the given information (and more) into a single answer and explain/show the differences between each approach.
This answer focuses on the APIs available in JavaSE and JavaFX and not third-party libraries such as ReactFX (showcased in Tomas Mikula's answer).
Background Information: JavaFX & Threads
Like most mainstream GUI frameworks, JavaFX is single-threaded. This means there's a single thread dedicated to reading and writing the state of the UI and processing user-generated events (e.g. mouse events, key events, etc.). In JavaFX this thread is called the "JavaFX Application Thread", sometimes shortened to just "FX thread", but other frameworks may call it something else. Some other names include "UI thread", "event-dispatch thread", and "main thread".
It is absolutely paramount that anything connected to the GUI showing on screen is only ever accessed or manipulated on the JavaFX Application Thread. The JavaFX framework is not thread-safe and using a different thread to improperly read or write the state of the UI can lead to undefined behavior. Even if you don't see any externally-visible problems, access to state shared between threads without the necessary synchronization is broken code.
Many GUI objects, however, can be manipulated on any thread as long as they aren't "live". From the documentation of javafx.scene.Node:
Node objects may be constructed and modified on any thread as long they are not yet attached to a Scene in a Window that is showing [emphasis added]. An application must attach nodes to such a Scene or modify them on the JavaFX Application Thread.
But other GUI objects, such as Window and even some subclasses of Node (e.g. WebView), are more strict. For instance, from the documentation of javafx.stage.Window:
Window objects must be constructed and modified on the JavaFX Application Thread.
If you're unsure about the threading rules of a GUI object, its documentation should provide the needed information.
Since JavaFX is single-threaded you also have to make sure never to block or otherwise monopolize the FX thread. If the thread is not free to do its job then the UI is never redrawn and new user-generated events can't be processed. Not following this rule can lead to the infamous unresponsive/frozen UI and your users are not happy.
It's virtually always wrong to sleep the JavaFX Application Thread.
Periodic Tasks
There are two different kinds of periodic tasks, at least for the purposes of this answer:
Periodic foreground "tasks".
This could include things such as a "blinking" node or periodically switching between images.
Periodic background tasks.
An example might be periodically checking a remote server for updates and, if there are any, downloading the new information and displaying it to the user.
Periodic Foreground Tasks
If your periodic task is short and simple then using a background thread is overkill and just adds unnecessary complexity. The more appropriate solution is to use the javafx.animation API. Animations are asynchronous but stay entirely within the JavaFX Application Thread. In other words, animations provide a way to "loop" on the FX thread, with delays between each iteration, without actually using loops.
There are three classes uniquely suited to periodic foreground tasks.
Timeline
A Timeline is made up of one or more KeyFrames. Each KeyFrame has a specified time of when it should complete. Each one can also have an "on finished" handler which is invoked after the specified amount of time has elapsed. This means you can create a Timeline with a single KeyFrame that periodically executes an action, looping as many times as you want (including forever).
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class App extends Application {
#Override
public void start(Stage primaryStage) {
Rectangle rect = new Rectangle(100, 100);
// toggle the visibility of 'rect' every 500ms
Timeline timeline =
new Timeline(new KeyFrame(Duration.millis(500), e -> rect.setVisible(!rect.isVisible())));
timeline.setCycleCount(Animation.INDEFINITE); // loop forever
timeline.play();
primaryStage.setScene(new Scene(new StackPane(rect), 200, 200));
primaryStage.show();
}
}
Since a Timeline can have more than one KeyFrame it's possible to have actions being executed at different intervals. Just keep in mind that the times of each KeyFrame do not stack. If you have one KeyFrame with a time of two seconds followed by another KeyFrame with a time of two seconds, both KeyFrames will finish two seconds after the animation is started. To have the second KeyFrame finish two seconds after the first one, its time needs to be four seconds.
PauseTransition
Unlike the other animation classes, a PauseTransition is not used to actually animate anything. It's main purpose is to be used as a child of SequentialTransition to put a pause between two other animations. However, like all subclassses of Animation it can have an "on finished" handler that's executed after it completes, allowing it to be used for periodic tasks.
import javafx.animation.PauseTransition;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class App extends Application {
#Override
public void start(Stage primaryStage) {
Rectangle rect = new Rectangle(100, 100);
// toggle the visibility of 'rect' every 500ms
PauseTransition pause = new PauseTransition(Duration.millis(500));
pause.setOnFinished(
e -> {
rect.setVisible(!rect.isVisible());
pause.playFromStart(); // loop again
});
pause.play();
primaryStage.setScene(new Scene(new StackPane(rect), 200, 200));
primaryStage.show();
}
}
Notice the on-finished handler invokes playFromStart(). This is necessary to "loop" the animation again. The cycleCount property can't be used since the on-finished handler is not invoked at the end of each cycle, it's only invoked at the end of the last cycle. The same thing is true of Timeline; the reason it works with Timeline above is because the on-finished handler isn't registered with the Timeline but with the KeyFrame.
Since the cycleCount property can't be used for PauseTransition for multiple cycles it makes it more difficult to loop only a certain number of times (rather than forever). You have to keep track of the state yourself and only invoke playFromStart() when appropriate. Keep in mind that local variables declared outside a lambda expression or anonymous class but used inside said lambda expression or anonymous class must be final or effectively final.
AnimationTimer
The AnimationTimer class is the lowest level of JavaFX's animation API. It's not a subclass of Animation and thus doesn't have any of the properties that were used above. Instead, it has an abstract method that, when the timer is started, is invoked once per frame with the timestamp (in nanoseconds) of the current frame: #handle(long). In order to execute something periodically with AnimationTimer (other than once per frame) will require manually calculating the time differences between invocations of handle using the method's argument.
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class App extends Application {
#Override
public void start(Stage primaryStage) {
Rectangle rect = new Rectangle(100, 100);
// toggle the visibility of 'rect' every 500ms
AnimationTimer timer =
new AnimationTimer() {
private long lastToggle;
#Override
public void handle(long now) {
if (lastToggle == 0L) {
lastToggle = now;
} else {
long diff = now - lastToggle;
if (diff >= 500_000_000L) { // 500,000,000ns == 500ms
rect.setVisible(!rect.isVisible());
lastToggle = now;
}
}
}
};
timer.start();
primaryStage.setScene(new Scene(new StackPane(rect), 200, 200));
primaryStage.show();
}
}
For most use cases similar to the above, using either Timeline or PauseTransition would be the better option.
Periodic Background Tasks
If your periodic task is time-consuming (e.g. expensive computations) or blocking (e.g. I/O) then a background thread needs to be used. JavaFX comes with some concurrency utilities built-in to aid with communication between background threads and the FX thread. These utilities are described in:
The Concurrency in JavaFX tutorial, and
The documentation of the classes in the javafx.concurrent package.
For periodic background tasks that need to communicate with the FX thread, the class to use is javafx.concurrent.ScheduledService. That class will execute its task periodically, restarting after successful execution, based on a specified period. If configured to do so it will even retry a configurable amount of times after failed executions.
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;
import javafx.concurrent.Worker.State;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;
public class App extends Application {
// maintain a strong reference to the service
private UpdateCheckService service;
#Override
public void start(Stage primaryStage) {
service = new UpdateCheckService();
service.setPeriod(Duration.seconds(5));
Label resultLabel = new Label();
service.setOnRunning(e -> resultLabel.setText(null));
service.setOnSucceeded(
e -> {
if (service.getValue()) {
resultLabel.setText("UPDATES AVAILABLE");
} else {
resultLabel.setText("UP-TO-DATE");
}
});
Label msgLabel = new Label();
msgLabel.textProperty().bind(service.messageProperty());
ProgressBar progBar = new ProgressBar();
progBar.setMaxWidth(Double.MAX_VALUE);
progBar.progressProperty().bind(service.progressProperty());
progBar.visibleProperty().bind(service.stateProperty().isEqualTo(State.RUNNING));
VBox box = new VBox(3, msgLabel, progBar);
box.setMaxHeight(Region.USE_PREF_SIZE);
box.setPadding(new Insets(3));
StackPane root = new StackPane(resultLabel, box);
StackPane.setAlignment(box, Pos.BOTTOM_LEFT);
primaryStage.setScene(new Scene(root, 400, 200));
primaryStage.show();
service.start();
}
private static class UpdateCheckService extends ScheduledService<Boolean> {
#Override
protected Task<Boolean> createTask() {
return new Task<>() {
#Override
protected Boolean call() throws Exception {
updateMessage("Checking for updates...");
for (int i = 0; i < 1000; i++) {
updateProgress(i + 1, 1000);
Thread.sleep(1L); // fake time-consuming work
}
return Math.random() < 0.5; // 50-50 chance updates are "available"
}
};
}
}
}
Here's a note from the documentation of ScheduledService:
Timing for this class is not absolutely reliable. A very busy event thread might introduce some timing lag into the beginning of the execution of the background Task, so very small values for the period or delay are likely to be inaccurate. A delay or period in the hundreds of milliseconds or larger should be fairly reliable.
And another:
The ScheduledService introduces a new property called lastValue. The lastValue is the value that was last successfully computed. Because a Service clears its value property on each run, and because the ScheduledService will reschedule a run immediately after completion (unless it enters the cancelled or failed states), the value property is not overly useful on a ScheduledService. In most cases you will want to instead use the value returned by lastValue.
The last note means binding to the value property of a ScheduledService is in all likelihood useless. The example above works despite querying the value property because the property is queried in the onSucceeded handler, before the service is rescheduled.
No Interaction with UI
If the periodic background task does not need to interact with the UI then you can use the standard APIs of Java instead. More specifically, either:
The java.util.Timer class (not javax.swing.Timer),
Or the more modern java.util.concurrent.ScheduledExecutorService interface.
Note that ScheduledExecutorService supports thread pools, unlike Timer which only supports a single thread.
ScheduledService is not an Option
If for whatever reason you can't use ScheduledService, but need to need to interact with the UI anyway, then you need to make sure the code interacting with the UI, and only that code, is executed on the FX thread. This can be accomplished by using Platform#runLater(Runnable).
Run the specified Runnable on the JavaFX Application Thread at some unspecified time in the future. This method, which may be called from any thread, will post the Runnable to an event queue and then return immediately to the caller. The Runnables are executed in the order they are posted. A runnable passed into the runLater method will be executed before any Runnable passed into a subsequent call to runLater. If this method is called after the JavaFX runtime has been shutdown, the call will be ignored: the Runnable will not be executed and no exception will be thrown.
NOTE: applications should avoid flooding JavaFX with too many pending Runnables. Otherwise, the application may become unresponsive. Applications are encouraged to batch up multiple operations into fewer runLater calls. Additionally, long-running operations should be done on a background thread where possible, freeing up the JavaFX Application Thread for GUI operations.
[...]
Heed the note from the above documentation. The javafx.concurent.Task class avoids this by coalescing updates to its message, progress, and value properties. This is currently implemented by using an AtomicReference and strategic get-and-set operations. If interested, you can take a look at the implementation (JavaFX is open source).
I would Prefer the PauseTransition:
PauseTransition wait = new PauseTransition(Duration.seconds(5));
wait.setOnFinished((e) -> {
/*YOUR METHOD*/
wait.playFromStart();
});
wait.play();
Here is a solution using Java 8 and ReactFX. Say that you want to periodically recompute the value of Label.textProperty().
Label label = ...;
EventStreams.ticks(Duration.ofSeconds(5)) // emits periodic ticks
.supplyCompletionStage(() -> getStatusAsync()) // starts a background task on each tick
.await() // emits task results, when ready
.subscribe(label::setText); // performs label.setText() for each result
CompletionStage<String> getStatusAsync() {
return CompletableFuture.supplyAsync(() -> getStatusFromNetwork());
}
String getStatusFromNetwork() {
// ...
}
Compared to Sergey's solution, you don't dedicate the whole thread to getting status from the network, but instead use the shared thread pool for that.
You can use ScheduledService too. I am using this alternative after noticing that during the use of Timeline and PauseTransition occurred some UI freezes in my application, especially when the user interacts with the elements of a MenuBar (on JavaFX 12). Using the ScheduledService these problems no longer occurred.
class UpdateLabel extends ScheduledService<Void> {
private Label label;
public UpdateLabel(Label label){
this.label = label;
}
#Override
protected Task<Void> createTask(){
return new Task<Void>(){
#Override
protected Void call(){
Platform.runLater(() -> {
/* Modify you GUI properties... */
label.setText(new Random().toString());
});
return null;
}
}
}
}
And then, use it:
class WindowController implements Initializable {
private #FXML Label randomNumber;
#Override
public void initialize(URL u, ResourceBundle res){
var service = new UpdateLabel(randomNumber);
service.setPeriod(Duration.seconds(2)); // The interval between executions.
service.play()
}
}
Was not easy find the way to programing this kind of behavior may be because my process reads I/O, works in milliseconds and I felt was often interrupted by GUI thread, but I made it by creating a BackgroundProcess class & with the help of ScheduledExecutorService.
In the controlle side, I use PauseTransition to read volatile (no contention) info only.
Sample code :
public class HelloApplication extends Application {
final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
final BackgroundProcess backgroundProcess = new BackgroundProcess();
#Override
public void start(Stage stage) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("hello-view.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 720, 610);
HelloController helloController = fxmlLoader.getController();
helloController.setBackgroundProcess(backgroundProcess);
stage.setTitle("Hello!");
stage.setScene(scene);
stage.show();
scheduledExecutor.scheduleWithFixedDelay(
backgroundProcess,
0, 111, TimeUnit.MILLISECONDS);
}
#Override
public void stop() throws Exception {
super.stop();
scheduledExecutor.shutdown();
}
...
}
public class BackgroundProcess implements Runnable{
volatile String status = "";
#Override
public void run() {
status = newStatus();
}
...
}
public class HelloController {
#FXML
protected void initialize() {
PauseTransition refresh = new PauseTransition(Duration.millis(111));
wait.setOnFinished((e) -> {
statusLabel.setText(backgroundProcess.status);
refresh.playFromStart();
});
refresh.play();
}
...
}
To read synchronized (contention) info I use ScheduledService to prepare the info and prevent interruptions in the JavaFX thread.
This is a more complex sample code:
public class HelloApplication extends Application {
final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
final BackgroundProcess backgroundProcess = new BackgroundProcess();
#Override
public void start(Stage stage) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("hello-view.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 720, 610);
HelloController helloController = fxmlLoader.getController();
helloController.setBackgroundProcess(backgroundProcess);
stage.setTitle("Hello!");
stage.setScene(scene);
stage.show();
scheduledExecutor.scheduleWithFixedDelay(
backgroundProcess,
0, 111, TimeUnit.MILLISECONDS);
}
#Override
public void stop() throws Exception {
super.stop();
scheduledExecutor.shutdown();
}
...
}
public class BackgroundProcess implements Runnable{
volatile String status = "";
LinkedTransferQueue<String> queue = new LinkedTransferQueue();
#Override
public void run() {
status = newStatus();
addToQueue();
}
...
}
public class HelloController {
static class SynchronizedInformation {
ArrayList<String> list;
}
private SynchronizedInformation prepareSynchronizedInformation() {
if (backgroundProcess.queue.isEmpty()) {
return null;
}
final SynchronizedInformation r = new SynchronizedInformation();
int size = backgroundProcess.queue.size();
r.list = new ArrayList<>(size);
String line;
while (r.list.size() < size && null != (line = backgroundProcess.queue.poll())) {
r.list.add(line);
}
return r;
}
private void refreshSynchronizedInformation(SynchronizedInformation synchronizedInformation) {
if (null != synchronizedInformation) {
synchronizedInformation.list.forEach(textArea::appendText);
}
statusLabel.setText(backgroundProcess.incoming);
}
#FXML
protected void initialize() {
ScheduledService<SynchronizedInformation> svc = new ScheduledService<>() {
#Override
protected Task<SynchronizedInformation> createTask() {
return new Task<SynchronizedInformation>() {
#Override
protected SynchronizedInformation call() throws Exception {
return prepareSynchronizedInformation();
}
};
}
};
svc.setDelay(Duration.millis(111));
svc.setOnSucceeded(e -> refreshSynchronizedInformation(svc.getValue()));
svc.start();
...
}

Java method run only once the full code after a scheduler runnable shutdown using JavaFX

Im stuck programing a Tetris game trying to learn Java and JavaFX.
When I call the method the first time from method start it runs well, when I call it from the thread it only runs partially, and dont add a new node to the pane.
Here is part of the code, you can view it entirely in
#Override
public void start(Stage stage) {
...
stage.show();
newPieces();
}
public void newPieces() {
Pieces pieces = new Pieces();
piece = pieces.createPiece();
nextPiece = pieces.createPiece();
boolean add1 = vbox.getChildren().add(nextPiece);
boolean add2 = pane.getChildren().add(piece);
translateDown(piece);
}
public void translateDown(Group piece) {
scheduler.scheduleWithFixedDelay(new Runnable() {
#Override
public void run() {
boolean translate = piece.getTransforms().add(new Translate(0, 25));
...
...
newPieces();
scheduler.shutdown();
...
...
}, 0, 1, TimeUnit.SECONDS);
The method newPieces creates a Group of Rectangles.
Thanks!
Instead of using a executor to schedule the updates I recommend using a Timeline which executes a frame's event handler on the application thread. Running the updates on a application thread is important since modifying properies of nodes on a different thread is problematic:
Timeline timeline = new Timeline();
timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(1), evt -> {
updateBoard(); // do things like moving a piece...
if (checkLoss()) {
// stop updates when game is lost
timeline.stop();
}
}));
// repeat indefinitely
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
You could also use timeline.pause() to pause the game and set the rate property to speed up the game...
If you want to access the javafx gui components you have to run the code on the javafx thread. The extra thread you start is not allowed to access the javafx elements. The exception thrown is probably uncatched.
Try Platform.runLater(Runnable runnable) with the code modifing the gui. This runs the specified runnable on the javafx thread at some time in the future.

Properly doing multithreading and thread pools with JavaFX Tasks

I have an option for users to submit multiple files from a FileChooser to be processed by some code. The result will be IO for reading the file, then the actual heavy computation on the stored data. The user is allowed to select multiple files, and since file processing does not depend on any of the other files selected, that makes my life a lot easier to handle this with threads.
In addition, the user needs to have a list of buttons, one for each Task to cancel, and a "Cancel All" button. Therefore I have to consider the ability to selectively or collectively kill one or all of the Tasks.
The last requirement is that I don't let the user choke the system by opening a ton of files. Therefore I figure a thread pool with a limited number of threads (let's pretend I'll cap it at 4 for some arbitrary number).
I am unsure how to properly go about setting this all up. I have the logic of what I need to do but using the right classes is where I am stuck.
I've checked this resource already, so if the answer is somehow in there then I've misread the article.
Are there any JavaFX classes that can help me with this situation?
If not, how would I mix a Task with some kind of thread pool? Do I have to make my own thread pool or is there one that is already provided for me?
Am I to make a singleton somewhere that contains the max number of threads I am willing to allow the user?
I would prefer to use one already in Java library since I am not a multithreading expert, and am worried that I could potentially do it wrong. Since thread bugs appear to be the most evil thing on the planet to debug, I'm trying very hard to make sure I do this as correctly as possible.
If there are no ways to do this and I have to roll my own implementation, what is the best way to go about doing this?
EDIT: I should note that I am generally new to threads, I have used them before and I'm reading books on them, but this will be my first major use of them and I'd really like to do it properly.
JavaFX has a javafx.concurrent API; in particular, the Task class fits your use case very nicely. This API is designed to work in conjunction with the java.util.concurrent API. For example, Task is an implementation of FutureTask, so it can be submitted to an Executor. As you want to use a thread pool, you can create an Executor that implements a thread pool for you, and submit your tasks to it:
final int MAX_THREADS = 4 ;
Executor exec = Executors.newFixedThreadPool(MAX_THREADS);
As these threads are running in the background of a UI application, you probably don't want them to prevent application exit. You can achieve this by making the threads created by your executor daemon threads:
Executor exec = Executors.newFixedThreadPool(MAX_THREADS, runnable -> {
Thread t = new Thread(runnable);
t.setDaemon(true);
return t ;
});
The resulting executor will have a pool of up to MAX_THREADS threads. If tasks are submitted when no threads are available, they will wait in a queue until a thread becomes available.
To implement the actual Task, there are a few things to bear in mind:
You must not update the UI from a background thread. Since your Task is submitted to the executor above, it's call() method will be invoked on a background thread. If you really need to change the UI during the execution of the call method, you can wrap the code that changes the UI in Platform.runLater(...), but it is better to structure things so that you avoid this situation. In particular, the Task has a set of updateXXX(...) methods that change the values of corresponding Task properties on the FX Application thread. Your UI elements can bind to these properties as needed.
It is advisable for the call method not to access any shared data (other than via the updateXXX(...) methods mentioned above). Instantiate your Task subclass setting only final variables, have the call() method compute a value, and return the value.
For canceling the Task, the Task class defines a built-in cancel() method. If you have a long-running call() method, you should periodically check the value of isCancelled() and stop doing work if it returns true.
Here's a basic example:
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import javafx.application.Application;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.beans.value.ChangeListener;
import javafx.concurrent.Task;
import javafx.concurrent.Worker;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.ProgressBarTableCell;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
public class FileTaskExample extends Application {
private static final Random RNG = new Random();
private static final int MAX_THREADS = 4 ;
private final Executor exec = Executors.newFixedThreadPool(MAX_THREADS, runnable -> {
Thread t = new Thread(runnable);
t.setDaemon(true);
return t ;
});
#Override
public void start(Stage primaryStage) {
// table to display all tasks:
TableView<FileProcessingTask> table = new TableView<>();
TableColumn<FileProcessingTask, File> fileColumn = new TableColumn<>("File");
fileColumn.setCellValueFactory(cellData -> new ReadOnlyObjectWrapper<File>(cellData.getValue().getFile()));
fileColumn.setCellFactory(col -> new TableCell<FileProcessingTask, File>() {
#Override
public void updateItem(File file, boolean empty) {
super.updateItem(file, empty);
if (empty) {
setText(null);
} else {
setText(file.getName());
}
}
});
fileColumn.setPrefWidth(200);
TableColumn<FileProcessingTask, Worker.State> statusColumn = new TableColumn<>("Status");
statusColumn.setCellValueFactory(cellData -> cellData.getValue().stateProperty());
statusColumn.setPrefWidth(100);
TableColumn<FileProcessingTask, Double> progressColumn = new TableColumn<>("Progress");
progressColumn.setCellValueFactory(cellData -> cellData.getValue().progressProperty().asObject());
progressColumn.setCellFactory(ProgressBarTableCell.forTableColumn());
progressColumn.setPrefWidth(100);
TableColumn<FileProcessingTask, Long> resultColumn = new TableColumn<>("Result");
resultColumn.setCellValueFactory(cellData -> cellData.getValue().valueProperty());
resultColumn.setPrefWidth(100);
TableColumn<FileProcessingTask, FileProcessingTask> cancelColumn = new TableColumn<>("Cancel");
cancelColumn.setCellValueFactory(cellData -> new ReadOnlyObjectWrapper<FileProcessingTask>(cellData.getValue()));
cancelColumn.setCellFactory(col -> {
TableCell<FileProcessingTask, FileProcessingTask> cell = new TableCell<>();
Button cancelButton = new Button("Cancel");
cancelButton.setOnAction(e -> cell.getItem().cancel());
// listener for disabling button if task is not running:
ChangeListener<Boolean> disableListener = (obs, wasRunning, isNowRunning) ->
cancelButton.setDisable(! isNowRunning);
cell.itemProperty().addListener((obs, oldTask, newTask) -> {
if (oldTask != null) {
oldTask.runningProperty().removeListener(disableListener);
}
if (newTask == null) {
cell.setGraphic(null);
} else {
cell.setGraphic(cancelButton);
cancelButton.setDisable(! newTask.isRunning());
newTask.runningProperty().addListener(disableListener);
}
});
return cell ;
});
cancelColumn.setPrefWidth(100);
table.getColumns().addAll(Arrays.asList(fileColumn, statusColumn, progressColumn, resultColumn, cancelColumn));
Button cancelAllButton = new Button("Cancel All");
cancelAllButton.setOnAction(e ->
table.getItems().stream().filter(Task::isRunning).forEach(Task::cancel));
Button newTasksButton = new Button("Process files");
FileChooser chooser = new FileChooser();
newTasksButton.setOnAction(e -> {
List<File> files = chooser.showOpenMultipleDialog(primaryStage);
if (files != null) {
files.stream().map(FileProcessingTask::new).peek(exec::execute).forEach(table.getItems()::add);
}
});
HBox controls = new HBox(5, newTasksButton, cancelAllButton);
controls.setAlignment(Pos.CENTER);
controls.setPadding(new Insets(10));
BorderPane root = new BorderPane(table, null, null, controls, null);
Scene scene = new Scene(root, 800, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
public static class FileProcessingTask extends Task<Long> {
private final File file ;
public FileProcessingTask(File file) {
this.file = file ;
}
public File getFile() {
return file ;
}
#Override
public Long call() throws Exception {
// just to show you can return the result of the computation:
long fileLength = file.length();
// dummy processing, in real life read file and do something with it:
int delay = RNG.nextInt(50) + 50 ;
for (int i = 0 ; i < 100; i++) {
Thread.sleep(delay);
updateProgress(i, 100);
// check for cancellation and bail if cancelled:
if (isCancelled()) {
updateProgress(0, 100);
break ;
}
}
return fileLength ;
}
}
public static void main(String[] args) {
launch(args);
}
}

Categories