[concurrency-interest] Synchronizing on AtomicBoolean safe?

Tim Peierls tim at peierls.net
Thu Jun 30 11:00:00 EDT 2005

Nikolai V. Chr. wrote:
> Sometimes I wish to just set a value on it, using set(). And I was 
> hoping that while I was synchronizing on the AtomicBoolean, I was 
> synchronizing on the same same object that AtomicBoolean was 
> synchronizing on.

AtomicBoolean doesn't synchronize on *any* value. The set() method executes 
atomically without obtaining a lock. That's a feature, not a bug. :-)

> Just like doing this would do:
> SynchronizedBoolean protocolSupportEnabled = new SynchronizedBoolean(false);
> synchronized(protocolSupportEnabled.getLock()) {
>  old = protocolSupportEnabled.set(enable);
>  if(enable) {
>     propertyChangeMulticaster.addPropertyChangeListenerIfAbsent(protocolListener); 
>  } else {
>     propertyChangeMulticaster.removePropertyChangeListener(protocolListener);
>  }
>  logProtocolSupportEnabled(enable);
> }
> And somewhere else I would do this at the same time:
> protocolSupportEnabled.set(true);
> And then expect them to lock on the same Object. The question is, will 
> the previous posted code do the same?

No. I'm not sure what behavior you are trying to support, but you cannot 
simply replace SynchronizedBoolean with AtomicBoolean and synchronize on 
the AtomicBoolean instance itself instead of SynchronizedBoolean.getLock().

It's worth repeating: There is no intrinsic relationship between the 
monitor lock associated with an object and that object's state.

Use the AtomicX classes when their state is independent of the rest of the 
containing class's state.

I suggested using plain boolean and synchronization because I was assuming 
a class invariant that tied the value of protocolSupportEnabled to whether 
propertyChangeMulticaster contained protocolListener.

But since you say you can set protocolSupportEnabled's value independently, 
that invalidates my assumption, and now I don't see why you need *any* 
synchronization if protocolSupportEnabled is AtomicBoolean. 
(PropertyChangeMulticaster uses CopyOnWriteArrayList, so it's safe.)


More information about the Concurrency-interest mailing list