What happens when two threads try to access a synchronous block?

advertisements

What happens, when two threads try to access a synchronized block?

Will one of the threads be queued somewhere and access the thread later, or will the thread give up if the trial fails?


Assuming you mean a synchronized block, one thread will manage to acquire the monitor, and the other thread will block until the monitor is released.

See section 14.19 and section 17.1 of the JLS for more details, including:

The synchronized statement (ยง14.19) computes a reference to an object; it then attempts to perform a lock action on that object's monitor and does not proceed further until the lock action has successfully completed. After the lock action has been performed, the body of the synchronized statement is executed. If execution of the body is ever completed, either normally or abruptly, an unlock action is automatically performed on that same monitor.

(Emphasis mine.)

If you need any other semantics - e.g. timeouts - you should use one of the the types in the java.util.concurrent.locks package, so that you can use methods such as tryLock() and tryLock(long time, TimeUnit unit).