孙猴子的水帘洞

« Previous day (一月 9, 2008) | Main | Next day (一月 11, 2008) »

http://blogs.163jsp.com/monkeysun/date/20080110 星期四 2008年01月10日

OutOfMemory

如何处理内存溢出错误

这些错误在开发期间相当普遍,即使是在产品服务器上。这些错误比其它错误恼人,因为不会显示任何堆栈跟踪(stack trace)。原因是堆栈跟踪对这样的错误没有任何帮助。导致内存溢出的代码,在大部分情况下,也是问题的“受害者”,而不是它产生的问题。

虽然这些问题让人迷惑容易把问题推卸到Tomcat上,实际上很多问题是在应用程序(webapps)中导致的“错误”。这些应用程序通常是程序设计模式和技术相当合法和安全的独立运行的应用程序,但是没有正确地管理其运行的环境,例如一个servlet容器(例如Tomcat)。

本文提供了一个这些“常见错误”的列表,任何人遇到这些问题,或者想避免这些问题,能够检查他们的webapps并纠正它们。

内存溢出错误的常见情况

一个servlet装载一个几个GB的文件到内存中将会一定杀死服务器。这种问题必须看作我们程序的一个简单的BUG

为了补偿你的servlet尝试装载的数据,你增加了堆尺寸(heap size),因此没有空间为需要创建的线程创建栈(stack)。注:堆区(heap):是由malloc之类函数分配的空间所在地。地址是由低向高增长的。一般由程序员分配释放, 若程序员不释放,程序结束时可能由OS回收。栈区(stack):是自动分配变量,以及函数调用的时候所使用的一些空间。地址是由高向低减少的。由编译器自动分配释放 ,存放函数的参数值,局部变量的值等。其操作方式类似于数据结构中的栈。 每一个线程将消耗2M,在一些操作系统(例如Debian Sarge)使用-Xss参数是不能减少的。一般的规则是在一个32web程序上使用多于1Gheap空间。

非常深的递归算法也能导致内存溢出问题。这种情况,仅有的办法是增加线程的stack空间(-Xss,或者改变算法较少深度或者每次调用的本地数据尺寸。

一个webapp使用很多具有依赖关系的库,或者一个服务器运行了太多的webapp,耗尽了JVMPermGen空间。这个空间是VM用来存储类和方法数据。在这种情况下,要增加这个尺寸。Sun的VM的 –XX:MaxPermSize 允许你设置这个尺寸(默认是64M)

⒌一个类的硬参考能够阻止垃圾回收器释放其占用的内存当ClassLoader被丢弃时。这个在JSP重新编译和webapps重新装载时出现。如果这些操作在一个webapps中是普遍的, 这仅仅是个时间问题,PermGen空间满的时候,内存溢出错误就被抛出。

最后这个情况我打算在这里说明。它是一个直接相关的事实,webapp运行在一个可管理的环境中,修改代码的提交根本不需要停止webapp。也就是说,将被包括的模式将是那些,虽然作为一个独立的应用程序是安全和合法的,需要重新设计来“兼容”servlet容器。

 

线程

servlet里没有其它线程启动运行。否则他们保持本地变量、他们的类和整个类装载器的硬参考。

DriveManager

如果你在你自己的classloader(或者servlets)中装载一个java.sql.Driver,驱动器在应用卸载时应该被移出。每个驱动器在DriverManager中注册,被系统classloader装载,参考本地的驱动器。

                Enumeration<Driver> drivers = DriverManager.getDrivers();
                ArrayList<Driver> driversToUnload=new ArrayList<Driver>();
                while (drivers.hasMoreElements()) {
                        Driver driver = drivers.nextElement();
                        if (driver.getClass().getClassLoader().equals(getClass().getClassLoader())) {
                                driversToUnload.add(driver);
                        }
                }
                for (Driver driver : driversToUnload) {
                    DriverManager.deregisterDriver(driver);
                }

Singleton模式

这是非常有用的模式在很多java程序中。它在一些独立运行的应用程序中是安全和可靠的,它看起来像这样:

public class MyClass {
  private static final MyClass instance = new MyClass();
  public static MyClass getInstance() {
    return instance;
  }
  private MyClass() { }

}

这种模式的问题是它创建了一个类本身的一个硬参考。只要这个实例没释放,类就不会被卸载。最终,这将导致服务器不能为整个webapps类装载器分配空间。下面的很多变通方法为了服务器的完整性牺牲了一些原有模式的优点。这个就让设计或者开发者来决定这些牺牲是否值得。

确认问题
  在你重新考虑你整个应用程序前,请确认这是否是真正的问题。我的singleton最终移出,但是tomcat还是崩溃。
1.在这样的singleton类中覆盖finalize方法,放置一个System.out.println()信息。
2.在构造函数中调用几次System.gc() (因为垃圾回收器是有些懒惰的)
3.反复布置几次应用程序
4.你可能会看到旧的singletons最终被释放,如果类装载器被垃圾回收器回收。
5.反复布置几次,内存溢出发生,在内存中会有多个"singletons"。

下面是一些变通方法,自己看吧。
Workaround 1: Move the class to another classloader

This workaround is for the case this class should be shared between webapps, or if the server will contain only one webapp. That is, we need to use the same instance across several webapps in the same server, or there is no need to worry about it. In this case, the class will need to be deployed on a shared classloader. This means this class must be in the shared/lib or shared/classes directory.

This way, the class will be loaded by a parent classloader, and not by the webapp classloader itself, so no resources need to be reclaimed on webapp reloadings.

This workaround may not always fit well with your code or design. In particular, care must be taken to avoid the singleton to keep references to classes loaded through the webapp classloader, because such references would prevent the classloader from being deallocated. A servlet context listener could be used to get rid of those references before the context is destroyed.

Workaround 2: Use commons-discovery

If you need to have a singleton instance for each webapp, you could use commons-discovery. This library provides a class named DiscoverSingleton that can be used to implement singletons in your webapp.

For using it, the class to be used as singleton will need to implement an interface (SPI) with the methods to be used. The following code is an example of usage of this library:

  MyClass instance = DiscoverSingleton.find(MyClass.class, MyClassImpl.class.getName());

It is important, for this library to work correctly, to not keep static references to the returned instances.

Just by using this syntax, you get the following advantages:

    ●Any class could be used as a singleton, as long as it implements an SPI interface.
    ●Your singleton class has been converted into a replaceable component in your webapp, so you can "plug-in" a different implementation whenever you want.

But only this does not make for a workaround. The most important advantage is the DiscoverSingleton.release() method, that releases all references to instantiated singletons in the current classloader. A call to this method could be placed into a ServletContextListener, into its contextDestroyed() method.

That is, with a ServletContextListener simple implementation like the following:

public class SingletonReleaser implements ServletContextListener {
  public contextInitialized(ServletContextEvent event) { }

  public contextDestroyed(ServletContextEvent event) {
    DiscoverSingleton.release();
  }
}

we could release all cached references to the instantiated singletons. Of course, this listener should be registered on the web.xml descriptor before any other listener that could use a singleton.


Workaround 3: Use ServletContext attributes

This refactoring will work well provided the ServletContext instance is available, as a local variable or as a parameter.

It will be more efficient than using commons-discovery, but has the disadvantage of making your code depend on the web layer (ServletContext class). Anyway, I have found out that, in some cases, it is a reasonable approach.

There are many ways to do this refactoring, so I will just present one implementation that works well for me:

    ●Create the following ServletContextListener:

public class SingletonFactory implements ServletContextListener {
  public static final String MY_CLASS = "...";

  /**
   * @see ServletContextListener#contextInitialized(ServletContextEvent)
   */
  public void contextInitialized(ServletContextEvent event) {
    ServletContext ctx = event.getServletContext();
    ctx.setAttribute(MY_CLASS, new MyClass());
  }

  /**
   * @see ServletContextListener#contextDestroyed(ServletContextEvent)
   */
  public void contextDestroyed(ServletContextEvent event) {
    ctx.setAttribute(MY_CLASS, null);
  }

  /**
   * Optional method for getting the MyClass singleton instance.
   */
  public static MyClass getMyClassInstance(ServletContext ctx) {
    return (MyClass)ctx.getAttribute(MY_CLASS);
  }
}

    ●Register the listener in the web.xml descriptor
    ●Replace the calls to MyClass.getInstance() by:

  MyClass instance = (MyClass)ctx.getAttribute(SingletonFactory.MY_CLASS);

  /* or, if implemented:
  MyClass instance = SingletonFactory.getMyClassInstance(ctx);
  */


Valid HTML! Valid CSS!

This is a personal weblog, I do not speak for my employer.