When a deadlock occurs I want to interrupt the blocking thread ...
You could implement a periodic task to check for deadlocks (where deadlocks are java intrinsic or Lock
based) and call interrupt
on all threads involved in the scenario. However, this has no guarantees that it will solve your problem. Its likely the scenario that will just happen again. See Dr Heinz's article on a deadlock detector for details.
If fact, there is no guarantee that interrupt
will even free up a blocked process like this. Its a far better approach to avoid the deadlock scenario in the first place by, for example, using locks with timeouts and retry strategies or 'try before you buy' approaches.
and I want to log the stack trace of this thread...
If you want to do this programatically, again, follow Dr Heinz's example. If not, just generate the thread dump when you've spotted the problem.
Is there any way how can we find the stack trace of a thread outside of that thread in Java?
Yes and no. You can dump the threads from other VMs but their stack traces may not be as useful as you might think to determining the causes of your deadlock. If a genuine deadlock has been detected (by the JVM itself on thread dump of your applications VM) you should have everything you need to debug the cause (more or less).