[concurrency-interest] Synchronizing on AtomicBoolean safe?

Nikolai V. Chr. nikolai at ifad.dk
Thu Jun 30 11:43:54 EDT 2005


Tim Peierls wrote:

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


Okay, thanks for the answers. (allthough I did not understand everything..)

-- 
Nikolai V. Christensen, Computer Engineer,
Simulation and Training department
IFAD TS A/S, Østre stationsvej 43 2.tv, DK-5000 Odense C
Denmark, EU
Phone: +45 63 11 02 11  Fax: +45 65 93 29 99
WWWeb: http://www.ifad.dk
e-mail: Nikolai.V.Christensen at ifad.dk
--




More information about the Concurrency-interest mailing list