Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Analysing a multi-threaded Java application

In an open source application I'm participating, we've got a bug, where the application doesn't always close properly. That's what I'd like to solve.

Experience has shown that this happens most of the time when threads and processes are being started, but not managed correctly (e.g. a thread is waiting on a socket connection, the application is being shut down and the thread keeps on waiting).
With this in mind I've searched for '.start()' in the entire source and found 53 occurrences (which scared me a bit).
As a first step, I wanted to create a helper class (ThreadExecutor) where the current code 'thread.start()' would be replaced by 'ThreadExecutor.Execute(thread)' to have a) only a few changes in the existing source and b) a single class where I can easily check which threads don't end as they should. To do this I wanted to

  • add the thread to be executed to a list called activeThreads when calling the Execute method
  • start the thread
  • remove it from the activeThreads list when it ends.

This way I'd have an up to date list of all executing threads and when the app hangs on shutdown I could see in there which thread(s) is(are) causing it.

Questions:

  • What do you think about the concept? I'm usually coding c# and know how I'd do it using .NET with workers, but am not too sure what's best in Java (I'd like to modify as few lines of code as possible in the existing source).
  • If the concept seems ok, how can I get notified of a thread terminating. I'd like to avoid having an additional thread checking every once in a while what the state of all threads contained in activeThreads is, to remove them if they terminated.

Just to clarify: Before figuring out how to terminate the application properly, what I'm asking here is what's the best/easiest way to find which threads are at cause for certain test cases which are pretty hard to reproduce.

like image 587
Philippe Avatar asked Nov 17 '11 15:11

Philippe


2 Answers

I would attempt to analyze your application's behavior before changing any code. Code changes can introduce new problems - not what you want to do if you're trying to solve problems.

The easiest way to introspect the state of your application with regard to which threads are currently running is to obtain a thread dump. You said that your problem is that the application hangs on shutdown. This is the perfect scenario to apply a thread dump. You'll be able to see which threads are blocked.

You can read more about thread dumps here.

like image 146
Paul Morie Avatar answered Sep 25 '22 13:09

Paul Morie


Try to make all threads daemon(when all remaining threads are daemon the JVM terminates). Use thread.setDaemon(true) before starting each thread.

like image 32
Petar Minchev Avatar answered Sep 23 '22 13:09

Petar Minchev