6、使用jconsole+VisualVM分析JVM

一、不断增加对象触发GC的代码

VM 参数:-Xms100m -Xmx100m -XX:+UseSerialGC

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) throws InterruptedException {

        while (true){
            fillheap(1000);

        }



    }

    private static void fillheap(int count) throws InterruptedException {
        List<OOMObjcet> list = new ArrayList<OOMObjcet>();
        for (int i = 0; i<count ; i++){
            Thread.sleep(50);
            list.add(new OOMObjcet());
        }
        System.gc();

    }
    static class OOMObjcet{
        public byte[] placeholder = new byte[64*1024];
    }
}

效果图:

二、线程检测

代码:

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ThreadDemo {

    public static void createBusyThread(){
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true);
            }
        },"testBusyThread");
        thread.start();
    }

    public static void createLockThread(final  Object lock){
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock){
                    try {
                        lock.wait();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        },"testLockThread");
        thread.start();
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        br.readLine();
        createBusyThread();
        br.readLine();

        Object o = new Object();
        createLockThread(o);
    }
}

jconsole的图:

三、死锁代码

public class ThreadDieLock {
    static class SynAddRunable implements Runnable{
        int a,b;

        public SynAddRunable(int a, int b) {
            this.a = a;
            this.b = b;
        }

        @Override
        public void run() {
            synchronized (Integer.valueOf(a)){
                synchronized (Integer.valueOf(b)){
                    System.out.println(a+b);
                }
            }
        }
    }

    public static void main(String[] args) {

        for (int i = 0;i <100;i++){
            new Thread(new SynAddRunable(1,2)).start();
            new Thread(new SynAddRunable(2,1)).start();
        }
    }
}

二、VisualVM

VisualVM安装插件报错

https://blog.csdn.net/xionglangs/article/details/77603343

猜你喜欢

转载自www.cnblogs.com/yeyongjian/p/9247565.html