Yhzhtk / note

知识代码笔记
https://github.com/Yhzhtk/note/issues
MIT License
108 stars 11 forks source link

BTrace 初体验 #30

Open Yhzhtk opened 9 years ago

Yhzhtk commented 9 years ago

BTrace 可以对正在运行的 Java 程序,通过修改 bytecode 字节码,来跟踪程序的运行,对于排查线上问题,非常有用。

BTrace 介绍

BTrace is a safe, dynamic tracing tool for Java. BTrace works by dynamically (bytecode) instrumenting classes of a running Java program. BTrace inserts tracing actions into the classes of a running Java program and hotswaps the traced program classes.

BTrace用户指南

BTrace下载地址

示例脚本:

内存定时分析,设置一个定时器,每四秒执行一次,打印当前堆栈使用情况。

下载

package com.sun.btrace.samples;

import com.sun.btrace.annotations.*;
import static com.sun.btrace.BTraceUtils.*;

/**
 * Simple BTrace program that prints memory
 * usage once every 4 seconds. It is possible
 * to modify this to dump heap depending on 
 * used memory crossing a threshold or some other
 * such condition. [dumpHeap is a built-in function].
 */
@BTrace public class Memory {
    @OnTimer(4000)
    public static void printMem() {
        println("Heap:");
        println(Sys.Memory.heapUsage());
        println("Non-Heap:");
        println(Sys.Memory.nonHeapUsage());
    }
}

运行命令:

sudo -u tomcat /bin/btrace <pid> Memeory.java

结果如下:

Heap:
init = 2147483648(2097152K) used = 1520250264(1484619K) committed = 2110324736(2060864K) max = 2110324736(2060864K)
Non-Heap:
init = 270991360(264640K) used = 133018568(129900K) committed = 288358400(281600K) max = 318767104(311296K)
....