Thought experiment: constructing Nodes on a different thread...

Kevin Rushforth kevin.rushforth at oracle.com
Thu Jan 25 14:50:42 UTC 2024


Yes, I think you are missing something. Unless you have an animation 
that just decides all on it's own to find and attach a newly discovered 
node to the scene and start rendering it, there will be a 
synchronization as a result of calling runLater. Consider the following 
code:

     Label label = new Label();
     label.setText("hi");

     // Attach it to the scene on the FX thread.
     Platform.runLater(()  -> root.getChildren().add(label));

The "runLater" necessarily synchronizes with the FX Application thread 
so that the runnable can be put on its queue and later taken off the 
queue and executed on the FX Application thread. As specified in the 
Platform::runLater API docs: Actions in a thread prior to submitting a 
runnable to this method happen-before actions performed by the runnable 
in the JavaFX Application Thread.

So I don't see the problem.

-- Kevin


On 1/25/2024 1:50 AM, John Hendrikx wrote:
> All this threading talk has made me wonder something:
>
> Let's say there are two threads, the FX thread and Thread 1.  I do the 
> following:
>
> - On thread 1: create Label
> - On thread 1: set Label text to "xyz"
>
> I now attach this label to an active Scene graph. This should be done 
> on the FX thread as we're going to be manipulating an active Scene 
> graph, so:
>
> - On FX thread: attach Label to active scene graph
>
> There is no synchronization in place on the Label's text field. What 
> guarantees do I have that when the label is shown on screen it will 
> show "xyz" ?
>
> IMHO, there is no such guarantee, and so any creation or manipulation 
> of Nodes that will later be part of an active scene graph (and thus 
> accessed by the FX thread) **must** be done on the FX thread.  
> Involving any other thread in their creation or manipulation runs the 
> risk of seeing an object in the incorrect state (or even an 
> "impossible" state when multiple fields are involved that normally 
> change together).
>
> Effectively, assuming that when you create Nodes you always have the 
> intention of showing them at some point, you can never construct Nodes 
> on any other thread than the FX thread...
>
> Am I missing something?
>
> --John
>



More information about the openjfx-dev mailing list