0

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.");?

2
  • 1
    What are the scope and the lifetime of executed? That's a critical piece of information here. Commented Dec 13, 2016 at 18:53
  • stackoverflow.com/questions/13356702/… Commented Dec 13, 2016 at 19:19

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

3 Comments

are you sure... ?
Hmm. I may have read this answer and that question a bit quicker than I should have.
No problem ... :-) There is just assumption that executed is static or instance variable of singleton object used by multiple threads at the same time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.