Action on exit java

aphor / java_signal_exit.md

Tuesday, February 19, 2013 JVMs and kill signals Ever wondered how a JVM reacts to various kill signals? The (intended) behaviour might be documented somewhere already, but I found having a table of > the actual behaviour available quite useful. In particular I wanted to know which kill signals trigger the JVM to run registered shutdown hooks, and > > which kill signals don’t actually terminate the JVM. So I decided to compile a table of that information.

I wrote up a small Java application that just registers a shutdown hook that I can detect whether it has executed or not, and then sleeps until I get a chance to kill it:

class Death < public static void main(String. args) throws Exception < Runtime.getRuntime().addShutdownHook( new Thread()< @Override public void run() < System.out.println("Shutting down"); > > ); for (;;) Thread.sleep(100); > >

Then I ran the program in one terminal window (java Death; echo $?) while iterating through all kill signals (0-31) in another:

kill -$SIGNAL $(jps | grep Death | cut -d\ -f1)
signal shutdown runs hook exit code comment
default (15) yes yes 143 SIGTERM
0 no
1 (SIGHUP) yes yes 129
2 (SIGINT) yes yes 130 SIGINT is the signal sent on ^C
3 (SIGQUIT) no Makes the JVM dump threads / stack-traces
4 (SIGILL) yes no 134 Makes the JVM write a core dump and abort on trap 6
5 yes no 133 Makes the JVM exit with «Trace/BPT trap: 5»
6 (SIGABRT) yes no 134 Makes the JVM exit with «Abort trap: 6»
7 yes no 135 Makes the JVM exit with «EMT trap: 7»
8 (SIGFPE) yes no 134 Makes the JVM write a core dump and abort on trap 6
9 (SIGKILL) yes no 137 The JVM is forcibly killed (exits with «Killed: 9»)
10 (SIGBUS) yes no 134 Emulates a «Bus Error»
11 (SIGSEGV) yes no 134 Emulates a «Segmentation fault»
12 yes no 140 Makes the JVM exit with «Bad system call: 12»
13 no
14 yes no 142 Makes the JVM exit with «Alarm clock: 14»
15 (SIGTERM) yes yes 143 This is the default unix kill signal
16 no
17 no 145 Stops the application (sends it to the background), same as ^Z
18 no 146 Stops the application (sends it to the background), same as ^Z
19 no
20 no
21 no 149 Stops the application (sends it to the background), same as ^Z
22 no 150 Stops the application (sends it to the background), same as ^Z
23 no
24 yes no 152 Makes the JVM exit with «Cputime limit exceeded: 24»
25 no
26 yes no 154 Makes the JVM exit with «Virtual timer expired: 26»
27 yes no 155 Makes the JVM exit with «Profiling timer expired: 27»
28 no
29 no
30 yes no 158 Makes the JVM exit with «User defined signal 1: 30»
31 yes no 134 Makes the JVM exit on Segmentation fault
Читайте также:  Python request post запрос

This list was compiled using (a quite old) Oracle Hotspot Java 8 EA on Mac OS X:

Java(TM) SE Runtime Environment (build 1.8.0-ea-b65) Java HotSpot(TM) 64-Bit Server VM (build 25.0-b09, mixed mode)``` Hope this is useful to more people than myself. Posted by Tobias at 10:42 Labels: Java, JVM

Источник

Perform an action when exiting a Java-based Android application

To resolve the issue, you can utilize the amazing realm of asynchronous events. For instance, assuming your Text to Speech object is available, you can subscribe to an event. This approach is asynchronous because your program can perform other tasks while you wait for the notification of the subscribed event occurrence.

Android waiting on something

I am trying to figure out how to make a program pause until an event is completed before triggering another event. For instance, I have a text-to-speech function that needs to finish speaking before the Google voice recognizer is activated. Currently, both events occur simultaneously, causing the recognizer to pick up the speech. I have researched solutions on this platform, but the explanations were not straightforward. Can someone assist me with this issue?

Here’s a code snippet that I experimented with.

protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_menu); tts=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() < @SuppressWarnings("deprecation") @Override public void onInit(int status) < if(status != TextToSpeech.ERROR)< tts.setLanguage(Locale.UK); tts.speak("Welcome", TextToSpeech.QUEUE_FLUSH, null); >> >); if(!(tts.isSpeaking())) < startVoiceRecognitionActivity(); >> private void startVoiceRecognitionActivity() < Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak Up"); startActivityForResult(intent, REQUEST_CODE); >@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) < if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) < matches = data.getStringArrayListExtra( RecognizerIntent.EXTRA_RESULTS); if (matches.contains("list"))< Intent gotoList = new Intent(MenuActivity.this, ListActivity.class ); startActivity(gotoList); >> super.onActivityResult(requestCode, resultCode, data); > 

Enter the fascinating realm of events that occur without synchronicity.

To achieve your desired outcome, it is not advisable to adopt a «wait and see» approach as it can lead to stagnation. Instead, the key is to adopt an active «listening» approach.

In Android, if a process like Text To Speech takes a while, you need to keep an ear out for an event.

Upon examining the documentation for the Text To Speech object, it is evident that it allows for the utilization of a listener for various purposes. This can be observed through the following links: http://developer.android.com/reference/android/speech/tts/TextToSpeech.html#setOnUtteranceProgressListener(android.speech.tts.UtteranceProgressListener) and http://developer.android.com/reference/android/speech/tts/UtteranceProgressListener.html.

Assuming your Text to Speech object is identified as tts , you would perform the following action.

tts.setOnUtteranceProgressListener(new UtteranceProgressListener() < public void onDone(String utteranceId) < // The text has been read, do your next action >public void onError(String utteranceId, int errorCode) < // Error reading the text with code errorCode, can mean a lot of things >public void onStart(String utteranceId) < // Reading of a sentence has just started. You could for example print it on the screen >>); 

The process of subscribing to an event is asynchronous as it allows your program to perform other tasks while waiting for a notification about the subscribed event. The notification is triggered by the occurrence of the event that has been subscribed to.

Then for example when you do

Upon completion, the onDone method will trigger the listener and initiate the voice recognizer.

Источник

Blog

How to perform an action before terminating a java application / How to use shutdown hook in java

  • Post author: codippa
  • Post published: February 1, 2018
  • Post category: J2SE (Core Java)
  • Post comments: 0 Comments

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home3/codippac/public_html/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home3/codippac/public_html/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home3/codippac/public_html/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Suppose your application starts a process (a server embedded in the application, let’s say). The application may be running from a command line interface or a GUI. Now, you want that whenever user terminates the application either by typing Ctrl + C(control and c keys pressed together) on command line or pressing close button on the application GUI, the process started by the application is also terminated.

Shutdown Hook is the solution

A shutdown hook is a piece of code which executes before an application terminates. Java provides a mechanism to apply shutdown hooks in an application. This shutdown hook is executed in below 2 cases :

  1. When the application is terminated by user intervention by pressing Ctrl + C on console window where it is running.
  2. When System.exit() is called from within the application.

How to apply shutdown hook

A shutdown hook is a separate thread which runs only when above 2 events occur and it is created using java.lang.Runtime class of java library. Creating a shutdown hook involves following steps:

  1. Create a normal java thread using a separate class (by extending java.lang.Thread) and implement its run method or create a thread using an anonymous class. This run method should contain the task which you want to perform during shutdown such as killing a process, closing a file or a database connection etc.
  2. Supply this thread to addShutdownHook method of java.lang.Runtime class.

It is also possible to unregister or remove a shutdown hook by using removeShutdown method of java.lang.Runtime class. This method takes the thread object which was supplied as argument while adding the hook.

Scenario 1 : When System.exit() is called

Create a class which extends java.lang.Thread class and implement its run method. This method should have all the code which needs to be executed as a part of shutdown process. Pass this thread to the addShutdownHook method if java.lang.Runtime class as shown below.

public class ShutDownHookDemo { public static void main(String[] args) { // create thread object ShutDownTask shutDownTask = new ShutDownTask(); // add shutdown hook Runtime.getRuntime().addShutdownHook(shutDownTask); // exit application System.exit(0); } /** * Class having shutdown steps * */ private static class ShutDownTask extends Thread { @Override public void run() { System.out.println("Performing shutdown"); } } }

When the above code is executed, following is the output

Note that when System.exit(0) is called, the statement written inside the shutdown hook gets printed. In actual applications, it will have a much complex code to perform actual shutdown operations.

Scenario 2 : When Ctrl + C is pressed

Consider the following code where a dummy infinite loop has been created. In real applications, this will be replaced by the application logic which takes some time to execute. Suppose this application is running on command line and user presses Control + C in between. Below program registers a shutdown hook which is executed as soon as Ctrl and C keys are pressed. See the output of execution after the code.

public class ShutDownHookDemo { public static void main(String[] args) { // create thread object ShutDownTask shutDownTask = new ShutDownTask(); // add shutdown hook Runtime.getRuntime().addShutdownHook(shutDownTask); System.out.println("Going into infinite loop. "); // infinite loop. Real applications will have some long running logic // here while (true) { //application logic } } /** * Class having shutdown steps * */ private static class ShutDownTask extends Thread { @Override public void run() { System.out.println("Performing shutdown"); } } }

The program is stuck in an infinite loop. When Ctrl-c is pressed at the console window, the registered shutdown hook is executed before application termination.

Shutdown hook using Anonymous Thread class

In both the above examples, a shutdown hook was created as a separate implementation class of java.lang.Thread but it is also possible without creating a separate class and creating it anonymously. Code is shown below.

public class ShutDownHookDemo { public static void main(String[] args) { // create shutdown hook with anonymous implementation Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.out.println("Performing shutdown"); } }); System.out.println("Going into infinite loop. "); // infinite loop. Real applications will have some long running logic // here while (true) { // application logic } } }

Behavior of shutdown hook created using this approach is the same.

A shutdown hook added by using an anonymous class cannot be removed since there would be no access to the thread object used while adding the hook.

Let’s tweak in

  1. A shutdown hook is just an unstarted thread which runs as soon as any of the events listed above occur.
  2. If the JVM terminates abnormally such as when an external KILL command is issued, then there is no guarantee of execution of shutdown hook.
  3. removeShutdownHook method returns true if the hook is successfully removed, false otherwise.
  4. A single application can have many shutdown hooks but their order of execution is random.
  5. It is not recommended to have any sort of user interaction inside shutdown hooks and their execution should also finish quickly.
  6. Registering a shutdown hook more than once using the same thread object will result in a java.lang.IllegalStateException as java.lang.IllegalArgumentException: Hook previously registered.
  7. Trying to add a new shutdown hook from another shutdown hook is not permitted and throws an exception as java.lang.IllegalStateException: Shutdown in progress . This is because you cannot add a new shutdown hook once a shutdown process has started.

Share if it’s worth .

Источник

Оцените статью