Search code examples
javamultithreadingiojvm

What can possibly go wrong when halting the JVM while a thread is doing I/O?


I read in this comment

don’t call System.exit(…) if you think there might be running threads doing I/O

Is killing a not-finished I/O operation potentially much worse than killing a, for example, DB transaction?


Solution

  • What can possibly go wrong when halting the JVM while a thread is doing I/O?

    Because if you do, it is difficult to know for sure if the I/O operation completed before the JVM exited. For a read operation that is probably OK, but an incomplete write could result in permanent loss of data.

    Is killing a not-finished I/O operation potentially much worse than killing a, for example, DB transaction?

    Yes, it is worse.

    If you kill a JVM while a database transaction1 is in progress, the database will revert to a consistent state. This should happen even if the JVM is killed without the normal JVM shutdown hooks getting to run. This is implemented by the database writing data to the file system in a controlled way that is resilient to being interrupted; i.e. some combination of atomic writes, and writing things in a specific order. The database may need to do some recovery on restart, but committed data will have been safely saved. (That is the D (durability) in ACID.)


    1 - assuming that the database has ACID properties, and you don't suffer catastrophic media failure.