Pergunta

I think I have a thread leak in my code, but I am not sure why. Here is the code -

foo(String solutionFileName, String SubmissionFileName){
    ExecutorService e = Executors.newFixedThreadPool(
    Future<BufferedReader> f1 = e.submit(new Builder(solutionFileName));
    Future<BufferedReader> f2 = e.submit(new Builder(submissionFileName));
    BufferedReader b1=f1.get();
    BufferedReader b2=f2.get();
    //do a little work
    e.shutdown();
}

class Builder{
    Builder(String fileName){this.fileName=fileName;}
    public BufferedReader call() throws FileNotFoundException{
        return new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
    String fileName;
    }
}

Im running this off Eclipse and the problem is that when I hit a FileNotFoundException the JVM doesnt die. I have to manually terminate it. I dont understand why though...

Foi útil?

Solução

problem is that when I hit a FileNotFoundException

When you hit this exception it seems your exception handler not shutting down ExecutorService. If you don't shutdown ExecutorService, that thread pool will stay there.

Outras dicas

Use a try/finally block:

ExecutorService e = Executors.newFixedThreadPool(10);
try {
    Future<BufferedReader> f1 = e.submit(new Builder(solutionFileName));
    Future<BufferedReader> f2 = e.submit(new Builder(submissionFileName));
    BufferedReader b1=f1.get();
    BufferedReader b2=f2.get();
    //do a little work
} finally {
    e.shutdown();
}

This will cause the shutdown call to be executed no matter how the try block is exited. Your code is throwing the exception, which causes the e.shutdown() line to be skipped (exceptions normally cause all code execution to stop). By adding the finally, you're guaranteeing that no matter how the try block exits, the e.shutdown() is called.

There's one exception. If you do this:

try {
    System.exit(0);
} finally {
    System.out.println("Finally block");
}

"Finally Block" will never be printed because System.exit never returns normally.

The exception is thrown in a separate thread. The thread spawn in the es.call() should die but not the main thread (or the thread running the foo()). And the JVM is still running because the main thread is not died.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top