Reputation: 5073
I noted the following a piece of code:
synchronized (this) {
if (executed) throw new IllegalStateException("Already executed.");
executed = true;
Is it pointless? After all, it is synchronized, so why it is if (executed) throw new IllegalStateException("Already executed.");
?
Upvotes: 0
Views: 65
Reputation: 116918
I noted the following a piece of code ... Is it pointless?
Depends a lot on the context of course but at face value, the code does a very specific and useful thing. So (uh) point-full I guess.
The code ensures that the code below the synchronized
block is executed only once. This is obviously in a multithreaded application. You could argue that all you need for this is an AtomicBoolean
of course:
private final AtomicBoolean executed = new AtomicBoolean();
...
// make sure that this is only executed once
if (!executed.compareAndSet(false, true)) {
throw new IllegalStateException("Already executed.");
}
The above code removes the need for a synchronized
block, but the effect of the code is the same. I might also argue that the code should return some sort of error code instead of throwing but that is an implementation specific detail.
Hope this helps.
Upvotes: 1
Reputation: 4120
It is not pointless.
synchronized means only one thread can execute that code at any point of time. others will wait.
So at the beginning executed is "false". First thread reaches that code and makes it true.
Second thread is waiting...
When second thread reaches that code execute is "true" and second thread throws exception.
Upvotes: 0