异常

结构图:

异常

1、java.lang.*Error:

public class StackOverErrorTest {
    public static void main(String[] args) {
        stackOverErrorTest();
    }
    private static void stackOverErrorTest() {
        stackOverErrorTest();
    }

}

2、java.lang.OutOfMemoryError:Java heap space

    /**
     * -Xmx10m -Xms10m
     */
    private static byte[] bytes = new byte[10 * 1024 * 1024];

    public static void main(String[] args) {
        List<byte[]> list = new ArrayList<>();
        for (int i=0;i<30;i++){
            list.add(bytes);
        }
    }
结果:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at com.yi23.springboot.interview.JVM.OutOfMemoryTest.<clinit>(OutOfMemoryTest.java:13)

3、java.lang.OutOfMemoryError:GC overhead limit exceeded:

GC回收时间过长时会抛出OutOfMemoryError。过长的定义是,超过98%的时间用来做GC并且回收了不到2%的堆内存,连续多次GC都只回收了不到2%的计算情况下才会抛出。加入不抛出

GC overhead limit错误会发生什么情况尼?那就是GC清理的这么点内存很快会再次填满,迫使GC再次执行,这样就形成恶性循环,CPU使用率一直是100%,而GC却没有任何效果。

//-Xms10m -Xmx10m -XX:+PrintGCDetails
public class GCOverheadLimit {

    public static void main(String[] args) {

        List<String> list = new ArrayList<>();
        Integer i = 1;
        try {
            while (true){
                list.add(String.valueOf(i++));
            }
        }catch (Throwable e){
            System.out.println("************i="+i);
            throw e;
        }
    }
}
结果:
[Full GC (Ergonomics) [PSYoungGen: 2048K->0K(2560K)] [ParOldGen: 7112K->381K(7168K)] 9160K->381K(9728K), [Metaspace: 2672K->2672K(1056768K)], 0.0044842 secs] [Times: user=0.01 sys=0.01, real=0.00 secs] 
Heap
 PSYoungGen      total 2560K, used 47K [0x00000007bfd00000, 0x00000007c0000000, 0x00000007c0000000)
  eden space 2048K, 2% used [0x00000007bfd00000,0x00000007bfd0bde8,0x00000007bff00000)
  from space 512K, 0% used [0x00000007bff00000,0x00000007bff00000,0x00000007bff80000)
  to   space 512K, 0% used [0x00000007bff80000,0x00000007bff80000,0x00000007c0000000)
 ParOldGen       total 7168K, used 381K [0x00000007bf600000, 0x00000007bfd00000, 0x00000007bfd00000)
  object space 7168K, 5% used [0x00000007bf600000,0x00000007bf65f438,0x00000007bfd00000)
 Metaspace       used 2703K, capacity 4486K, committed 4864K, reserved 1056768K
  class space    used 290K, capacity 386K, committed 512K, reserved 1048576K
Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
	at java.lang.Integer.valueOf(Integer.java:832)
	at com.yi23.springboot.interview.JVM.GCOverheadLimit.main(GCOverheadLimit.java:21)

4、java.lang.OutOfMemoryError:Direct buffer memory

/**
 * -Xms10m -Xmx10m -XX:+PrintGCDetails -XX:MaxDirectMemorySize=5m
 */
public class DirectBufferMemoryTest {

    public static void main(String[] args) {
        System.out.println(sun.misc.VM.maxDirectMemory() / 1024 / 1024);

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        ByteBuffer byteBuffer =ByteBuffer.allocateDirect(6*1024*1024);
    }
}
结果:
5
[GC (System.gc()) [PSYoungGen: 960K->512K(2560K)] 960K->520K(9728K), 0.0011897 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
[Full GC (System.gc()) [PSYoungGen: 512K->0K(2560K)] [ParOldGen: 8K->402K(7168K)] 520K->402K(9728K), [Metaspace: 2666K->2666K(1056768K)], 0.0034804 secs] [Times: user=0.01 sys=0.00, real=0.00 secs] 
Exception in thread "main" java.lang.OutOfMemoryError: Direct buffer memory
	at java.nio.Bits.reserveMemory(Bits.java:693)
	at java.nio.DirectByteBuffer.<init>(DirectByteBuffer.java:123)
	at java.nio.ByteBuffer.allocateDirect(ByteBuffer.java:311)
	at com.yi23.springboot.interview.JVM.DirectBufferMemoryTest.main(DirectBufferMemoryTest.java:22)

5、java.lang.OutOfMemoryError:unable to create new native thread

高并发请求服务器时,经常出现如下异常:java.lang.OutOfMemoryError:unable to create new native thread

准确的讲该native thread异常与对应的平台有关

导致原因:

  • 1、你的应用创建了太多线程了,一个应用进程创建多个线程,超过系统承载极限
  • 2、你的服务器并不允许你的应用程序创建这么多线程,linux系统默认允许单个进程可以创建线程数是1024(理论数据)个,你的应用创建超过这个数量,就会报java.lang.OutOfMemoryError:unable to create new native thread

解决办法:

  • 1、想办法降低你应用程序创建线程的数量,分析应用是否真的需要创建这么多线程,如果不是,该代码将线程数降低到最低。
  • 2、对于有的应用,确实需要创建很多线程,远超过linux系统的默认1024个线程的限制,可以通过修改linux服务器配置,扩大linux默认限制
public class UnableToCreateNewNativeThreadTest {

    public static void main(String[] args) {
        for (int i=0;;i++){
            System.out.println(i);
            new Thread(()->{
                try {
                    Thread.sleep(Integer.MAX_VALUE);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },""+i).start();
        }
    }
}
结果:
Exception in thread "main" java.lang.OutOfMemoryError: unable to create new native thread
	at java.lang.Thread.start0(Native Method)
	at java.lang.Thread.start(Thread.java:714)
	at com.yi23.springboot.interview.JVM.UnableToCreateNewNativeThreadTest.main(UnableToCreateNewNativeThreadTest.java:19)

6、java.lang.OutOfMemoryError:Metaspace

java 8及之后的版本使用Metaspace来替代永久代。

Metaspace是方法区在HotSpot中的实现,它与持久代最大的区别在于:Metaspace并不在虚拟机内存中而是使用本地内存也即在java8中,class metadata(the virtual machines internal presentation of java class),被存储在叫做Metaspace的native memory

永久代(java8后被原空间Metaspace取代了)存放了以下信息:

  • 虚拟机加载的类信息
  • 常量池
  • 静态变量
  • 即时编译后的代码
/**
 * @Description -XX:MetaspaceSize=10m -XX:MaxMetaspaceSize=10m
 */
public class MetaSpceTest {

    static class OOMTest{

    }

    public static void main(String[] args) {

        int i=0;
        try{
            while (true){

                i++;
                Enhancer enhancer = new Enhancer();
                enhancer.setSuperclass(OOMTest.class);
                enhancer.setUseCache(false);
                enhancer.setCallback(new MethodInterceptor() {
                    @Override
                    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                        return methodProxy.invoke(o,args);
                    }
                });
                enhancer.create();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println("***********多少次后发生了异常i="+i);
        }
    }
}
结果:
org.springframework.cglib.core.CodeGenerationException: java.lang.reflect.InvocationTargetException-->null
	at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:345)
	at org.springframework.cglib.proxy.Enhancer.generate(Enhancer.java:492)
	at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:114)
	at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:291)
	at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:480)
	at org.springframework.cglib.proxy.Enhancer.create(Enhancer.java:305)
	at com.yi23.springboot.interview.JVM.MetaSpceTest.main(MetaSpceTest.java:36)
Caused by: java.lang.reflect.InvocationTargetException
	at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.springframework.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:459)
	at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:336)
	... 6 more
Caused by: java.lang.OutOfMemoryError: Metaspace
	at java.lang.ClassLoader.defineClass1(Native Method)
	at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
	... 11 more
***********多少次后发生了异常i=576