看到一个帖子,为何Exception对象创建缓慢

http://www.blogjava.net/stone2083/archive/2010/07/09/325649.html


貌似问题集中在Throwable的fillInStackTrace方法,用hprof测试一下:

java -agentlib:hprof=cpu=samples NewExceptionTester

o: 10369

e: 372768

exte: 24102

Dumping CPU usage by sampling running threads ... done.


查看dump文件,果然.....

CPU SAMPLES BEGIN (total = 16147) Thu Oct 10 21:29:45 2013

rank self accum count trace method

1 90.64% 90.64% 14636 300051 java.lang.Throwable.fillInStackTrace

2 4.61% 95.25% 744 300067 TestExceptionTime$NewException.call

3 2.22% 97.47% 358 300058 TestExceptionTime$NewExtException.call

4 0.63% 98.10% 102 300066 TestExceptionTime$NewObject.call

5 0.53% 98.63% 86 300064 java.util.HashMap.

6 0.32% 98.95% 52 300069 TestExceptionTime$ExtCustomException.

7 0.22% 99.17% 35 300052 TestExceptionTime$NewObject.call

8 0.18% 99.35% 29 300078 TestExceptionTime$CustomException.


调用14636次?! 那将创建普通的Exception对象注销掉,比较一下重写fillInStackTrace方法的Exception对象的创建速度:

o: 2152

exte: 6290


看下dump文件:

CPU SAMPLES BEGIN (total = 168) Thu Oct 10 21:45:51 2013

rank self accum count trace method

1 45.83% 45.83% 77 300053 TestExceptionTime$ExtCustomException.

2 36.31% 82.14% 61 300051 TestExceptionTime$NewExtException.call

3 7.14% 89.29% 12 300048 TestExceptionTime$NewObject.call

4 5.95% 95.24% 10 300055 java.lang.Long.valueOf

5 1.79% 97.02% 3 300050 TestExceptionTime$NewObject.call

果然不见了