D
D
Dmitry Osipov2019-02-11 17:10:05
linux
Dmitry Osipov, 2019-02-11 17:10:05

How does a java application stop?

Good afternoon
We have a multi-threaded java application that works with the web and the database. We send him a kill pid.
How will the currently running threads be terminated?
Is it possible with try-catch to do something at a stop, such as sending a request to an address or writing something to the database?
What happens to a java application when you call kill -9 ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Marat Khayrutdinov, 2019-02-12
@Shiftuia

One of the classic ways to handle the shutdown of a java application, as mentioned above, is Runtime.getRuntime().addShutdownHook. In turn, it can issue a command to stop all other threads, either using the "interrupt" flag of the Thread class, or using a prudently set own stop flag in worker threads.
Accordingly, the threads being stopped should either check the stop flag periodically or handle the InterruptedException gracefully.
Example with "interrupt" flag

public static void main(String[] args) {
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
      Thread.getAllStackTraces().keySet().stream()
          //Не стоит останавливать поток в котором отрабатывает хук, а тем более пытаться заджойниться
          .filter(thread -> !thread.equals(Thread.currentThread()))
          //Демоны предполагают безопасное завершение в любой момент, останавливать их не нужно
          .filter(thread -> !thread.isDaemon())
          //Устанавливаем флаг "interrupt" для всех остальных 
          .peek(Thread::interrupt) 
          .peek(thread -> System.out.println(thread.getClass()))
          .forEach(thread -> {
            try {
              thread.join(); //Ждем завершения всех потоков, которым установлен флаг "interrupt"
            } catch (InterruptedException e) {
              // ...
            }
          });
    }));
    
    while (true) {
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        System.out.println("Thread was interrupted once");
        //После перехвата исключения флаг "interrupt" возвращается в исходное состояние, поэтому его нужно установить снова
        Thread.currentThread().interrupt(); 
        break;
      }
    }

    while (true) {
      try {
        Thread.sleep(100); // Мы бы зависли здесь, если бы не установили флаг "interrupt" повторно
      } catch (InterruptedException e) {
        System.out.println("Thread was interrupted");
        Thread.currentThread().interrupt();
        break;
      }
    }
    
    while (!Thread.currentThread().isInterrupted()) {
      doSomeUninterruptableWork();
    }
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question