Tip #2: How to runAndWait with JRebirth Thread Engine

Last week I saw an interesting blog entry from Kynosarges that deal with the missing feature Platform.runAndWait(…) that was available into Swing.

While I was reading it, I figure that JRebirth Thread Engine already does the job !!!

As a remember JRebirth Application framework provides 4 kinds of threads:

  • JAT ==> JavaFX Application Thread to perform all graphical updates
  • JIT ==> JRebirth Internal Thread (perform JRebirth wave registration and other custom internal stuff)
  • JTP ==> First Thread Pool (perform long task)
  • HPTP ==> Second Thread Pool to perform higher priority task

Let’s see how to do run a UI task and wait before doing something else, we will play with some JRebirth Commands, the threading engine is totally hidden from developer sight.

You just need to create a sequential MultiCommand.
Each sub command will be triggered only when the previous is achieved whatever the thread used to run it.

We will append to it 2 commands:

  • UICommand (will do the graphical update)
  • LongCommand will perform a long task into a thread pool

The MyMultiCommand simply references other sub-commands.

@Sequential
public class MyMultiCommand extends DefaultMultiCommand {

	@Override
	protected void manageSubCommand() {
		addCommandClass(UiCommand.class);
		addCommandClass(LongCommand.class);
	}
}

The UICommand will show a stage and then close it before writing a trace into the console

public class UiCommand extends DefaultUICommand {

	@Override
	protected void perform(Wave wave) {

		Stage s = new Stage();
		s.show();
		s.close();
		System.out.println(“ui command done”);
	}
}

The LongCommand will lock the current thread 2 seconds before writing a trace into the console. Note that the sleeping thread will be one provided by JTP (It will NOT lock the JAT neither the JIT).

public class LongCommand extends DefaultCommand {

	@Override
	protected void perform(Wave wave) throws CommandException {
		try {
		Thread.sleep(2000);
		} catch (InterruptedException e) {
		e.printStackTrace();
		}
		System.out.println(“long command done”);
	}
}

You can call this command during the application preBoot phase (in example) of your JRebirth Application Class like this:

@Override
public List getPreBootWaveList() {
    return Collections.singletonList(WaveBase.callCommand(MyMultiCommand.class));
}

(otherwise you can simply call your command by using callCommand(MyMultiCommand.class) method of any JRebirth Component or send a Wave that will do the same thing.

The long task will be always performed after the end of the UI task.

In a near future we will see how to use method references to be embedded into JRebirth command to provide a dynamic way to chain dynamic Commands (by writing less classes, and so less code), thanks to Java 8.

One thought on “Tip #2: How to runAndWait with JRebirth Thread Engine

Leave a Reply