Код: Выделить всё
public class SimpleResourceExample {
public static void main(String... args) {
try (var resource1 = new Resource(1);
var resource2 = new Resource(2)) {
System.out.println("Using "+resource1 +" and "+resource2);
Thread.sleep(20 * 1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private record Resource(int id) implements AutoCloseable {
@Override
public void close() {
System.out.println("Closing resource "+id);
}
}
}
Код: Выделить всё
Using Resource[id=1] and Resource[id=2]
Closing resource 2
Closing resource 1
Process finished with exit code 0
Код: Выделить всё
var t = Thread.currentThread();
new Thread(() -> {
try {
Thread.sleep(10 * 1000);
t.interrupt();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}).start();
Код: Выделить всё
Using Resource[id=1] and Resource[id=2]
Closing resource 2
Closing resource 1
Exception in thread "main" java.lang.RuntimeException: java.lang.InterruptedException: sleep interrupted
at ....
Process finished with exit code 1
Но когда я ввожу перехватчик завершения работы с приведенным ниже кодом:
Код: Выделить всё
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("Shutting down");
t.interrupt();
}));
Код: Выделить всё
kill -15
Код: Выделить всё
Using Resource[id=1] and Resource[id=2]
Shutting down
Process finished with exit code 143 (interrupted by signal 15:SIGTERM)
Кто-нибудь знает, почему это происходит и как обеспечить закрытие ресурсов?
Спасибо.
Подробнее здесь: https://stackoverflow.com/questions/787 ... -resources