Reputation: 11569
Is it dangerous for the standard implementations of Property
in JavaFX to call set methods from multiple threads? I don't really care about race conditions on the client side from reading-and-then-setting operations. I want to know if the Property
itself can be corrupted internally if multiple threads call its set()
or setValue()
method.
Is this code below threadsafe?
public class ThreadSafeProperty {
public static void main(String[] args) {
ObjectProperty<Integer> property = new SimpleObjectProperty<>(5);
ExecutorService exec = Executors.newFixedThreadPool(5);
property.addListener((obs,o,n) -> System.out.println("OLD: " + o + " NEW: " + n));
exec.execute(() -> property.set(4));
exec.execute(() -> property.set(6));
exec.execute(() -> property.set(11));
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
exec.shutdown();
}
}
Upvotes: 2
Views: 983
Reputation: 1643
SimpleObjectProperty is not thread safe.
You see this in the source: javafx/beans/property/ObjectPropertyBase.set is not synchronized, or you use a tool like http://vmlens.com witch looks for you:-)
Upvotes: 1