1
+
2
+ import java .util .Random ;
3
+ import java .util .concurrent .TimeUnit ;
4
+ import java .util .concurrent .atomic .LongAdder ;
5
+ /*
6
+ 演示GC日志生成与解读
7
+ */
8
+ public class GCLogAnalysis {
9
+ private static Random random = new Random ();
10
+ public static void main (String [] args ) {
11
+ // 当前毫秒时间戳
12
+ long startMillis = System .currentTimeMillis ();
13
+ // 持续运行毫秒数; 可根据需要进行修改
14
+ long timeoutMillis = TimeUnit .SECONDS .toMillis (1 );
15
+ // 结束时间戳
16
+ long endMillis = startMillis + timeoutMillis ;
17
+ LongAdder counter = new LongAdder ();
18
+ System .out .println ("正在执行..." );
19
+ // 缓存一部分对象; 进入老年代
20
+ int cacheSize = 2000 ;
21
+ Object [] cachedGarbage = new Object [cacheSize ];
22
+ // 在此时间范围内,持续循环
23
+ while (System .currentTimeMillis () < endMillis ) {
24
+ // 生成垃圾对象
25
+ Object garbage = generateGarbage (100 *1024 );
26
+ counter .increment ();
27
+ int randomIndex = random .nextInt (2 * cacheSize );
28
+ if (randomIndex < cacheSize ) {
29
+ cachedGarbage [randomIndex ] = garbage ;
30
+ }
31
+ }
32
+ System .out .println ("执行结束!共生成对象次数:" + counter .longValue ());
33
+ }
34
+
35
+ // 生成对象
36
+ private static Object generateGarbage (int max ) {
37
+ int randomSize = random .nextInt (max );
38
+ int type = randomSize % 4 ;
39
+ Object result = null ;
40
+ switch (type ) {
41
+ case 0 :
42
+ result = new int [randomSize ];
43
+ break ;
44
+ case 1 :
45
+ result = new byte [randomSize ];
46
+ break ;
47
+ case 2 :
48
+ result = new double [randomSize ];
49
+ break ;
50
+ default :
51
+ StringBuilder builder = new StringBuilder ();
52
+ String randomString = "randomString-Anything" ;
53
+ while (builder .length () < randomSize ) {
54
+ builder .append (randomString );
55
+ builder .append (max );
56
+ builder .append (randomSize );
57
+ }
58
+ result = builder .toString ();
59
+ break ;
60
+ }
61
+ return result ;
62
+ }
63
+ }
0 commit comments