星期四 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参数是不能减少的。一般的规则是在一个32位web程序上使用多于1G的heap空间。
⒊非常深的递归算法也能导致内存溢出问题。这种情况,仅有的办法是增加线程的stack空间(-Xss),或者改变算法较少深度或者每次调用的本地数据尺寸。
⒋一个webapp使用很多具有依赖关系的库,或者一个服务器运行了太多的webapp,耗尽了JVM的PermGen空间。这个空间是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);
*/
Posted at 08:38上午 一月 10, 2008 by 孙悟空 in Java | 评论[0]
星期三 2008年01月09日
在JSP中取得通过URL获得文件的磁盘绝对路径
总有用户询问,其程序布置的目录绝对位置是啥。其实很简单,ServletContext中有一个getRealPath函数,它可以通过虚拟路径来得到目录或者文件的绝对路径。
例如在JSP文件中:
application.getRealPath("/")
就可以获得应用目录的绝对路径,如果应用的目录为 D:\Tomcat\webapps\test,那么 application.getRealPath("/")就会返回D:\Tomcat\webapps\test 。
Posted at 03:52下午 一月 09, 2008 by 孙悟空 in Java | 评论[0]
星期二 2008年01月08日
Web上使用文本编辑器FCKeditor-超强悍
这个文本编辑器可是大名鼎鼎了,让你在网页中向使用word那样来编辑文本,并兼容所有的主要流行浏览器。我这里仅仅说明在Tomcat上如何安装它,并运行其附带的例子。
现在的最新版本是 FCKeditor_2.5.1.zip ,把它下载下来,这个包中包含了主要的javascript脚本,和asp及php使用的例子,并没有jsp实现代码,首先解压,一会儿我们会用到。
JSP的实现代码最新版本是 FCKeditor-2.3.zip ,下载,解压出里面的web目录即可。你可以把这个目录放在自己的Tomcat\webapps目录下,当然你可以把这个web命名为其它名称。现在这个目录里缺乏核心的javascript等文件,无法运行里面的例子。现在把FCKeditor_2.5.1.zip里面的editor目录、fckconfig.js、fckeditor.js、fckpackager.xml、fckstyles.xml、fcktemplates.xml拷贝到web目录下就可以了,启动Tomcat你就可以体验FCKeditor的强大功能了。
Posted at 09:21上午 一月 08, 2008 by 孙悟空 in Java | 评论[0]