Return to site

☕🎓JAVA CERTIFICATION QUESTION: ReentrantLock

· java,ocp

In pursuit of thread safety, they implemented the following locking mechanism:

 

Which statement is correct about this code? Choose one.

* It consistently prints 12 to console.

* It might print 12 to console.

* It consistently throws an exception.

* It might throw an exception.

* It prints nothing, hanging indefinitely.

 

#java #certificationquestion #ocp

 

Answer:

Consider the computation performed by the block lambda in the map step of the stream.

It takes its argument, v, copies that value to the local variable res, and then returns the value of res.

Notice that the increment operator used on v is a postincrement operator.

As a result, the numbers that are in the stream at the point of the sum() operation are 1, 2, and 3.

Therefore, if any value is printed, it could only be 6.

This tells you that options with 12 output must be incorrect.

Now consider the locking behavior.

The tryLock method never blocks

—if the lock cannot be obtained, the method immediately returns false, and execution proceeds with no lock held.

On the other hand, if the lock is obtained successfully, the method returns true and, as before, continues without blocking.

Because tryLock never blocks, you can determine that option "It prints nothing, hanging indefinitely." must be incorrect;

there’s no reason for the code to hang indefinitely.

Now you get to the crux of the question. If an unlock call is made on a ReentrantLock that is not in the locked state, it throws an IllegalMonitorStateException.

You must decide whether this will definitely happen or is simply a possibility.

Looking at the code, it’s easy to imagine that as the three numbers arrive at the map method, they could do so with a timing that simply results in three nonoverlapping sets of calls: tryLock, unlock; tryLock, unlock; and tryLock, unlock.

If that sequence happens, no exception will arise.

This means that the exception might arise but is not guaranteed. From this you know that option "It might throw an exception." is correct because the code might throw an exception.