[concurrency-interest] Synchronizing on AtomicBoolean safe?

Tim Peierls tim at peierls.net
Wed Jun 29 12:30:28 EDT 2005


This will work, but why use AtomicBoolean at all? There is no intrinsic 
relationship between the monitor lock associated with an object and that 
object's state. It's simpler to use a plain boolean guarded by the 
containing object's monitor lock:

   /**
    * Class invariant:
    * protocolSupportEnabled is true iff propertyChangeMulticaster
    * contains protocolListener on its list of listeners.
    */
   public synchronized boolean enableProtocolSupport(boolean enable) {
       if (enable)
           ... add protocolListener ...
       else
           ... remove protocolListener ...
       boolean old = protocolSupportEnabled;
       protocolSupportEnabled = enable;
       return old;
   }

   public synchronized boolean isProtocolSupportEnabled() {
       return protocolSupportEnabled;
   }

   /** Guarded by this object's monitor lock */
   private boolean protocolSupportEnabled = false;

   /** Listener list state guarded by this object's monitor lock */
   private final PropertyChangeMulticaster propertyChangeMulticaster;

If for some reason you can't (or don't want to) use the containing object's 
monitor lock, you could use instead, for example:

  synchronized (protocolListener) { ... }

instead of synchronized methods.

--tim


Nikolai V. Chr. wrote:
> Is this sane? If not, how could I do it? I used to use getLock() on 
> Lea's old SynchronizedBoolean.
> 
> AtomicBoolean protocolSupportEnabled = new AtomicBoolean(false);
> 
> synchronized(protocolSupportEnabled) {
>   old = protocolSupportEnabled.getAndSet(enable);
>   if(enable) {
>      propertyChangeMulticaster.addPropertyChangeListenerIfAbsent(protocolListener); 
>   } else {
>      propertyChangeMulticaster.removePropertyChangeListener(protocolListener);
>   }
>   logProtocolSupportEnabled(enable);
> }




More information about the Concurrency-interest mailing list