Fixed a deadlock issue that prevented the process from exiting by uyong · Pull Request #29692 · spring-projects/spring-framework (original) (raw)
how deadlocks occur?
- when ApplicationContext call refresh() method, main thread will hold startupShutdownMonitor monitor;
- then call onRefresh() method, it will load the external WebServer and create it;
- Let's say I implemented this WebServer, i will check license before created it, when the certification fails, I call System.exit(1), want to exit the process;
- System.exit(1) will runHooks, ApplicationContext's shutdownHook will be call, It runs in another thread, name of 'SpringContextShutdownHook', it will wait the monitor startupShutdownMonitor, but the monitor still hold by main thread, to make matters worse, main thread blocking in onRefresh method, wait WebServer created.
- so, deadlock occur!!
Fix it:
shutdownHook does not need to acquire a monitor on startupShutdownMonitor , and doClose method is thread safe, it is enough to call it.