Programing

Java에서 종료 후크의 유용한 예?

lottogame 2020. 7. 16. 08:09
반응형

Java에서 종료 후크의 유용한 예?


Java 응용 프로그램을 강력하게 만들기 위해 합리적인 단계를 수행하도록 노력하고 있으며 그 일부에는 정상적으로 종료해야합니다. 종료 후크 에 대해 읽고 실제로 실제로 사용하는 방법을 알지 못합니다.

실용적인 예가 있습니까?

아래에 이와 같은 간단한 응용 프로그램이 있다고 가정 해보십시오.이 파일은 파일에 10을 한 줄에 100 단위로 씁니다. 프로그램이 중단되면 주어진 배치가 완료되도록하고 싶습니다. 종료 후크를 등록하는 방법을 얻었지만이를 내 응용 프로그램에 통합하는 방법을 모릅니다. 어떤 제안?

package com.example.test.concurrency;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;

public class GracefulShutdownTest1 {
    final private int N;
    final private File f;
    public GracefulShutdownTest1(File f, int N) { this.f=f; this.N = N; }

    public void run()
    {
        PrintWriter pw = null;
        try {
            FileOutputStream fos = new FileOutputStream(this.f);
            pw = new PrintWriter(fos);
            for (int i = 0; i < N; ++i)
                writeBatch(pw, i);
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        finally
        {
            pw.close();
        }       
    }

    private void writeBatch(PrintWriter pw, int i) {
        for (int j = 0; j < 100; ++j)
        {
            int k = i*100+j;
            pw.write(Integer.toString(k));
            if ((j+1)%10 == 0)
                pw.write('\n');
            else
                pw.write(' ');
        }
    }

    static public void main(String[] args)
    {
        if (args.length < 2)
        {
            System.out.println("args = [file] [N] "
                    +"where file = output filename, N=batch count");
        }
        else
        {
            new GracefulShutdownTest1(
                    new File(args[0]), 
                    Integer.parseInt(args[1])
            ).run();
        }
    }
}

다음을 수행 할 수 있습니다.

  • 종료 후크가 일부 AtomicBoolean (또는 휘발성 부울) "keepRunning"을 false로 설정하도록합니다.
  • (Optionally, .interrupt the working threads if they wait for data in some blocking call)
  • Wait for the working threads (executing writeBatch in your case) to finish, by calling the Thread.join() method on the working threads.
  • Terminate the program

Some sketchy code:

  • Add a static volatile boolean keepRunning = true;
  • In run() you change to

    for (int i = 0; i < N && keepRunning; ++i)
        writeBatch(pw, i);
    
  • In main() you add:

    final Thread mainThread = Thread.currentThread();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            keepRunning = false;
            mainThread.join();
        }
    });
    

That's roughly how I do a graceful "reject all clients upon hitting Control-C" in terminal.


From the docs:

When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.

That is, a shutdown hook keeps the JVM running until the hook has terminated (returned from the run()-method.


Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().JVM does not give any guarantee on the order in which shutdown hooks are started.For more info refer http://techno-terminal.blogspot.in/2015/08/shutdown-hooks.html

참고URL : https://stackoverflow.com/questions/2921945/useful-example-of-a-shutdown-hook-in-java

반응형