Example of LockSupport in Java
December 27, 2012
1. LockSupport belongs to the package java.util.concurrent.locks. It is available from jdk1.5.
2. LockSupport works on the basis of permit which is handled by Semaphore.
3. LockSupport hs the basic methods as
park(): On call of park, current thread is made available for thread scheduling.
unpark(): On call of unpark, the opposite task of park method is done and thread is made available if it not already available.
package com.concretepage; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.LockSupport; public class LockSupportTest { private AtomicBoolean atLocked = new AtomicBoolean(false); private QueuewaitingThraeds = new ConcurrentLinkedQueue (); public void lockRes() { Thread current = Thread.currentThread(); waitingThraeds.add(current); while (waitingThraeds.peek() != current || !atLocked.compareAndSet(false, true)) { LockSupport.park(); } waitingThraeds.remove(); } public void unlockRes() { atLocked.set(false); LockSupport.unpark(waitingThraeds.peek()); } }