Synchronizing on AtomicBoolean?

1.3k views Asked by At

In an application I'm working on I found the following code snippet:

public class MyClass {

    private AtomicBoolean atomicBoolean = new AtomicBoolean(false);

    public void Execute() {
        // Whole lot of business logic
        // ....
        synchronized (this.atomicBoolean) {
            // Want to make sure that execution is stopped if Stop() was called
            if (this.atomicBoolean.get()) {
                throw new SpecificException("...");
            }
            // Some more business logic...
         }
     }

    public void Stop() {
        synchronized (this.atomicBoolean) {
            this.atomicBoolean.set(true);
        }
    }
}

According to FindBugs this is not correct as I can't use an AtomicBoolean together with synchronized and expect it to block the object.

My question is: What is the correct way to rewrite this methods? I've read about using an lock Object together with a boolean attribute instead but it appears kinda clumsy to introduce two new attributes for this lock.

Edit: As stated in a comment below: I think the intention is that in the two synchronized blocks, the AtomicBoolean can't be changed and that while one Thread is in one of the synchronized blocks, none other such block could be entered.

2

There are 2 answers

8
Eugene On BEST ANSWER

just replace the synchronized (this.atomicBoolean) { part from both methods, AtomicBoolean::get and AtomicBoolean::set is already atomic.

0
Solomon Slow On

...I can't use an AtomicBoolean together with synchronized...

For whatever it's worth, the language allows you to synchronize on any object.

As a matter of style, some programmers prefer to only synchronize on a private object that is used for no other purpose.

private static Object foobarLock = new Object();
...
public void fooItUp(...) {
    ...
    synchronized(foobarLock) {
        ...
    }
    ...
}

...and expect it to block the object

Just to be clear, when some thread T enters a synchronized (o) {...} block, that does not prevent other threads from accessing or modifying the object o. The only thing it prevents is, it prevents some other thread U from entering a synchronized block on the same object o at the same time.