How to identify name or any contextual info of thread A when it interrupts thread B?

I found one question on similar lines : Interrupt with name identifier [Sigaction – Linux]

  1. How to identify name or any contextual info of thread A when it interrupts thread B?
  2. Even if we get name of thread A, there is chance there could be multiple threads with same name as mentioned here : https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#interrupt– Every thread has a name for identification purposes. More than one thread may have the same name. If a name is not specified when a thread is created, a new name is generated for it.
  3. Does this mean I would have to create custom thread inheriting “java.lang.Thread”?

Code Sample

Thread threadA = new Thread(new Runnable() {
public void run() {
    try {
      Thread.sleep(500);
    } catch (InterruptedException ex) { }
    System.out.println("I am going to interrupt, catch me if you can");
    threadB.interrupt();
  }
});

Thread threadB = new Thread(new Runnable() {
public void run() {
    try {
            System.out.println("threadB going to be interrupted");
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            //How to find name or any contextual info of threadA here?
            Thread.currentThread().interrupt();
        }
    
  }
});

threadB.start();
threadA.start();

If this is not possible directly, is there any workaround or trick?

Answer

I don’t think this would compile as is. For one thing, System.out.println does not throw InterruptedException. I think you have a mistaken idea that calling threadB.interrupt() will cause threadB to throw an InterruptedException. But it won’t: it will only set the interrupt flag. Remember, InterruptedException is a checked exception: it just doesn’t appear out of nowhere, something has to throw it.

So, leaving that aside, how close is your example to what really happens?

If you need to, in general, know “who set my interrupted flag” I don’t think there’s any straightforward way to know that. If you really, really needed to know that, you could use something like Aspect4J and weave in advice on the interrupt() method that saves that information.

But if you have more control over your code (as in the example above), the answer is to use object encapsulation and have B not directly interrupt A, but rather call a method that does. Really, I think this is better practice anyway, since it lets your own code do what it needs to do on the interrupted case. This isn’t tested, but it’s the idea:

static class MyThread extends Thread {
  String interrupter;

  public void interrupt(String interrupter) {
    this.interrupter = interrupter;
    super.interrupt();
  }

  public void run() {
    while (!this.isInterrupted()) {
      // Do the thing
    }
    // Here you can see who interrupted you and do whatever
  }
}