Showing posts with label synchronized. Show all posts
Showing posts with label synchronized. Show all posts

Determine thread hold synchronized lock in java

Source code below will print true if current thread hold synchronized lock for current object and print false for otherwise.

*******************************************
COMPLETE SOURCE CODE FOR : DetermineThreadHoldSynchronizedLock.java
*******************************************


//This program will print three value whether current thread hold synchronized lock
//for cuurent object or not.
public class DetermineThreadHoldSynchronizedLock
{
boolean isLock;

public DetermineThreadHoldSynchronizedLock()
{
//Check whether current thread hold synchronized lock for current object
isLock=Thread.holdsLock(this);

//Print lock value
//It should print false
System.out.println("HOLD SYNCHRONIZED : "+isLock);

//Go to method locker()
locker();
}

public void locker()
{
//Current thread get lock from current object
//It's mean other thread can't interrupt untill this thread get out from
//synchronized block,{}...like below
synchronized (this)
{
isLock=Thread.holdsLock(this);
//Print lock value
//It should print true
System.out.println("HOLD SYNCHRONIZED : "+isLock);
}
lastCheck();
}

public void lastCheck()
{
//Check whether current thread hold synchronized lock for current object
isLock=Thread.holdsLock(this);
//Print lock value
//It should print false
System.out.println("HOLD SYNCHRONIZED : "+isLock);
}

public static void main(String[]args)
{
DetermineThreadHoldSynchronizedLock dthsl=new DetermineThreadHoldSynchronizedLock();
}
}


*******************************************
JUST COMPILE AND EXECUTE IT
*******************************************

RELAXING NATURE VIDEO