Luca
Luca

Reputation: 1766

Java Lock.lock() and Lock.lockInterruptibly()

I would like to know how locks are implemented in Java. In some tutorials I found that they should be implemented using wait() and notify()/notifyAll() and some boolean flags (it might be much more complicated than that,but basically that should be like that)

class SimpleLock {

  private boolean locked=false;

  public synchronized void lock() throws InterruptedException {
    while (locked)
      wait();
    locked=true;
  }

  public synchronized void unlock() throws InterruptedException {
    locked=false;
    notify();
  }

} 

but I know that interface Lock defines two methods, Lock.lock() that can't be interrupted and Lock.lockInterruptibly() that can and throws InterruptedException in order to deal with the evenience.

If locks were implemented using wait(),shouldn't them be interrupted by a call to Thread.interrupt() ?

So how are locks really implemented? I think that they're based on other Java low-level synchronization facilities (like synchronized and wait()/notify()), but I don't know how.

Upvotes: 2

Views: 1129

Answers (1)

dezhik
dezhik

Reputation: 1030

Locks are implemented using other technique. They use AbstractQueuedSynchronizer under the hood. It uses LockSupport.park() which calls Unsafe's public native void park(boolean var1, long var2).

Actually threads waiting in Lock.lock() could still be interrupted, but this wouldn't be shown to a user, because InterruptedException won't be thrown. Thread will wake up after interruption, then clear interruption flag and try to acquire the same lock again.

The Lock.lockInterruptibly() acts another way, when interruption occurs it will throw an exception, so user can handle it the way he desires.

Upvotes: 5

Related Questions