Search code examples
javamultithreadingsynchronize

Executing a code when thread gets Blocked by Intrinsic Lock


Is there any way to run a piece of code when a thread accesses a locked object ?

public class Student implements Runnable {

private String name;
private Workshop w;

public Student(String name,Workshop workshop) {
    this.name = name;
    this.w=workshop;
}

@Override
public void run() {

    this.w.getReady();
    this.w.file(this.name);
    this.w.cut(this.name);
    this.w.punch(this.name); //Synchronized Method

    if(Thread.currentThread().getState()==Thread.State.BLOCKED)
        System.out.println(this.name+" is waiting in queue");

    System.out.println(this.name+" has finished and is going home");
}

}

This is a simulation for a Workshop scenario where each and every student has to file,cut and punch the metal workpiece.
Since punching is turn by turn, I have declared it as synchronized, as every student (thread) will have to wait for their turn to punch.
All I want to know is,if there some in-built method or a way to write a method that gets executed when a thread gets blocked and is waiting for the intrinsic lock to be unlocked.

Example

public void onBlock() {
    System.out.println(this.name+" is waiting in queue");
    ...
}

Solution

  • For object monitors protected by synchronized, no, it either successfully locks or it blocks indefinitely waiting for a lock.

    If you're using a ReentrantLock or the like, you have more options:

    1. You can wait indefinitely, just like object monitors, by calling lock.
    2. You can wait for a limited amount of time by calling tryLock with a timeout value.
    3. You can immediately return if the lock is unavailable by calling tryLock with no arguments.