Hello,
I'd rather use the compareAndSet method in AtomicReference for this particular task. On Sun, Sep 26, 2010 at 4:00 PM, Ohad Shacham <ohad.shac...@gmail.com>wrote: > Hi, > > > In addition to the behavior we experienced in function setAttribute. We > also > experienced another atomicity violation in function removeAttribute. > > The following code is located at the beginning of function removeAttribute > at class ApplicationContext. This code fragment intends to check whether a > key is already inside the “attributes” collection. If it does, then the key > is removed from the collection and the function continues running while > assigning the corresponding value to “value”. Otherwise, the function > should > return. > > > > > found = attributes.containsKey(name); > > if (found) { > > value = attributes.get(name); > > attributes.remove(name); > > } else { > > return; > > } > > > > This code can behave non atomically when two different threads call > removeAttribute function with the same attribute name. In this case, there > exists a thread interleaving where two threads enter the “if” condition > while the first one removes “name” from the attributes collection before > the > second one runs the get operation. This causes the function to continue > running with value == null instead of returning. > > > > Could you please let me know whether you consider this as a bug? > > > > A possible way of modifying the code in order to execute this code > atomically is as follows: > > > > if (attributes.containsKey(name)) { > value = attributes.remove(name); > if (value == null) > return; > } > > > > Thanks, > > Ohad > -- Sincerely yours and Best Regards, Xie Xiaodong