[Solved] How to close threads in Java? [closed]


As noted:

  • You are not using threads, so this it not about threads.

  • You don’t “close” threads. Threads are not closable.

  • You do need to close input/output streams … and you are not doing that in all of places you need to in your program.

But the modern way to close a stream doesn’t involve finally. Way back in Java 7, they introduced the try with resources syntax which will automatically close resources for you. For example:

    try {
        fw = new FileWriter(file, true);
        fw.write(" " + getRandomNumber(1, 100));
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fw != null)
                fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

can be written as

    try (fw = new FileWriter(file, true)) {
        fw.write(" " + getRandomNumber(1, 100));
    } catch (IOException e) {
        e.printStackTrace();
    }

Note that fw will be auto-closed. It is better to make fw a local declaration so that it is out of scope after the statement:

    try (FileWriter fw = new FileWriter(file, true)) {
        fw.write(" " + getRandomNumber(1, 100));
    } catch (IOException e) {
        e.printStackTrace();
    }
    // fw is out of scope.

Also, you don’t need to call flush after each write when you are writing to a file. Any buffered output is written when the output stream / writer is closed. You just need to make sure that the stream / writer is always closed.

solved How to close threads in Java? [closed]