I update a table by modifying an observable array list but now 2 threads might modify the observable array list. Should I place the code that modifies the list in a synchronized method or will only 1 thread be allowed to modify the list anyway?
Thread safety in a JavaFX application cannot be achieved by synchronizing thread actions. We must ensure that the programs that manipulate the scene graph must do so only from the JavaFX Application Thread. Therefore, multithreading in JavaFX has to be handled in a different manner.
ObservableCollection is the recommended collection to use for ListViews, but it isn't thread safe. Let's explore how we can fix this and use it in our multi-threaded apps!
The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.
ObservableList : A list that enables listeners to track changes when they occur. ListChangeListener : An interface that receives notifications of changes to an ObservableList. ObservableMap : A map that enables observers to track changes when they occur.
For this particular use case - where the ObservableList
is bound to a TableView
, you must only access the list from the FX Application Thread. This is because changes to the list will result in changes to the TableView
, and all changes to the scene graph must occur on the FX Application Thread.
So in this case, the question as to whether the ObservableList
is thread safe is a moot point: since you can only access it from a single thread for other reasons, you don't need it to be.
If you have a background thread that needs to update the list, you can schedule those updates to occur on the FX Application Thread by wrapping them in a call to Platform.runLater(...)
, or (and this is probably preferable) by using the javafx.concurrent
API to manage your threading.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With