Home  >  Core Java

Example of LockSupport in Java

By Arvind Rai, 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 Queue waitingThraeds = 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());
	   } 
	 }
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us