Reputation:
when having java Threads communicating with each other, but no explicit synchronization is required (so no need to call synchronize on an object to synchronize execution), what is the best practice to ensure proper visibility among involved threads?
For example:
class B extends Thread {
...
A instanceOfA = ...;
B(){
instanceOfA.registerHandler(new Handler(){
@Override
handle(SomeObjectToBeVisibile o){
...
}
});
}
}
class A extends Thread {
...
void registerSomeHandlerMethod(HandlerMethod handler){...}
void executeHandlers(){
for(each registered handler){
handler.handle(instanceOfSomeObjectToBeVisible);
}
}
}
If I am not mistaken, there is a potential visibility problem to the handlers "handle" method calls passing some constructed object which then might not be visible the proper way in the receiving thread (stale values, e.g.), right? If yes, how to force visibility without using synchronized?
Thanks.
Upvotes: 1
Views: 728
Reputation: 45443
Don't be afraid of synchronization, if the synchronized block is small and fast, which is true in your case, lock-unlock won't cause any problems.
You could use a "lock-free" concurrent data structure, like ConcurrentLinkedQueue. (It is not going to be a lot faster for your case)
EDIT: it looks like you are worrying about the visibility of the argument passed to handle()
, not handlers themselves.
Upvotes: 0
Reputation: 12296
It should be possible to use volatile modifiers, however I'd recommend to use AtomicReference
Also if you're passing an object, which is immutable - then no problem would arise at all, since final fields are guaranteed to be initialized before constructor ends it's execution.
Upvotes: 3