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.
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.