Reputation: 377
I need to share some global states (button status) between EDT and a bunch of worker threads. When the EDT changes the value, it needs to appear immediately in all other worker threads. I have designed a singleton class with Java enum as follows:
public enum ButtonState {
INSTANCE;
private volatile boolean showPhase = false;
public boolean showPhase() {
return showPhase;
}
public void setShowPhase(boolean showPhase) {
this.showPhase = showPhase;
}
}
//Client Code:
if (ButtonState.INSTANCE.showPhase()) {
// show phase
// do stuff
ButtonState.INSTANCE.setShowPhase(false);
}
showPhase
volatile?Upvotes: 0
Views: 126
Reputation: 2626
It depends upon your use case if only requirement is to shared flag among the multiple thread your approach looks correct and thread safe as you are using volatile.So the change value will be visible to all thread.This is a pull model all worker thread needs to be access the flag by there own.
Or you can use push based model as suggested above to use Observer patter to push to all worker thread any changes in the flag.I think 2nd approach is good as it will notify the worker immediately and all thread will get the notification same time.In your approach may be there will be a delay .
Upvotes: 1