简体   繁体   中英

Stop thread and save map to disk when JVM terminates

I have a Java class that starts a thread like this. This thread must be started in a static {} section.

private static final Thread thCleaner = new Thread(new SessionCleaner(mapSession));
static { thCleaner.start(); }

When JVM terminates, I need to stop this thread and save to disk the elements of a ConcurrentMap .

Code added from user's own comments:

private void writeMap() { 
   ObjectOutputStream oos = null; 
   try { 
       oos = new   ObjectOutputStream(new FileOutputStream(mapFilePath));
       oos.writeObject(this.mapSession); 
   } 
   catch (Exception e) { 
       e.printStackTrace(); 
   } 
   finally { if (oos != null) { try { oos.close(); } catch (Exception e) {} } } 

}

I tried a shutdownHook , but I could not load java.io.ObjectOutputStream to write the map (because JVM is terminating)because it's throws this exception:

28-ene-2014 13:56:00 org.apache.catalina.loader.WebappClassLoader loadClass INFO: Acceso ilegal: esta instancia de aplicación web ya ha sido parada. 
Could not load java.io.ObjectOutputStream. java.lang.IllegalStateException
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:15‌​66) 
at java.lang.ClassLoader.loadClass(ClassLoader.java:295) 
at java.net.FactoryURLClassLoader.loadClass(URLClassLoader.java:627) 
at java.lang.ClassLoader.loadClass(ClassLoader.java:247) 
at com.vpfw.tests.skiart.SkiArtDispatchInterruption$1.run 

And a finalizer is not working (and it's not recommended). What alternatives do I have?

The Exception is thrown, because the ClassLoader tries to load a new class during termination of the JVM. A possible solution is to run the whole saving chain at least once during execution to ensure that all classes are loaded.

In general it is not a good idea to react to JVM shutdown, as for once not all functionalities are still available, and for second no one can guarantee that the JVM is actually shut down properly. Under certain circumstances (eg Linux kill command) a JVM can instantly terminate without granting time to perform saves. If you want to make sure that data is available on restart, you need to frequently do saves in between and - if possible - have some form of rolling save-file, should the JVM terminate during write.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM