Lock in Java

In the previous post (Synchronized vs ReentrantLock in Java) ,  we have discussed the difference between synchronized and ReentrantLock. The keyword synchronized can be widely used in many multi-threaded environments. However, there are some drawbacks when using synchronized. The use of keyword synchronized provides access to the implicit monitor lock associated with every object, but forces all lock acquisition and release to occur in a block-structured way: when multiple locks are acquired they must be released in the opposite order, and all locks must be released in the same lexical scope in which they were acquired. In short, when the keyword synchronized locks a block, and a thread is in the block, other threads have to wait and will be blocked until that thread exits the block. It will slow down the performance. In some situations, it may leads to a deadlock.

Lock implementations provide more extensive locking operations than using synchronized methods and statements.

  • lockInterruptibly() – Acquires the lock unless the current thread is interrupted.
  • tryLock() – Acquires the lock only if it is free at the time of invocation.
  • unlock() – Releases the lock

lock_interface

The basic implementation looks like:

Example using ReentrantLock

output:

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on RedditShare on StumbleUponEmail this to someoneShare on TumblrDigg this

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">