Recently, a Data transformation engine service was required to be written in the project, synchronizing data every 5 minutes. The implementation is a scheduledexecutorservice and a threadpoolexecutor thread pool that is initialized after the engine server is started. Schduel executor every 5 minutes, each tranform in the datatransformlist is added to the thread pool to run. Each data converter is responsible for converting a set of database data. There is a service restart during execution and at this point the tranform is transforming the data and the data is not fully operational, at which point you want the work that is being performed to complete the job before exiting. Graceful downtime in the service restart, the service shutdown is more important (although it does not solve the sudden outage of the server caused the service instantaneous unavailability, etc.).
Normal graceful shutdown: When using the Kill PID, the JVM receives a service stop signal and executes the shutdownhook thread
Runtime.getruntime (). Addshutdownhook (New Thread () {
public void Run () {
Synchronized (Enginebootstrap.class) {
Engineserver.getinstance (). Shutdown ();
running = false;
EngineBootstrap.class.notify ();
}
}
});
The Shutdown method of Engineserver
public void shutdown () {
This.transformExecutor.shutdown ();
This.scheduledExecutorService.shutdown ();
}
Threadpoolexecutor's shutdown method interrupts all idle tasks, leaving the running task to complete, but the JVM exits after a certain period of kill PID, causing the task that is executing to stop before it finishes.
Improved graceful shutdown:
Signal sig = new Signal (Getossignaltype ());
Signal.handle (SIG, New Signalhandler () {
public void handle (Signal Signal) {
Synchronized (Enginebootstrap.class) {
Engineserver.getinstance (). Shutdown ();
running = false;
EngineBootstrap.class.notify ();
}
}
});
private static String Getossignaltype () {
Return System.getproperties (). GetProperty ("Os.name").
toLowerCase (). StartsWith ("Win")? "INT": "USR2";
}
Under Linux kill-l View 31 corresponds to SIGUSR2 performing kill-31 PID, Signalhander receives a signal of signal number 31 and executes server shutdown, At this point the JVM does not exit until all executing threads in the thread pool have completed execution.
Java-jar Data-engine-1.0.0-snapshot.jar
SH shutdown.sh
You can see that the Java process does not end after the work in the thread pool has completed after the primary thread exits safely
Chenbanghongs-macbook-pro:nbugs-data-engine sylar$ java -jar target/ data-engine-1.0.0-snapshot.jar.zip1234531 Graceful shutdown main thread safe exit 67891011121314151617181920transform
Download
Data-engine-1.0.0-snapshot.jar.zip
shutdown.sh
Implementation of graceful downtime in Java