Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I diagnose the source of orphaned threads in Java?

I'm writing a piece of video analysis software using Java and the Xuggler library. My code is all single threaded, but some of it is being called from a Xuggler thread.

I have to process a directory full of video files, so I iterate through the files and for each one I start an instance of IMediaReader then process the frames. When I'm finished I detach the listener and close the reader. Like this:

public void ProcessFrames(VideoFile file, MediaProcessor processor, int ImageType) 
{
    IMediaReader mediaReader = ToolFactory.makeReader(file.location);
    mediaReader.setBufferedImageTypeToGenerate(ImageType);  

    mediaReader.addListener(processor);
    mediaReader.open();
    IError videoDecodeError = null;
    while (videoDecodeError == null && 
           processor.isListenerFinishedWithStream() == false)
    {
        try {
            videoDecodeError = mediaReader.readPacket();
        } catch(Exception ex) {
            ex.printStackTrace();
        }
    }       

    System.out.println("Closing media reader.");
    mediaReader.close();
    mediaReader.removeListener(processor);
}

I've noticed that every time I create a new IMediaReader it seems to leave a thread open and just hanging around. The problem is that I can't seem to find any information about the orphaned threads. In Eclipse they show up as "Thread [Thread-2] (Running)".

I can't find any information about where the thread is stuck, or what spawned it to begin with. I attached VisualVM to see if it would tell me what's going on. The graph is pretty informative, but it doesn't answer my question:

VisualVM showing thread leak

VisualVM shows the threads being created, but they never close. Neither Eclipse or VisualVM tell me any information about where the threads were created or what they're doing.

How do I determine where a thread was created? How do I prevent them from being orphaned like this?

Many Thanks!

EDIT: I've added a screencap of Eclipse's threads tree when I pause the application.

Eclipse threads window

like image 810
zorlack Avatar asked Feb 16 '26 06:02

zorlack


1 Answers

Click the pause button in the Eclipse debugger and then expand the threads of interest to see what they were doing at that point in time.

Alternatively (and this does not require a debugger, or even a running process) use the jstack utility in the JDK.

Of course, stack traces do not cross thread boundaries - they won't show you what spawned a thread. But they may help.

If they don't, to find out what is spawning threads, you can put a breakpoint on java.lang.Thread.start().

like image 54
Robin Green Avatar answered Feb 18 '26 19:02

Robin Green



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!