WebSphere Classloader Memory Leak Prevention

Solving Application ClassLoader Leaks

Applications tend to want to:

  • Start new threads using Runnable implementations from the application class loader. Even though the JEE programming model does not support this, customers frequently either directly create new threads or indirectly create them by using Timers. Customers must ensure that these threads are stopped when the corresponding application (or WAR module) is stopped:

    • javax.servlet.ServletContextListener.contextDestroyed can be used to be notified when a WAR is being stopped in order to clean up. Note that WARs can be stopped independently from an application when class reloading is enabled.
    • javax.ejb.Singletonjavax.ejb.Startup, and javax.annotation.PreDestroy annotations can be used to be notified when an EJB module is being stopped in order to clean it up. Note, singleton EJBs are only available in EJB 3.1 (WAS v8).
    • Startup beans can be used to be notified when an EJB module is being stopped in order to clean up. All EJB modules are stopped when an entire application is being stopped.
  • Use ThreadLocal (storing a ThreadLocal in a static). ThreadLocal values are effectively stored as WeakHashMap in each Thread. Since the values typically include application objects, the application object references its Class, which references its ClassLoader, which references the Class contain the ThreadLocal, the weak reference is never broken, and a leak occurs.

    Customers are encouraged either to avoid the use of ThreadLocal, to clear references to the ThreadLocal when the module is stopped (see above), or to ensure that remove() is called after every request.

  • Register JMX MBeans or NotificationListener with the JMX server. Customers must ensure that these are unregistered when the corresponding application (or WAR module) is stopped.

Arbitrary components

This includes JDBC providers, third-party software, and applications themselvestend to want to:
  • Start new threads, including the “timer threads” created by the java.util.Timer constructor. When a Thread is created, two pieces of information are copied from the primordial thread:

    1. The context class loader (getContextClassLoader()). When an application is executing, the containers set the context class loader to the module class loader, so the newly created thread will keep the context class loader alive for the duration of its existence. This can be avoided by calling setContextClassLoader to a non-application class loader prior to starting the timer and then resetting it afterwards.
    2. The AccessControlContext of the calling thread (as documented by AccessController). If the thread is being started due to an API call from an application, then the application’s ProtectionDomain will be in theAccessControlContext, and the ProtectionDomain of an application class will include a reference to its ClassLoader. This can be avoided by creating the thread using doPrivileged. Note that care must be taken to ensure that the use of doPrivileged does not allow unprivileged applications to create threads.

    For example:

    // doPrivileged fixes the AccessControlContext leak, and it is also required
    // for calls to Thread.get/setContextClassLoader.
    Timer timer = AccessController.doPrivileged(new PrivilegedAction() {
      public void run() {
        Thread thread = Thread.currentThread();
        ClassLoader savedCL = thread.getContextClassLoader();
        thread.setContextClassLoader(null);
        try {
          // The Timer constructor will create a Thread, which will copy the
          // context class loader from the current thread, which is now null.
          return new Timer(true);
        } finally {
          thread.setContextClassLoader(savedCL);
        }
      }
    });
    
  • Associate data with the current context class loader. This is typically done via a Map<classloaderValue></classloader. This Map must either:
    1. Have explicit lifecycle APIs. In this case, the lifecycle API must be called. If the code was introduced by a customer, then the customer is responsible for adding a JMX listener. If the code was introduced by a WAS prereq, then the owner must use a WAS application listener API. If the code belongs to the JDK, then the runtime team will accept responsibility for calling it (e.g., ResourceBundle.clearCache andIntrospector.flushCaches).
    2. Be a WeakHashMap to allow the ClassLoader key to be garbage collected. Note that the value must not hold a non-weak reference to classes or objects created from that ClassLoader, or the entry will never be removed. Either WeakHashMap<ClassLoader, WeakReference<Class>> or WeakHashMap<ClassLoader, Tuple>, where Tuple contains WeakReference<Class> and WeakReference<Object> to an object instantiated from the class. In both cases, the Class is held weakly, which will still allow the ClassLoader to be collected. In the latter case, the reference to the instantiated object will be cleared if a GC occurs, but the assumption is made that it can be cheaply reinstantiated.

These tips are courtesy of WAS guru Brett Kail

Reference: WebSphere Classloader Memory Leak Preventions from our JCG partner Rohit Kelapure at the All Things WebSphere blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

One Response to "WebSphere Classloader Memory Leak Prevention"

  1. The techniques referred can help. But as the close to 1,000 classloader leaks we have discovered and cured so far show – developers are not aware of those JVM shortcomings. So in the form of blatant marketing – if you have a leak and nobody else can help – you can pick http://www.plumbr.eu for the task at hand.

Leave a Reply


8 − seven =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books