简体   繁体   中英

Java thread visibility - best practice for visibility without explicit synchronization

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, eg), right? If yes, how to force visibility without using synchronized?

Thanks.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM