简体   繁体   中英

Multithreaded debugging in java

I have a program that runs about 50 threads . I employ a producer consumer design pattern to communicate data between the threads. After the program has been running for a while, sometimes it freezes due to one of the BlockingQueue's I use to distribute data between the threads becomes full, and therefore the main distribution part of the program blocks when it tries to add data to this BlockingQueue. In other words, one of the threads stops for some reason and then the blockingQueue it uses to receive data becomes full.

How do I go about debugging this in an efficient manner? I have tried surrounding the content in all run() methods with catch(Exception e) , but nothing is ever thrown. I develop in Java/IntelliJ .

Any thoughts, ideas or general guidelines?

"Debug it" by using a logger. I like SLF4J .

Set up log.debug statements before and after each critical operation. Use log.entering and log.exiting calls at the start and end of each method.

While you are 'debugging' you'll run your application with the logger set to a very low level (FINEST) then run your application and watch the logging statements to learn when it fails and what the state is when it fails.

Since you're worried about a threading issue, make sure your log format includes the thread name or number.

general guidelines?

I don't know if this applies to your situation, but a very important guideline is to never have locks being taken in different orders.

An example:

Thread 1:

ResourceA.lock();
ResourceB.lock();
...
ResourceB.unlock();
ResourceA.unlock();

Thread 2:

ResourceB.lock();
ResourceA.lock();
...
ResourceA.unlock();
ResourceB.unlock();

Now if thread 1 is interrupted when it already owns ResourceA but not yet ResourceB , and thread 2 is allowed to run, thread 2 will take ResourceB . Then thread 1 owns ResourceA and waits for ResourceB , and thread 2 owns ResourceB and waits for ResourceA , so you have a deadlock.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM