0% found this document useful (0 votes)
5 views

pract3

Uploaded by

Up ka sher king
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

pract3

Uploaded by

Up ka sher king
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

ava Shutdown Hook

A special construct that facilitates the developers to add some code that has to be run when the Java
Virtual Machine (JVM) is shu ng down is known as the Java shutdown hook. The Java shutdown
hook comes in very handy in the cases where one needs to perform some special cleanup work
when the JVM is shu ng down. Note that handling an opera on such as invoking a special method
before the JVM terminates does not work using a general construct when the JVM is shu ng down
due to some external factors. For example, whenever a kill request is generated by the opera ng
system or due to resource is not allocated because of the lack of free memory, then in such a case, it
is not possible to invoke the procedure. The shutdown hook solves this problem comfortably by
providing an arbitrary block of code.

Taking at a surface level, learning about the shutdown hook is straigh orward. All one has to do is to
derive a class using the java.lang.Thread class, and then provide the code for the task one wants to
do in the run() method when the JVM is going to shut down. For registering the instance of the
derived class as the shutdown hook, one has to invoke the method
Run me.getRun me().addShutdownHook(Thread), whereas for removing the already registered
shutdown hook, one has to invoke the removeShutdownHook(Thread) method.

In nutshell, the shutdown hook can be used to perform cleanup resources or save the state when
JVM shuts down normally or abruptly. Performing clean resources means closing log files, sending
some alerts, or something else. So if you want to execute some code before JVM shuts down, use the
shutdown hook.

When does the JVM shut down?

The JVM shuts down when:

o user presses ctrl+c on the command prompt

o System.exit(int) method is invoked

o user logoff

o user shutdown etc.

The addShutdownHook(Thread hook) method

The addShutdownHook() method of the Run me class is used to register the thread with the Virtual
Machine.

Syntax:

1. public void addShutdownHook(Thread hook){}

The object of the Run me class can be obtained by calling the sta c factory method getRun me().
For example:

1. Run me r = Run me.getRun me();

The removeShutdownHook(Thread hook) method

The removeShutdownHook() method of the Run me class is invoked to remove the registra on of
the already registered shutdown hooks.

Syntax:
1. public boolean removeShutdownHook(Thread hook){ }

True value is returned by the method, when the method successfully de-register the registered
hooks; otherwise returns false.

Factory method

The method that returns the instance of a class is known as factory method.

Simple example of Shutdown Hook

FileName: MyThread.java

1. class MyThread extends Thread{

2. public void run(){

3. System.out.println("shut down hook task completed..");

4. }

5. }

6.

7. public class TestShutdown1{

8. public sta c void main(String[] args)throws Excep on {

9.

10. Run me r=Run me.getRun me();

11. r.addShutdownHook(new MyThread());

12.

13. System.out.println("Now main sleeping... press ctrl+c to exit");

14. try{Thread.sleep(3000);}catch (Excep on e) {}

15. }

16. }

Output:

Now main sleeping... press ctrl+c to exit

shut down hook task completed.

Same example of Shutdown Hook by anonymous class:

FileName: TestShutdown2.java

1. public class TestShutdown2{

2. public sta c void main(String[] args)throws Excep on {

3.
4. Run me r=Run me.getRun me();

5.

6. r.addShutdownHook(new Thread(){

7. public void run(){

8. System.out.println("shut down hook task completed..");

9. }

10. }

11. );

12.

13. System.out.println("Now main sleeping... press ctrl+c to exit");

14. try{Thread.sleep(3000);}catch (Excep on e) {}

15. }

16. }

Output:

Now main sleeping... press ctrl+c to exit

shut down hook task completed.

Removing the registered shutdown hook example

The following example shows how one can use the removeShutdownHook() method to remove the
registered shutdown hook.

FileName: RemoveHookExample.java

AD

1. public class RemoveHookExample

2. {

3.

4. // the Msg class is derived from the Thread class

5. sta c class Msg extends Thread

6. {

7.

8. public void run()

9. {

10. System.out.println("Bye ...");


11. }

12. }

13.

14. // main method

15. public sta c void main(String[] argvs)

16. {

17. try

18. {

19. // crea ng an object of the class Msg

20. Msg ms = new Msg();

21.

22. // registering the Msg object as the shutdown hook

23. Run me.getRun me().addShutdownHook(ms);

24.

25. // prin ng the current state of program

26. System.out.println("The program is beginning ...");

27.

28. // causing the thread to sleep for 2 seconds

29. System.out.println("Wai ng for 2 seconds ...");

30. Thread.sleep(2000);

31.

32. // removing the hook

33. Run me.getRun me().removeShutdownHook(ms);

34.

35. // prin ng the message program is termina ng

36. System.out.println("The program is termina ng ...");

37. }

38. catch (Excep on ex)

39. {

40. ex.printStackTrace();

41. }
42. }

43. }

Output:

The program is beginning ...

Wai ng for 2 seconds ...

The program is termina ng ...

Points to Remember

There are some important points to keep in mind while working with the shutdown hook.

No guarantee for the execu on of the shutdown hooks: The first and the most important thing to
keep in mind is that there is no certainty about the execu on of the shutdown hook. In some
scenarios, the shutdown hooks will not execute at all. For example, if the JVM gets crashed due to
some internal error, then there is no scope for the shutdown hooks. When the opera ng system
gives the SYSKILL signal, then also it is not possible for the shutdown hooks to come into picture.

Note that when the applica on is terminated normally the shutdown hooks are called (all threads of
the applica on is finished or terminated). Also, when the opera ng system is shut down or the user
presses the ctrl + c the shutdown hooks are invoked.

Before comple on, the shutdown hooks can be stopped forcefully: It is a special case of the above
discussed point. Whenever a shutdown hooks start to execute, one can forcefully terminate it by
shu ng down the system. In this case, the opera ng system for a specific amount of me. If the job
is not done in that frame of me, then the system has no other choice than to forcefully terminate
the running hooks.

AD

There can be more than one shutdown hooks, but there execu on order is not guaranteed: The JVM
can execute the shutdown hooks in any arbitrary order. Even concurrent execu on of the shutdown
hooks are also possible.

Within shutdown hooks, it is not allowed to unregister or register the shutdown hooks: When the
JVM ini ates the shutdown sequence, one can not remove or add more any exis ng shutdown
hooks. If one tries to do so, the IllegalStateExcep on is thrown by the JVM.

The Run me.halt() can stop the shutdown sequence that has been started: Only the Run me.halt(),
which terminates the JVM forcefully, can stop the started shutdown sequence, which also means
that invoking the System.exit() method will not work within a shutdown hook.

Security permissions are required when using shutdown hooks: If one is using the Java Security
Managers, then the Java code that is responsible for removing or adding the shutdown hooks need
to get the shutdown hooks permission at the run me. If one invokes the method without ge ng the
permission in the secure environment, then it will raise the SecurityExcep on.

You might also like