Can anyone explain how to use Reentrant Lock in java via Synchronized with some best examples

3 answers

Here are three ways, methods, a thread accessing a lock, and one to release a lock. You might want to apply them using the synchronized . The advanced features and benefits of using ReentrantLock will become apparent.

 public class DoorLockUsingLock { private int counter= 0; private Thread owner= null; private Lock l = new ReentrantLock(); private Condition notLocked= l.newCondition(); public void lockItDown() throws InterruptedException { l.lockInterruptibly(); try { while ((counter> 0) && (owner!= Thread.currentThread())) { notLocked.await(); } counter++; owner = Thread.currentThread(); } finally { l.unlock(); } } public void lockItDownUninterruptibly() { l.lock(); try { while ((counter > 0) && (owner != Thread.currentThread())) { notLocked.awaitUninterruptibly(); } counter++; owner= Thread.currentThread(); } finally { l.unlock(); } } public boolean tryLockItDown(long timeout, TimeUnit unit) throws InterruptedException { long time = unit.toNanos(timeout); long end = System.nanoTime() + time; boolean success = l.tryLock(timeout, unit); if (!success) { return false; } try { time = end- System.nanoTime(); while ((counter> 0) && (owner != Thread.currentThread()) && (time > 0)) { notLocked.await(time, TimeUnit.NANOSECONDS); time = end - System.nanoTime(); } if (time > 0) { counter++; owner = Thread.currentThread(); return true; } return false; } finally { l.unlock(); } } public void unlockIt() throws IllegalMonitorStateException { l.lock(); try { if (counter== 0) { throw new IllegalMonitorStateException(); } if (owner!= Thread.currentThread()) { throw new IllegalMonitorStateException(); } counter--; if (counter == 0) { owner = null; notLocked.signal(); } } finally { l.unlock(); } } } 
+6
source

From the JavaDoc of the ReetrantLock class :

Repeated mutual exclusion of Lock with the same basic behavior and semantics, since access to the implicit monitor is carried out using synchronized methods and statements, but with advanced features.

In your example, you are not using "advanced features"; you use ReentrantLock as an equivalent alternative to the synchronized method (except that you use this as a lock with the synchronized operator). Thus, both methods should behave the same.

+2
source

No, you will not see a difference in behavior at all. But, as the website says, there are several cases when you want to use ReentrantLock instead of synchronized .

  • You want pending threads to be sufficiently selected.
  • You want to use the tryLock () method.
  • You want to interrupt the waiting thread and force it to do something else.
  • The performance of ReentrantLock is better than synchronized, and you care about that.

If you do not need any of these improvements, using synchronized is fine, and you cannot tell the difference.

0
source

Source: https://habr.com/ru/post/952675/


All Articles