@@ -645,8 +645,12 @@ public void refresh() throws BeansException, IllegalStateException {
645
645
* active flag as well as performing any initialization of property sources.
646
646
*/
647
647
protected void prepareRefresh () {
648
- // Switch to active.
649
648
this .startupDate = System .currentTimeMillis ();
649
+
650
+ // Remove shutdown hook during refresh phase.
651
+ removeShutdownHook ();
652
+
653
+ // Switch to active.
650
654
this .closed .set (false );
651
655
this .active .set (true );
652
656
@@ -966,6 +970,9 @@ protected void finishRefresh() {
966
970
967
971
// Publish the final event.
968
972
publishEvent (new ContextRefreshedEvent (this ));
973
+
974
+ // Restore shutdown hook if registered before.
975
+ restoreShutdownHook ();
969
976
}
970
977
971
978
/**
@@ -1024,6 +1031,28 @@ public void run() {
1024
1031
}
1025
1032
}
1026
1033
1034
+ private void removeShutdownHook () {
1035
+ if (this .shutdownHook != null ) {
1036
+ try {
1037
+ Runtime .getRuntime ().removeShutdownHook (this .shutdownHook );
1038
+ }
1039
+ catch (IllegalStateException ex ) {
1040
+ // ignore - VM is already shutting down
1041
+ }
1042
+ }
1043
+ }
1044
+
1045
+ private void restoreShutdownHook () {
1046
+ if (this .shutdownHook != null ) {
1047
+ try {
1048
+ Runtime .getRuntime ().addShutdownHook (this .shutdownHook );
1049
+ }
1050
+ catch (IllegalStateException | IllegalArgumentException ex ) {
1051
+ // ignore - VM is already shutting down or hook already registered
1052
+ }
1053
+ }
1054
+ }
1055
+
1027
1056
/**
1028
1057
* Close this application context, destroying all beans in its bean factory.
1029
1058
* <p>Delegates to {@code doClose()} for the actual closing procedure.
@@ -1034,17 +1063,11 @@ public void run() {
1034
1063
@ Override
1035
1064
public void close () {
1036
1065
synchronized (this .startupShutdownMonitor ) {
1037
- doClose ();
1038
1066
// If we registered a JVM shutdown hook, we don't need it anymore now:
1039
- // We've already explicitly closed the context.
1040
- if (this .shutdownHook != null ) {
1041
- try {
1042
- Runtime .getRuntime ().removeShutdownHook (this .shutdownHook );
1043
- }
1044
- catch (IllegalStateException ex ) {
1045
- // ignore - VM is already shutting down
1046
- }
1047
- }
1067
+ // We're already explicitly closing the context.
1068
+ removeShutdownHook ();
1069
+
1070
+ doClose ();
1048
1071
}
1049
1072
}
1050
1073
0 commit comments