Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaFX, is an observableArrayList thread safe?

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?

like image 277
user2312688 Avatar asked Sep 10 '15 09:09

user2312688


People also ask

Why is JavaFX not thread safe?

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.

Is ObservableList thread safe?

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!

Which class is thread safe?

The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.

What is ObservableList in JavaFX?

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.


1 Answers

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.

like image 173
James_D Avatar answered Oct 25 '22 03:10

James_D