Thread Management
Writing concurrent application could be painful ! Not with JRebirth

Thread Management

In 30 seconds

JAT = JavaFX UI thread (update displayed nodes). JIT = JRebirth messaging (waves, listen/send). JTP/HPTP = background pools (heavy work). Commands/Services pick threads via @RunInto or base classes. From non-component code use JRebirth.runIntoJAT(...), runIntoJIT(...), runIntoJTP(...).

How to use

  1. UI updates on nodes in the scene → JAT (DefaultUICommand, @RunInto(JAT)).
  2. Wave listen/send and notifier work → JIT (automatic for listen / sendWave).
  3. File I/O, parsing, remote calls → JTP (DefaultPoolCommand, @RunInto(JTP)).
  4. Service task methods run on JTP by default; return waves to Models are handled on JAT.
  5. Stuck on the wrong thread? Use JRebirth.runIntoJAT(() -> { ... }) — not raw Platform.runLater as a pattern.

Threading overview

JRebirth is multi-threaded, not only by using Task Worker provided by JavaFX APIs. JRebirth has got its own Thread to manage local events (called waves) allowing components to communicate with each others. It also allows to manage multiple threads in a very simple manner with its included thread pool.

Thus all inner JRebirth tasks are processed into a custom thread and don't infer with the JavaFX Application Thread which have to manage user events and some UI instantiation.

Lags, UI Freeze … are lost to history :D

What happens when you debug a JRebirth application ? You can observe a lot of threads, but don't be scared !! Everything is at the right isolated place doing the right thing.

The most important are :

  • JAT - JavaFX Application Thread
  • JIT - JRebirth Internal Thread
  • JTP - JRebirth Thread Pool (name pattern is JTP Slot ‘n’)
  • HPTP - High Priority Thread Pool (name pattern is HPTP Slot ‘n’)

Other threads are related to JavaFX platform, JRebirth only creates one thread and two Thread Pools.

JRebirth Thread Pool and High Priority Thread Pool have the same size, computed like this:

  • Number of available Core * threadPoolSizeRatio parameter

The default parameter value is 2, so each thread pool will have a size of 16 on Core i7 (Quad Core with HyperThreading). You can use a double value to divide this amount if you think that it can disturb your platform performances (0.250 value will only provide a thread pool size of 2 on a such platform).

Obviously a minimum size of 1 will be used if your thread pool ratio is too low or if the platform has not enought cpu cores.

Concurrent Class Diagram

Thread Usage

Each thread shall manage specific tasks, let's see their aims.

JAT

JavaFX Application Thread is the graphical thread of the toolkit, you shouldn't perform long task into it, but you must update all node attached to the displayed scene into it. It's the equivalent of the former EDT (Event Dispatch Thread) in Swing. If you try to update a node attached to the main JavaFX scene outside it you will obtain an ugly Exception.

// Wrong — may throw if label is in the scene
statusLabel.setText("Done");

// Right — marshal to JAT from JTP or JIT
JRebirth.runIntoJAT(() -> statusLabel.setText("Done"));
  • Any mutation on nodes attached to the displayed scene must run on JAT.

JIT

JRebirth Internal Thread is the internal thread of JRebirth Application Framework. It will be used to host the communication engine between all JRebirth Components. If you start a long task into it it will freeze all communication tasks because all runnable added will be executed synchronously according to FIFO rule (First-In First-Out).

// Safe on JIT — register listeners, send waves
listen(MyWaves.DO_REFRESH);
sendWave(MyWaves.DO_REFRESH);

// Risky on JIT — blocks all messaging until perform() returns
getCommand(HeavyCommand.class).run();
  • listen / sendWave belong on JIT — the Notifier rejects calls from other threads.
  • Never run long work directly on JIT; use JTP commands or services instead.

JTP

JRebirth Thread Pool is designed to perform all other long task your application require, you just have to remember that any graphical update still require to be done into JAT. Moreover any JRebirth internal configuration must be performed into JIT (ie: listen a WaveType).

@RunInto(RunType.JTP)
public class ParseFileCommand extends DefaultCommand {

    @Override
    protected void perform(final Wave wave) {
        final List<String> lines = readAllLines(pathFrom(wave));
        sendWave(MyWaves.DO_LINES_LOADED, WBuilder.waveData(MyWaves.LINES, lines));
    }
}
  • @RunInto(JTP) — file I/O and parsing off UI and JIT.
  • Return results via sendWave — Model listeners receive them on JAT automatically.

HPTP

High Priority Thread Pool has been added to be able to assign a priority to a long task. On small platform or when using very long task, the JTP can be overloaded and we should create an higher priority task to trigger an User interface refresh. The HPTP will be used to trigger higher priority task when JTP is full. It has same settings than JTP.

Quick Reference

Task Thread How
Update displayed node JAT @RunInto(JAT) or DefaultUICommand
Send/receive waves JIT automatic for listen/sendWave
Heavy computation JTP @RunInto(JTP) or DefaultPoolCommand
Priority task HPTP @Priority(PriorityLevel.Highest) on service
From non-component code any JRebirth.runIntoJAT(...), JRebirth.runIntoJIT(...), JRebirth.runIntoJTP(...)

Example — update a label from background work:

JRebirth.runIntoJAT(() -> statusLabel.setText("Done"));
  • runIntoJAT — marshals the runnable onto the JavaFX Application Thread (safe for scene nodes).
  • Use after JTP/IO completes; never touch attached nodes from JTP directly.

Thread Rules

JavaFX Application Thread (JAT)

JAT is the the graphical thread of the JavaFX toolkit (identical to Swing EDT), all UI tasks must be perform into it only if a direct link can be establish between the graphical component and the displayed scene. So if you call setText(“myText”) on a Text node:

  • You must call it into JAT if the node is displayed or linked to the displayed scene.
  • You can call in whatever thread you want if the node isn't linked to the displayed scene.

JavaFX toolkit let you prepare some tree of node into a separate thread and then attached it to the displayed scene. This is how JRebirth load and display any Model, the PrepareModelCommand will run into JTP to create the Model root Node with all its children. Then the AttachModelCommand will be run into JAT to attach the model root node into another node already displayed into the Scene.

JRebirth Internal Thread

JIT does same things than JAT but for managing communication between JRebirth Components. It mainly manage the JRebirth Notifier. So any call to Notifier outside JIT will raise a new Exception. For a standrad usage it will be totally transparent for you.

But sometimes you can want to trigger a command within JIT to be sure it will be executed before another wave is handled. This is a really risky task, do it on your own responsability.

JRebirth Thread Pool

JRebirth provides 2 thread pools to run long task asynchronously without freezing neither the User Interface (JAT) nor JRebirth Messaging (JIT).

All Wave processing tasks are automatically done into the JIT.

When the JRebirth Framework needs to update UI (thanks to Model area), it's done automatically done into the JAT. No matters to have !

But when you call a component directly (synchronous method: getCommand, getService, getModel), your call is processed into the current thread, so you must pay attention to what you are doing.

Examples

If you are into the JIT

  • getCommand => the code will be processed synchronously into JIT, but if you call the run method of the command it will be run into the thread defined by the command configuration.
  • getModel => all called methods of the model will be processed into the JIT ==> Can Break !!! Toolkit will raise an error if any node displayed within the current scene is updated.
  • getService => all methods called of the service will be processed into the JIT, can dramatically slow down messaging.

When you are into the JIT you can use JRebirth.runIntoJAT that call internally Platform.runLater to perform UI updates.

JRebirth.runIntoJAT(() -> view().statusLabel().setText("Ready"));
  • runIntoJAT(Runnable) — preferred over raw Platform.runLater in JRebirth apps.
  • Call from JIT/JTP after async work completes.

JRebirth Framework offers some default commands to do the trick (DefaultUiCommand). Moreover if you send a Wave with a WaveType listened by a model, it will be automatically processed into the JAT (Cool JRebirth Magic).

If you are into the JAT

  • getCommand, getService => this code will be processed into JAT: Don't perform long task or you will freeze the application !!!
  • getModel => actions will be done synchronously into JAT ==> tolerated for short UI actions

When you are in the JAT you must use JRebirth.runIntoJIT that call internally JRebirthThread.runLater to run tasks into the core thread. You can also use JRebirth.runIntoJTP to run task within a slot of available thread pool.

// From JAT — schedule messaging work on JIT
JRebirth.runIntoJIT(() -> sendWave(MyWaves.DO_BACKGROUND_START));

// From JAT — offload heavy work to JTP
JRebirth.runIntoJTP(() -> parseLargeFile(file));
  • runIntoJIT — wave registration and sendWave must not run on JAT directly.
  • runIntoJTP — background work without blocking the UI thread.

JRebirth Framework offers some default commands to force to run into JIT & JTP (DefaultCommand and DefaultPoolCommand). You can also send a wave that will trigger a command, or call a service into another thread that JAT.

Run Synchronously

Sometimes you want to run a task within another thread but synchronously. It's a bad idea but can be required in some particular cases. You can use custom methods:

  • JRebirth.runIntoJATSync
  • JRebirth.runIntoJITSync
  • JRebirth.runIntoJTPSync

Each will wait synchronously the end of the task run within the wanted thread.

JRebirth.runIntoJATSync(() -> {
    previewPane.getChildren().setAll(buildPreviewNodes());
});
// continues on calling thread only after JAT work completes
  • Sync variants block the caller until the target thread finishes — use sparingly.
  • Prefer async runIntoJAT + return wave for service-style flows.

Use Case

If you want to call a service which make an asynchronous call to a remote server. You can use a Service Task method to initiate the call (By default this call will be managed into JRebirth Thread Pool: JTP), but the return must be managed into the JAT:

  • Either use a wave to send data received from remote server, default service will generate a such wave (automatically processed into the JAT for models that listen it)
  • Either call the model from the JAT and access to service results (the first way way is the best to use)

Wave customization

When components communicate using Wave, any Wave handler method can be managed in a specific thread by using @RunInto annotation.

The default behavior is:

  • Into JAT for Model
  • Into JIT for Service
  • Into JIT for Command

3 kinds of Wave are managed differently (not customizable) because they trigger special Component interaction:

  • attachUI => always into JAT
  • returnData => always into JTP
  • callCommand => Depends on Command called

Use @RunInto(value = RunType.JAT) on your wave handler method to override the default thread. For example, a Service method that needs to update UI directly can be annotated with @RunInto(RunType.JAT) to force execution on the JavaFX Application Thread regardless of the component's default behavior.

@RunInto(RunType.JAT)
public void doUpdateLabel(final String text, final Wave wave) {
    view().statusLabel().setText(text);
}
  • Overrides default handler thread (Models → JAT by default; Services → JIT).
  • Still declare listen(...) or @OnWave — annotation only affects where the handler body runs.