10

How to switch between threads of a suspended program?

or Any tutorial on multi-threaded debugging with Intellij Idea describing basic features - suspend, resume, switch between threads.

very good tutorials/step-by-step guide available for Netbeans: e.g. https://netbeans.org/kb/docs/java/debug-multithreaded.html

Amit G
  • 2,293
  • 3
  • 24
  • 44

2 Answers2

18

Trick is to set breakpoint suspend policy to - Thread. View breakpoint properties (right-click on breakpoint)

breakpoint properties - suspend policy

Once done threads will hit breakpoint and block, now active thread can be switched to check race conditions/deadlocks.

switching between threads

Following code snippet for creating deadlock:

public static void main(String args[]) {
    Thread thread1 = new Thread(null, new MyThread(obj1, obj2), "Thread-1");
    Thread thread2 = new Thread(null, new MyThread(obj2, obj1), "Thread-2");
    thread1.start();
    thread2.start();
}
class MyThread implements Runnable {
    private Object obj1;
    private Object obj2;

    MyThread(Object obj1, Object obj2) {
        this.obj1 = obj1;
        this.obj2 = obj2;
    }

    @Override
    public void run() {
        System.out.println("Acquiring locks");
        synchronized (obj1){
            System.out.println("Acquired 1st lock");
            synchronized (obj2){
                System.out.println("Acquired 2nd lock");
            }
            System.out.println("Released 2nd lock");
        }
        System.out.println("Released 1st lock");
    }
}
Amit G
  • 2,293
  • 3
  • 24
  • 44
  • How in the world did you get to that first screen to set suspend policy – Dean Hiller Aug 04 '20 at 14:46
  • @DeanHiller - View breakpoint properties (right-click on breakpoint). Updated answer. – Amit G Aug 04 '20 at 17:47
  • thanks @Amit G. I thought it was a global setting, heh, but it's hidden there. I thought that would work differently so I posted this question https://stackoverflow.com/questions/63249855/in-intellij-2020-1-when-i-hit-play-in-debugger-how-to-stop-it-from-switching-t – Dean Hiller Aug 04 '20 at 18:52
6

Amit,

You may be interested in an alternative threads view of the call stack, enabled by clicking the 'Restore threads view' button: enter image description here

A bit of documentation around that : Debug Tool Window - Threads

Also, these questions might be useful :

  1. IntelliJ Thread Debug
  2. IntelliJ - pause a thread while debugging
Community
  • 1
  • 1
Ashutosh Jindal
  • 18,501
  • 4
  • 62
  • 91