Machine-translated by Google. Questions are authored in English.
Top

Discussion

Which of these correctly takes and releases a ReentrantLock?

  • A.lock.lock(); try { work(); } finally { lock.unlock(); }
  • B.try { lock.lock(); work(); } finally { lock.unlock(); }
  • C.synchronized (lock) { work(); }
  • D.lock.acquire(); try { work(); } finally { lock.release(); }

Answer: A

The lock is taken before the try so that the finally only runs when it was actually acquired; acquiring inside the try would attempt an unlock even if lock itself threw. ReentrantLock uses lock and unlock, and the synchronized statement does not drive it at all.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.