`
jiagou
  • 浏览: 2537446 次
文章分类
社区版块
存档分类
最新评论

Java性能调优笔记

 
阅读更多

Java性能调优笔记

调优步骤:衡量系统现状、设定调优目标、寻找性能瓶颈、性能调优、衡量是否到达目标(如果未到达目标,需重新寻找性能瓶颈)、性能调优结束。


寻找性能瓶颈
性能瓶颈的表象:资源消耗过多、外部处理系统的性能不足、资源消耗不多但程序的响应速度却仍达不到要求。

资源消耗:CPU、文件IO、网络IO、内存。
外部处理系统的性能不足:所调用的其他系统提供的功能或数据库操作的响应速度不够。
资源消耗不多但程序的响应速度却仍达不到要求:程序代码运行效率不够高、未充分使用资源、程序结构不合理。


CPU消耗分析
CPU主要用于中断、内核、用户进程的任务处理,优先级为中断>内核>用户进程。

上下文切换:
每个线程分配一定的执行时间,当到达执行时间、线程中有IO阻塞或高优先级线程要执行时,将切换执行的线程。在切换时要存储目前线程的执行状态,并恢复要执行的线程的状态。
对于Java应用,典型的是在进行文件IO操作、网络IO操作、锁等待、线程Sleep时,当前线程会进入阻塞或休眠状态,从而触发上下文切换,上下文切换过多会造成内核占据较多的CPU的使用。

运行队列:
每个CPU核都维护一个可运行的线程队列。系统的load主要由CPU的运行队列来决定。
运行队列值越大,就意味着线程会要消耗越长的时间才能执行完成。

利用率:
CPU在用户进程、内核、中断处理、IO等待、空闲,这五个部分使用百分比。


文件IO消耗分析
Linux在操作文件时,将数据放入文件缓存区,直到内存不够或系统要释放内存给用户进程使用。所以通常情况下只有写文件和第一次读取文件时会产生真正的文件IO。
对于Java应用,造成文件IO消耗高主要是多个线程需要进行大量内容写入(例如频繁的日志写入)的动作、磁盘设备本身的处理速度慢、文件系统慢、操作的文件本身已经很大。


网络IO消耗分析
对于分布式Java应用,网卡中断是不是均衡分配到各CPU(cat/proc/interrupts查看)。


内存消耗分析(-Xms和-Xmx设为相同的值,避免运行期JVM堆内存要不断申请内存)
对于Java应用,内存的消耗主要在Java堆内存上,只有创建线程和使用Direct ByteBuffer才会操作JVM堆外的内存。
JVM内存消耗过多会导致GC执行频繁,CPU消耗增加,应用线程的执行速度严重下降,甚至造成OutOfMemoryError,最终导致Java进程退出。

JVM堆外的内存
swap的消耗、物理内存的消耗、JVM内存的消耗。

程序执行慢原因分析

锁竞争激烈:很多线程竞争互斥资源,但资源有限, 造成其他线程都处于等待状态。

未充分使用硬件资源:线程操作被串行化。

数据量增长:单表数据量太大(如1个亿)造成数据库读写速度大幅下降(操作此表)。

调优

JVM调优(最关键参数为:-Xms -Xmx -Xmn -XX:SurvivorRatio -XX:MaxTenuringThreshold)

代大小调优:避免新生代大小设置过小、避免新生代大小设置过大、避免Survivor设置过小或过大、合理设置新生代存活周期。

-Xmn 调整新生代大小,新生代越大通常也意味着更多对象会在minor GC阶段被回收,但可能有可能造成旧生代大小,造成频繁触发Full GC,甚至是OutOfMemoryError。

-XX:SurvivorRatio调整Eden区与Survivor区的大小,Eden 区越大通常也意味着minor GC发生频率越低,但可能有可能造成Survivor区太小,导致对象minor GC后就直接进入旧生代,从而更频繁触发Full GC。

GC策略的调优:CMS GC多数动作是和应用并发进行的,确实可以减小GC动作给应用造成的暂停时间。对于Web应用非常需要一个对应用造成暂停时间短的GC,再加上Web应用 的瓶颈都不在CPU上,在G1还不够成熟的情况下,CMS GC是不错的选择。

(如果系统不是CPU密集型,且从新生代进入旧生代的大部分对象是可以回收的,那么采用CMS GC可以更好地在旧生代满之前完成对象的回收,更大程度降低Full GC发生的可能)

在调整了内存管理方面的参数后应通过-XX:PrintGCDetails、-XX:+PrintGCTimeStamps、 -XX:+PrintGCApplicationStoppedTime以及jstat或visualvm等方式观察调整后的GC状况。

出内存管理以外的其他方面的调优参数:-XX:CompileThreshold、-XX:+UseFastAccessorMethods、 -XX:+UseBaiasedLocking。

程序调优

CPU消耗严重的解决方法

CPU us高的解决方法:

CPU us 高的原因主要是执行线程不需要任何挂起动作,且一直执行,导致CPU 没有机会去调度执行其他的线程。

调优方案: 增加Thread.sleep,以释放CPU 的执行权,降低CPU 的消耗。以损失单次执行性能为代价的,但由于其降低了CPU 的消耗,对于多线程的应用而言,反而提高了总体的平均性能。

(在实际的Java应用中类似场景, 对于这种场景最佳方式是改为采用wait/notify机制)

对于其他类似循环次数过多、正则、计算等造成CPU us过高的状况, 则需要结合业务调优。

对于GC频繁,则需要通过JVM调优或程序调优,降低GC的执行次数。

CPU sy高的解决方法:

CPU sy 高的原因主要是线程的运行状态要经常切换,对于这种情况,常见的一种优化方法是减少线程数。

调优方案: 将线程数降低

这种调优过后有可能会造成CPU us过高,所以合理设置线程数非常关键。

对于Java分布式应用,还有一种典型现象是应用中有较多的网络IO操作和确实需要一些锁竞争机制(如数据库连接池),但为了能够支撑搞得并发量,可采用协程(Coroutine)来支撑更高的并发量,避免并发量上涨后造成CPU sy消耗严重、系统load迅速上涨和系统性能下降。

在Java中实现协程的框架有Kilim,Kilim执行一项任务创建Task,使用Task的暂停机制,而不是Thread,Kilim承担了线程调度以及上下切换动作,Task相对于原生Thread而言就轻量级多了,且能更好利用CPU。Kilim带来的是线程使用率的提升,但同时由于要在JVM堆中保存Task上下文信息,因此在采用Kilim的情况下要消耗更多的内存。(目前JDK 7中也有一个支持协程方式的实现,另外基于JVM的Scala的Actor也可用于在Java使用协程)

文件IO消耗严重的解决方法

从程序的角度而言,造成文件IO消耗严重的原因主要是多个线程在写进行大量的数据到同一文件,导致文件很快变得很大,从而写入速度越来越慢,并造成各线程激烈争抢文件锁。

常用调优方法:

异步写文件

批量读写

限流

限制文件大小

网络IO消耗严重的解决方法

从程序的角度而言,造成网络IO消耗严重的原因主要是同时需要发送或接收的包太多。

常用调优方法:

限流,限流通常是限制发送packet的频率,从而在网络IO消耗可接受的情况下来发送packget。

内存消耗严重的解决方法

释放不必要的引用:代码持有了不需要的对象引用,造成这些对象无法被GC,从而占据了JVM堆内存。(使用ThreadLocal:注意在线程内动作执行完毕时,需执行ThreadLocal.set把对象清除,避免持有不必要的对象引用)

使用对象缓存池:创建对象要消耗一定的CPU以及内存,使用对象缓存池一定程度上可降低JVM堆内存的使用。

采用合理的缓存失效算法:如果放入太多对象在缓存池中,反而会造成内存的严重消耗, 同时由于缓存池一直对这些对象持有引用,从而造成Full GC增多,对于这种状况要合理控制缓存池的大小,避免缓存池的对象数量无限上涨。(经典的缓存失效算法来清除缓存池中的对象:FIFO、LRU、LFU等)

合理使用SoftReference和WeekReference:SoftReference的对象会在内存不够用的时候回收,WeekReference的对象会在Full GC的时候回收。

资源消耗不多但程序执行慢的情况的解决方法

降低锁竞争: 多线多了,锁竞争的状况会比较明显,这时候线程很容易处于等待锁的状况,从而导致性能下降以及CPU sy上升。

使用并发包中的类:大多数采用了lock-free、nonblocking算法。

使用Treiber算法:基于CAS以及AtomicReference。

使用Michael-Scott非阻塞队列算法:基于CAS以及AtomicReference,典型ConcurrentLindkedQueue。

(基于CAS和AtomicReference来实现无阻塞是不错的选择,但值得注意的是,lock-free算法需不断的循环比较来保证资源的一致性的,对于冲突较多的应用场景而言,会带来更高的CPU消耗,因此不一定采用CAS实现无阻塞的就一定比采用lock方式的性能好。 还有一些无阻塞算法的改进:MCAS、WSTM等)

尽可能少用锁:尽可能只对需要控制的资源做加锁操作(通常没有必要对整个方法加锁,尽可能让锁最小化,只对互斥及原子操作的地方加锁,加锁时尽可能以保护资源的最小化粒度为单位--如只对需要保护的资源加锁而不是this)。

拆分锁:独占锁拆分为多把锁(读写锁拆分、类似ConcurrentHashMap中默认拆分为16把锁),很多程度上能提高读写的性能,但需要注意在采用拆分锁后,全局性质的操作会变得比较复杂(如ConcurrentHashMap中size操作)。(拆分锁太多也会造成副作用,如CPU消耗明显增加)

去除读写操作的互斥:在修改时加锁,并复制对象进行修改,修改完毕后切换对象的引用,从而读取时则不加锁。这种称为CopyOnWrite,CopyOnWriteArrayList是典型实现,好处是可以明显提升读的性能,适合读多写少的场景, 但由于写操作每次都要复制一份对象,会消耗更多的内存。

充分利用硬件资源(CPU和内存):

充分利用CPU

在能并行处理的场景中未使用足够的线程(线程增加:CPU资源消耗可接受且不会带来激烈竞争锁的场景下), 例如单线程的计算,可以拆分为多个线程分别计算,最后将结果合并,JDK 7中的fork-join框架。

Amdahl定律公式:1/(F+(1-F)/N)。

充分利用内存

数据的缓存、耗时资源的缓存(数据库连接创建、网络连接的创建等)、页面片段的缓存。

毕竟内存的读取肯定远快于硬盘、网络的读取, 在内存消耗可接受、GC频率、以及系统结构(例如集群环境可能会带来缓存的同步)可接受情况下,应充分利用内存来缓存数据,提升系统的性能。

总结:

好的调优策略是收益比(调优后提升的效果/调优改动所需付出的代价)最高的,通常来说简单的系统调优比较好做,因此尽量保持单机上应用的纯粹性, 这是大型系统的基本架构原则。

调优的三大有效原则:充分而不过分使用硬件资源、合理调整JVM、合理使用JDK包。

学习参考资料:

《分布式Java应用:基础与实践》

补充《分布式Java应用:基础与实践》一些代码样例:

cpu-----------------------------------

CpuNotUseEffectiveDemo

  1. /**
  2. *
  3. */
  4. packagetune.program.cpu;
  5. importjava.util.ArrayList;
  6. importjava.util.List;
  7. importjava.util.Random;
  8. /**
  9. *未充分利用CPU:在能并行处理的场景中未使用足够的线程(线程增加:CPU资源消耗可接受且不会带来激烈竞争锁的场景下)
  10. *
  11. *@authoryangwmAug25,20109:54:50AM
  12. */
  13. publicclassCpuNotUseEffectiveDemo{
  14. privatestaticintexecuteTimes=10;
  15. privatestaticinttaskCount=200;
  16. publicstaticvoidmain(String[]args)throwsException{
  17. Tasktask=newTask();
  18. for(inti=0;i<taskCount;i++){
  19. task.addTask(Integer.toString(i));
  20. }
  21. longbeginTime=System.currentTimeMillis();
  22. for(inti=0;i<executeTimes;i++){
  23. System.out.println("Round:"+(i+1));
  24. Threadthread=newThread(task);
  25. thread.start();
  26. thread.join();
  27. }
  28. longendTime=System.currentTimeMillis();
  29. System.out.println("Executesummary:Round("+executeTimes+")TaskCountPerRound("+taskCount
  30. +")ExecuteTime("+(endTime-beginTime)+")ms");
  31. }
  32. staticclassTaskimplementsRunnable{
  33. List<String>tasks=newArrayList<String>();
  34. Randomrandom=newRandom();
  35. booleanexitFlag=false;
  36. publicvoidaddTask(Stringtask){
  37. List<String>copyTasks=newArrayList<String>(tasks);
  38. copyTasks.add(task);
  39. tasks=copyTasks;
  40. }
  41. @Override
  42. publicvoidrun(){
  43. List<String>runTasks=tasks;
  44. List<String>removeTasks=newArrayList<String>();
  45. for(Stringtask:runTasks){
  46. try{
  47. Thread.sleep(random.nextInt(10));
  48. }catch(Exceptione){
  49. e.printStackTrace();
  50. }
  51. removeTasks.add(task);
  52. }
  53. try{
  54. Thread.sleep(10);
  55. }catch(Exceptione){
  56. e.printStackTrace();
  57. }
  58. }
  59. }
  60. }
  61. /*
  62. Round:1
  63. ......
  64. Round:10
  65. Executesummary:Round(10)TaskCountPerRound(200)ExecuteTime(10687)ms
  66. */

CpuUseEffectiveDemo

  1. /**
  2. *
  3. */
  4. packagetune.program.cpu;
  5. importjava.util.ArrayList;
  6. importjava.util.List;
  7. importjava.util.Random;
  8. importjava.util.concurrent.CountDownLatch;
  9. /**
  10. *充分利用CPU:在能并行处理的场景中使用足够的线程(线程增加:CPU资源消耗可接受且不会带来激烈竞争锁的场景下)
  11. *
  12. *@authoryangwmAug25,20109:54:50AM
  13. */
  14. publicclassCpuUseEffectiveDemo{
  15. privatestaticintexecuteTimes=10;
  16. privatestaticinttaskCount=200;
  17. privatestaticfinalintTASK_THREADCOUNT=16;
  18. privatestaticCountDownLatchlatch;
  19. publicstaticvoidmain(String[]args)throwsException{
  20. Task[]tasks=newTask[TASK_THREADCOUNT];
  21. for(inti=0;i<TASK_THREADCOUNT;i++){
  22. tasks[i]=newTask();
  23. }
  24. for(inti=0;i<taskCount;i++){
  25. intmod=i%TASK_THREADCOUNT;
  26. tasks[mod].addTask(Integer.toString(i));
  27. }
  28. longbeginTime=System.currentTimeMillis();
  29. for(inti=0;i<executeTimes;i++){
  30. System.out.println("Round:"+(i+1));
  31. latch=newCountDownLatch(TASK_THREADCOUNT);
  32. for(intj=0;j<TASK_THREADCOUNT;j++){
  33. Threadthread=newThread(tasks[j]);
  34. thread.start();
  35. }
  36. latch.await();
  37. }
  38. longendTime=System.currentTimeMillis();
  39. System.out.println("Executesummary:Round("+executeTimes+")TaskCountPerRound("+taskCount
  40. +")ExecuteTime("+(endTime-beginTime)+")ms");
  41. }
  42. staticclassTaskimplementsRunnable{
  43. List<String>tasks=newArrayList<String>();
  44. Randomrandom=newRandom();
  45. booleanexitFlag=false;
  46. publicvoidaddTask(Stringtask){
  47. List<String>copyTasks=newArrayList<String>(tasks);
  48. copyTasks.add(task);
  49. tasks=copyTasks;
  50. }
  51. @Override
  52. publicvoidrun(){
  53. List<String>runTasks=tasks;
  54. List<String>removeTasks=newArrayList<String>();
  55. for(Stringtask:runTasks){
  56. try{
  57. Thread.sleep(random.nextInt(10));
  58. }catch(Exceptione){
  59. e.printStackTrace();
  60. }
  61. removeTasks.add(task);
  62. }
  63. try{
  64. Thread.sleep(10);
  65. }catch(Exceptione){
  66. e.printStackTrace();
  67. }
  68. latch.countDown();
  69. }
  70. }
  71. }
  72. /*
  73. Round:1
  74. ......
  75. Round:10
  76. Executesummary:Round(10)TaskCountPerRound(200)ExecuteTime(938)ms
  77. */

fileio-------------------------------------------------------------------

IOWaitHighDemo

  1. /**
  2. *
  3. */
  4. packagetune.program.fileio;
  5. importjava.io.BufferedWriter;
  6. importjava.io.File;
  7. importjava.io.FileWriter;
  8. importjava.util.Random;
  9. /**
  10. *文件IO消耗严重的原因主要是多个线程在写进行大量的数据到同一文件,
  11. *导致文件很快变得很大,从而写入速度越来越慢,并造成各线程激烈争抢文件锁。
  12. *
  13. *@authoryangwmAug21,20109:48:34PM
  14. */
  15. publicclassIOWaitHighDemo{
  16. privateStringfileName="iowait.log";
  17. privatestaticintthreadCount=Runtime.getRuntime().availableProcessors();
  18. privateRandomrandom=newRandom();
  19. publicstaticvoidmain(String[]args)throwsException{
  20. if(args.length==1){
  21. threadCount=Integer.parseInt(args[1]);
  22. }
  23. IOWaitHighDemodemo=newIOWaitHighDemo();
  24. demo.runTest();
  25. }
  26. privatevoidrunTest()throwsException{
  27. Filefile=newFile(fileName);
  28. file.createNewFile();
  29. for(inti=0;i<threadCount;i++){
  30. newThread(newTask()).start();
  31. }
  32. }
  33. classTaskimplementsRunnable{
  34. @Override
  35. publicvoidrun(){
  36. while(true){
  37. try{
  38. StringBuilderstrBuilder=newStringBuilder("====begin====/n");
  39. StringthreadName=Thread.currentThread().getName();
  40. for(inti=0;i<100000;i++){
  41. strBuilder.append(threadName);
  42. strBuilder.append("/n");
  43. }
  44. strBuilder.append("====end====/n");
  45. BufferedWriterwriter=newBufferedWriter(newFileWriter(fileName,true));
  46. writer.write(strBuilder.toString());
  47. writer.close();
  48. Thread.sleep(random.nextInt(10));
  49. }catch(Exceptione){
  50. }
  51. }
  52. }
  53. }
  54. }
  55. /*
  56. C:/DocumentsandSettings/yangwm>jstack2656
  57. 2010-08-2123:24:17
  58. FullthreaddumpJavaHotSpot(TM)ClientVM(17.0-b05mixedmode):
  59. "DestroyJavaVM"prio=6tid=0x00868c00nid=0xde0waitingoncondition[0x00000000]
  60. java.lang.Thread.State:RUNNABLE
  61. "Thread-1"prio=6tid=0x0ab9dc00nid=0xb7crunnable[0x0b0bf000]
  62. java.lang.Thread.State:RUNNABLE
  63. atjava.io.FileOutputStream.close0(NativeMethod)
  64. atjava.io.FileOutputStream.close(FileOutputStream.java:336)
  65. atsun.nio.cs.StreamEncoder.implClose(StreamEncoder.java:320)
  66. atsun.nio.cs.StreamEncoder.close(StreamEncoder.java:149)
  67. -locked<0x034dd268>(ajava.io.FileWriter)
  68. atjava.io.OutputStreamWriter.close(OutputStreamWriter.java:233)
  69. atjava.io.BufferedWriter.close(BufferedWriter.java:265)
  70. -locked<0x034dd268>(ajava.io.FileWriter)
  71. attune.IOWaitHighDemo$Task.run(IOWaitHighDemo.java:58)
  72. atjava.lang.Thread.run(Thread.java:717)
  73. "Thread-0"prio=6tid=0x0ab9d400nid=0x80crunnable[0x0b06f000]
  74. java.lang.Thread.State:RUNNABLE
  75. atjava.io.FileOutputStream.writeBytes(NativeMethod)
  76. atjava.io.FileOutputStream.write(FileOutputStream.java:292)
  77. atsun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
  78. atsun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:282)
  79. atsun.nio.cs.StreamEncoder.write(StreamEncoder.java:125)
  80. -locked<0x034e1290>(ajava.io.FileWriter)
  81. atjava.io.OutputStreamWriter.write(OutputStreamWriter.java:207)
  82. atjava.io.BufferedWriter.flushBuffer(BufferedWriter.java:128)
  83. -locked<0x034e1290>(ajava.io.FileWriter)
  84. atjava.io.BufferedWriter.write(BufferedWriter.java:229)
  85. -locked<0x034e1290>(ajava.io.FileWriter)
  86. atjava.io.Writer.write(Writer.java:157)
  87. attune.IOWaitHighDemo$Task.run(IOWaitHighDemo.java:57)
  88. atjava.lang.Thread.run(Thread.java:717)
  89. "LowMemoryDetector"daemonprio=6tid=0x0ab6f800nid=0xfb0runnable[0x00000000]
  90. java.lang.Thread.State:RUNNABLE
  91. "CompilerThread0"daemonprio=10tid=0x0ab6c800nid=0x5fcwaitingoncondition[0x00000000]
  92. java.lang.Thread.State:RUNNABLE
  93. "AttachListener"daemonprio=10tid=0x0ab67800nid=0x6fcwaitingoncondition[0x00000000]
  94. java.lang.Thread.State:RUNNABLE
  95. "SignalDispatcher"daemonprio=10tid=0x0ab66800nid=0x5a0runnable[0x00000000]
  96. java.lang.Thread.State:RUNNABLE
  97. "Finalizer"daemonprio=8tid=0x0ab54000nid=0xe74inObject.wait()[0x0ac8f000]
  98. java.lang.Thread.State:WAITING(onobjectmonitor)
  99. atjava.lang.Object.wait(NativeMethod)
  100. -waitingon<0x02f15d90>(ajava.lang.ref.ReferenceQueue$Lock)
  101. atjava.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:135)
  102. -locked<0x02f15d90>(ajava.lang.ref.ReferenceQueue$Lock)
  103. atjava.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:151)
  104. atjava.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:177)
  105. "ReferenceHandler"daemonprio=10tid=0x0ab4f800nid=0x8a4inObject.wait()[0x0ac3f000]
  106. java.lang.Thread.State:WAITING(onobjectmonitor)
  107. atjava.lang.Object.wait(NativeMethod)
  108. -waitingon<0x02f15af8>(ajava.lang.ref.Reference$Lock)
  109. atjava.lang.Object.wait(Object.java:502)
  110. atjava.lang.ref.Reference$ReferenceHandler.run(Reference.java:133)
  111. -locked<0x02f15af8>(ajava.lang.ref.Reference$Lock)
  112. "VMThread"prio=10tid=0x0ab4a800nid=0x1d0runnable
  113. "VMPeriodicTaskThread"prio=10tid=0x0ab7d400nid=0x464waitingoncondition
  114. JNIglobalreferences:693
  115. C:/DocumentsandSettings/yangwm>
  116. */

LogControl

  1. /**
  2. *
  3. */
  4. packagetune.program.fileio;
  5. importjava.util.concurrent.atomic.AtomicInteger;
  6. /**
  7. *日志控制:采用简单策略为统计一段时间内日志输出频率,当超出这个频率时,一段时间内不再写log
  8. *
  9. *@authoryangwmAug24,201010:41:43AM
  10. */
  11. publicclassLogControl{
  12. publicstaticvoidmain(String[]args){
  13. for(inti=1;i<=1000;i++){
  14. if(LogControl.isLog()){
  15. //logger.error(errorInfo,throwable);
  16. System.out.println("errorInfo"+i);
  17. }
  18. //
  19. if(i%100==0){
  20. try{
  21. Thread.sleep(1000);
  22. }catch(InterruptedExceptione){
  23. e.printStackTrace();
  24. }
  25. }
  26. }
  27. }
  28. privatestaticfinallongINTERVAL=1000;
  29. privatestaticfinallongPUNISH_TIME=5000;
  30. privatestaticfinalintERROR_THRESHOLD=100;
  31. privatestaticAtomicIntegercount=newAtomicInteger(0);
  32. privatestaticlongbeginTime;
  33. privatestaticlongpunishTimeEnd;
  34. //由于控制不用非常精确,因此忽略此处的并发问题
  35. publicstaticbooleanisLog(){
  36. //System.out.println(count.get()+","+beginTime+","+punishTimeEnd+","+System.currentTimeMillis());
  37. //不写日志阶段
  38. if(punishTimeEnd>0&&punishTimeEnd>System.currentTimeMillis()){
  39. returnfalse;
  40. }
  41. //重新计数
  42. if(count.getAndIncrement()==0){
  43. beginTime=System.currentTimeMillis();
  44. returntrue;
  45. }else{//已在计数
  46. //超过阀门值,设置count为0并设置一段时间内不写日志
  47. if(count.get()>ERROR_THRESHOLD){
  48. count.set(0);
  49. punishTimeEnd=PUNISH_TIME+System.currentTimeMillis();
  50. returnfalse;
  51. }
  52. //没超过阀门值,且当前时间已超过计数周期,则重新计算
  53. elseif(System.currentTimeMillis()>(beginTime+INTERVAL)){
  54. count.set(0);
  55. }
  56. returntrue;
  57. }
  58. }
  59. }
  60. /*
  61. errorInfo1
  62. errorInfo2
  63. ......
  64. errorInfo99
  65. errorInfo100
  66. errorInfo601
  67. errorInfo602
  68. ......
  69. errorInfo699
  70. errorInfo700
  71. */

memory-------------------------------------------------------------------

MemoryHighDemo

  1. /**
  2. *
  3. */
  4. packagetune.program.memory;
  5. importjava.nio.ByteBuffer;
  6. /**
  7. *directbytebuffer消耗的是jvm堆外的内存,但同样是基于GC方式来释放的。
  8. *
  9. *@authoryangwmAug21,20109:40:18PM
  10. */
  11. publicclassMemoryHighDemo{
  12. publicstaticvoidmain(String[]args)throwsException{
  13. Thread.sleep(20000);
  14. System.out.println("readtocreatebytes,sojvmheapwillbeused");
  15. byte[]bytes=newbyte[128*1000*1000];
  16. bytes[0]=1;
  17. bytes[1]=2;
  18. Thread.sleep(10000);
  19. System.out.println("readtoallocate&putdirectbytebuffer,nojvmheapshouldbeused");
  20. ByteBufferbuffer=ByteBuffer.allocateDirect(128*1024*1024);
  21. buffer.put(bytes);
  22. buffer.flip();
  23. Thread.sleep(10000);
  24. System.out.println("readytogc,jvmheapwillbefreed");
  25. bytes=null;
  26. System.gc();
  27. Thread.sleep(10000);
  28. System.out.println("readtogetbytes,thenjvmheapwillbeused");
  29. byte[]resultbytes=newbyte[128*1000*1000];
  30. buffer.get(resultbytes);
  31. System.out.println("resultbytes[1]is:"+resultbytes[1]);
  32. Thread.sleep(10000);
  33. System.out.println("readtogcall");
  34. buffer=null;
  35. resultbytes=null;
  36. System.gc();
  37. Thread.sleep(10000);
  38. }
  39. }
  40. /*
  41. D:/study/tempProject/JavaLearn/classes>java-Xms140M-Xmx140Mtune.MemoryHighDemo
  42. readtocreatebytes,sojvmheapwillbeused
  43. readtoallocate&putdirectbytebuffer,nojvmheapshouldbeused
  44. readytogc,jvmheapwillbefreed
  45. readtogetbytes,thenjvmheapwillbeused
  46. resultbytes[1]is:2
  47. readtogcall
  48. */

ObjectCachePool

  1. /**
  2. *
  3. */
  4. packagetune.program.memory;
  5. importjava.util.LinkedHashMap;
  6. importjava.util.Map;
  7. importjava.util.Set;
  8. /**
  9. *采用合理的缓存失效算法:FIFO、LRU、LFU等
  10. *
  11. *@authoryangwmAug24,20106:06:48PM
  12. */
  13. publicclassObjectCachePool<K,V>{
  14. publicstaticvoidmain(String[]args){
  15. //FIFO_POLICY
  16. intsize=10;
  17. intpolicy=1;
  18. ObjectCachePool<Integer,Integer>objectCachePool=newObjectCachePool<Integer,Integer>(size,policy);
  19. for(inti=1;i<=15;i++){
  20. objectCachePool.put(i,i);
  21. }
  22. for(inti=15;i>=1;i--){
  23. objectCachePool.put(i,i);
  24. }
  25. System.out.println("size("+size+"),policy("+policy+")FIFO");
  26. for(Map.Entry<Integer,Integer>entry:objectCachePool.entrySet()){
  27. System.out.println(entry.getKey()+","+entry.getValue());
  28. }
  29. //LRU_POLICY
  30. size=10;
  31. policy=2;
  32. objectCachePool=newObjectCachePool<Integer,Integer>(size,policy);
  33. for(inti=1;i<=15;i++){
  34. objectCachePool.put(i,i);
  35. }
  36. for(inti=15;i>=1;i--){
  37. objectCachePool.put(i,i);
  38. }
  39. System.out.println("size("+size+"),policy("+policy+")LRU");
  40. for(Map.Entry<Integer,Integer>entry:objectCachePool.entrySet()){
  41. System.out.println(entry.getKey()+","+entry.getValue());
  42. }
  43. }
  44. privatestaticfinalintFIFO_POLICY=1;
  45. privatestaticfinalintLRU_POLICY=2;
  46. privatestaticfinalintDEFAULT_SIZE=10;
  47. privateMap<K,V>cacheObjects;
  48. publicObjectCachePool(){
  49. this(DEFAULT_SIZE);
  50. }
  51. publicObjectCachePool(intsize){
  52. this(size,FIFO_POLICY);
  53. }
  54. publicObjectCachePool(finalintsize,finalintpolicy){
  55. switch(policy){
  56. caseFIFO_POLICY:
  57. cacheObjects=newLinkedHashMap<K,V>(size){
  58. /**
  59. *
  60. */
  61. privatestaticfinallongserialVersionUID=1L;
  62. protectedbooleanremoveEldestEntry(Map.Entry<K,V>eldest){
  63. returnsize()>size;
  64. }
  65. };
  66. break;
  67. caseLRU_POLICY:
  68. cacheObjects=newLinkedHashMap<K,V>(size,0.75f,true){
  69. /**
  70. *
  71. */
  72. privatestaticfinallongserialVersionUID=1L;
  73. protectedbooleanremoveEldestEntry(Map.Entry<K,V>eldest){
  74. returnsize()>size;
  75. }
  76. };
  77. break;
  78. default:
  79. thrownewIllegalArgumentException("Unknownpolicy:"+policy);
  80. }
  81. }
  82. publicvoidput(Kkey,Vvalue){
  83. cacheObjects.put(key,value);
  84. }
  85. publicvoidget(Kkey){
  86. cacheObjects.get(key);
  87. }
  88. publicvoidremove(Kkey){
  89. cacheObjects.remove(key);
  90. }
  91. publicvoidclear(){
  92. cacheObjects.clear();
  93. }
  94. publicSet<Map.Entry<K,V>>entrySet(){
  95. returncacheObjects.entrySet();
  96. }
  97. }
  98. /*
  99. size(10),policy(1)FIFO
  100. 11,11
  101. 12,12
  102. 13,13
  103. 14,14
  104. 15,15
  105. 5,5
  106. 4,4
  107. 3,3
  108. 2,2
  109. 1,1
  110. size(10),policy(2)LRU
  111. 10,10
  112. 9,9
  113. 8,8
  114. 7,7
  115. 6,6
  116. 5,5
  117. 4,4
  118. 3,3
  119. 2,2
  120. 1,1
  121. */

ObjectPoolDemo

  1. /**
  2. *
  3. */
  4. packagetune.program.memory;
  5. importjava.util.HashMap;
  6. importjava.util.Map;
  7. importjava.util.concurrent.CountDownLatch;
  8. /**
  9. *使用对象缓存池:创建对象要消耗一定的CPU以及内存,使用对象缓存池一定程度上可降低JVM堆内存的使用。
  10. *
  11. *@authoryangwmAug24,20104:34:47PM
  12. */
  13. publicclassObjectPoolDemo{
  14. privatestaticintexecuteTimes=10;
  15. privatestaticintmaxFactor=10;
  16. privatestaticintthreadCount=100;
  17. privatestaticfinalintNOTUSE_OBJECTPOOL=1;
  18. privatestaticfinalintUSE_OBJECTPOOL=2;
  19. privatestaticintrunMode=NOTUSE_OBJECTPOOL;
  20. privatestaticCountDownLatchlatch=null;
  21. publicstaticvoidmain(String[]args)throwsException{
  22. Tasktask=newTask();
  23. longbeginTime=System.currentTimeMillis();
  24. for(inti=0;i<executeTimes;i++){
  25. System.out.println("Round:"+(i+1));
  26. latch=newCountDownLatch(threadCount);
  27. for(intj=0;j<threadCount;j++){
  28. newThread(task).start();
  29. }
  30. latch.await();
  31. }
  32. longendTime=System.currentTimeMillis();
  33. System.out.println("Executesummary:Round("+executeTimes+")ThreadPerRound("+threadCount
  34. +")ObjectFactor("+maxFactor+")ExecuteTime("+(endTime-beginTime)+")ms");
  35. }
  36. staticclassTaskimplementsRunnable{
  37. @Override
  38. publicvoidrun(){
  39. for(intj=0;j<maxFactor;j++){
  40. if(runMode==USE_OBJECTPOOL){
  41. BigObjectPool.getInstance().getBigObject(j);
  42. }else{
  43. newBigObject(j);
  44. }
  45. }
  46. latch.countDown();
  47. }
  48. }
  49. staticclassBigObjectPool{
  50. privatestaticfinalBigObjectPoolself=newBigObjectPool();
  51. privatefinalMap<Integer,BigObject>cacheObjects=newHashMap<Integer,BigObject>();
  52. privateBigObjectPool(){
  53. }
  54. publicstaticBigObjectPoolgetInstance(){
  55. returnself;
  56. }
  57. publicBigObjectgetBigObject(intfactor){
  58. if(cacheObjects.containsKey(factor)){
  59. returncacheObjects.get(factor);
  60. }else{
  61. BigObjectobject=newBigObject(factor);
  62. cacheObjects.put(factor,object);
  63. returnobject;
  64. }
  65. }
  66. }
  67. staticclassBigObject{
  68. privatebyte[]bytes=null;
  69. publicBigObject(intfactor){
  70. bytes=newbyte[(factor+1)*1024*1024];
  71. }
  72. publicbyte[]getBytes(){
  73. returnbytes;
  74. }
  75. }
  76. }
  77. /*
  78. -Xms128M-Xmx128M-Xmn64M,runModeisNOTUSE_OBJECTPOOL:
  79. Round:1
  80. ......
  81. Executesummary:Round(10)ThreadPerRound(100)ObjectFactor(10)ExecuteTime(50672)ms
  82. -Xms128M-Xmx128M-Xmn64M,runModeisUSE_OBJECTPOOL:
  83. Round:1
  84. ......
  85. Executesummary:Round(10)ThreadPerRound(100)ObjectFactor(10)ExecuteTime(344)ms
  86. */

ThreadLocalDemo

  1. /**
  2. *
  3. */
  4. packagetune.program.memory;
  5. importjava.util.concurrent.ExecutorService;
  6. importjava.util.concurrent.Executors;
  7. /**
  8. *释放不必要的引用:代码持有了不需要的对象引用,造成这些对象无法被GC,从而占据了JVM堆内存。
  9. *(使用ThreadLocal:注意在线程内动作执行完毕时,需执行ThreadLocal.set把对象清除,避免持有不必要的对象引用)
  10. *
  11. *@authoryangwmAug24,201011:29:59AM
  12. */
  13. publicclassThreadLocalDemo{
  14. publicstaticvoidmain(String[]args){
  15. ThreadLocalDemodemo=newThreadLocalDemo();
  16. demo.run();
  17. }
  18. publicvoidrun(){
  19. ExecutorServiceexecutor=Executors.newFixedThreadPool(1);
  20. executor.execute(newTask());
  21. System.gc();
  22. }
  23. classTaskimplementsRunnable{
  24. @Override
  25. publicvoidrun(){
  26. ThreadLocal<byte[]>localString=newThreadLocal<byte[]>();
  27. localString.set(newbyte[1024*1024*30]);
  28. //业务逻辑
  29. //localString.set(null);//释放不必要的引用
  30. }
  31. }
  32. }

concurrent-----------------------------------------------------------------------

LockHotDemo

  1. /**
  2. *
  3. */
  4. packagetune.program.concurrent;
  5. importjava.util.Random;
  6. importjava.util.concurrent.CountDownLatch;
  7. importjava.util.concurrent.locks.Lock;
  8. importjava.util.concurrent.locks.ReentrantLock;
  9. /**
  10. *锁竞争的状况会比较明显,这时候线程很容易处于等待锁的状况,从而导致性能下降以及CPUsy上升
  11. *
  12. *@authoryangwmAug24,201011:59:35PM
  13. */
  14. publicclassLockHotDemo{
  15. privatestaticintexecuteTimes=10;
  16. privatestaticintthreadCount=Runtime.getRuntime().availableProcessors()*100;
  17. privatestaticCountDownLatchlatch=null;
  18. publicstaticvoidmain(String[]args)throwsException{
  19. HandleTasktask=newHandleTask();
  20. longbeginTime=System.currentTimeMillis();
  21. for(inti=0;i<executeTimes;i++){
  22. System.out.println("Round:"+(i+1));
  23. latch=newCountDownLatch(threadCount);
  24. for(intj=0;j<threadCount;j++){
  25. newThread(task).start();
  26. }
  27. latch.await();
  28. }
  29. longendTime=System.currentTimeMillis();
  30. System.out.println("Executesummary:Round("+executeTimes+")ThreadPerRound("+threadCount
  31. +")ExecuteTime("+(endTime-beginTime)+")ms");
  32. }
  33. staticclassHandleTaskimplementsRunnable{
  34. privatefinalRandomrandom=newRandom();
  35. @Override
  36. publicvoidrun(){
  37. Handler.getInstance().handle(random.nextInt(10000));
  38. latch.countDown();
  39. }
  40. }
  41. staticclassHandler{
  42. privatestaticfinalHandlerself=newHandler();
  43. privatefinalRandomrandom=newRandom();
  44. privatefinalLocklock=newReentrantLock();
  45. privateHandler(){
  46. }
  47. publicstaticHandlergetInstance(){
  48. returnself;
  49. }
  50. publicvoidhandle(intid){
  51. try{
  52. lock.lock();
  53. //executesth
  54. try{
  55. Thread.sleep(random.nextInt(10));
  56. }catch(Exceptione){
  57. e.printStackTrace();
  58. }
  59. }finally{
  60. lock.unlock();
  61. }
  62. }
  63. }
  64. }
  65. /*
  66. Round:1
  67. ......
  68. Round:10
  69. Executesummary:Round(10)ThreadPerRound(200)ExecuteTime(10625)ms
  70. */

ReduceLockHotDemo

  1. /**
  2. *
  3. */
  4. packagetune.program.concurrent;
  5. importjava.util.Random;
  6. importjava.util.concurrent.CountDownLatch;
  7. importjava.util.concurrent.locks.Lock;
  8. importjava.util.concurrent.locks.ReentrantLock;
  9. /**
  10. *尽可能少用锁:尽可能只对需要控制的资源做加锁操作
  11. *
  12. *@authoryangwmAug24,201011:59:35PM
  13. */
  14. publicclassReduceLockHotDemo{
  15. privatestaticintexecuteTimes=10;
  16. privatestaticintthreadCount=Runtime.getRuntime().availableProcessors()*100;
  17. privatestaticCountDownLatchlatch=null;
  18. publicstaticvoidmain(String[]args)throwsException{
  19. HandleTasktask=newHandleTask();
  20. longbeginTime=System.currentTimeMillis();
  21. for(inti=0;i<executeTimes;i++){
  22. System.out.println("Round:"+(i+1));
  23. latch=newCountDownLatch(threadCount);
  24. for(intj=0;j<threadCount;j++){
  25. newThread(task).start();
  26. }
  27. latch.await();
  28. }
  29. longendTime=System.currentTimeMillis();
  30. System.out.println("Executesummary:Round("+executeTimes+")ThreadPerRound("+threadCount
  31. +")ExecuteTime("+(endTime-beginTime)+")ms");
  32. }
  33. staticclassHandleTaskimplementsRunnable{
  34. privatefinalRandomrandom=newRandom();
  35. @Override
  36. publicvoidrun(){
  37. Handler.getInstance().handle(random.nextInt(10000));
  38. latch.countDown();
  39. }
  40. }
  41. staticclassHandler{
  42. privatestaticfinalHandlerself=newHandler();
  43. privatefinalRandomrandom=newRandom();
  44. privatefinalLocklock=newReentrantLock();
  45. privateHandler(){
  46. }
  47. publicstaticHandlergetInstance(){
  48. returnself;
  49. }
  50. publicvoidhandle(intid){
  51. //executesthdon'tneedlock
  52. try{
  53. Thread.sleep(random.nextInt(5));
  54. }catch(Exceptione){
  55. e.printStackTrace();
  56. }
  57. try{
  58. lock.lock();
  59. //executesth
  60. try{
  61. Thread.sleep(random.nextInt(5));
  62. }catch(Exceptione){
  63. e.printStackTrace();
  64. }
  65. }finally{
  66. lock.unlock();
  67. }
  68. }
  69. }
  70. }
  71. /*
  72. Round:1
  73. ......
  74. Round:10
  75. Executesummary:Round(10)ThreadPerRound(200)ExecuteTime(5547)ms
  76. */

SplitReduceLockHotDemo

  1. /**
  2. *
  3. */
  4. packagetune.program.concurrent;
  5. importjava.util.Random;
  6. importjava.util.concurrent.CountDownLatch;
  7. importjava.util.concurrent.locks.Lock;
  8. importjava.util.concurrent.locks.ReentrantLock;
  9. /**
  10. *尽可能少用锁:尽可能只对需要控制的资源做加锁操作
  11. *拆分锁:独占锁拆分为多把锁(读写锁拆分、类似ConcurrentHashMap中默认拆分为16把锁)
  12. *
  13. *@authoryangwmAug24,201011:59:35PM
  14. */
  15. publicclassSplitReduceLockHotDemo{
  16. privatestaticintexecuteTimes=10;
  17. privatestaticintthreadCount=Runtime.getRuntime().availableProcessors()*100;
  18. privatestaticCountDownLatchlatch=null;
  19. publicstaticvoidmain(String[]args)throwsException{
  20. HandleTasktask=newHandleTask();
  21. longbeginTime=System.currentTimeMillis();
  22. for(inti=0;i<executeTimes;i++){
  23. System.out.println("Round:"+(i+1));
  24. latch=newCountDownLatch(threadCount);
  25. for(intj=0;j<threadCount;j++){
  26. newThread(task).start();
  27. }
  28. latch.await();
  29. }
  30. longendTime=System.currentTimeMillis();
  31. System.out.println("Executesummary:Round("+executeTimes+")ThreadPerRound("+threadCount
  32. +")ExecuteTime("+(endTime-beginTime)+")ms");
  33. }
  34. staticclassHandleTaskimplementsRunnable{
  35. privatefinalRandomrandom=newRandom();
  36. @Override
  37. publicvoidrun(){
  38. Handler.getInstance().handle(random.nextInt(10000));
  39. latch.countDown();
  40. }
  41. }
  42. staticclassHandler{
  43. privatestaticfinalHandlerself=newHandler();
  44. privatefinalRandomrandom=newRandom();
  45. privateintlockCount=10;
  46. privateLock[]locks=newLock[lockCount];
  47. privateHandler(){
  48. for(inti=0;i<lockCount;i++){
  49. locks[i]=newReentrantLock();
  50. }
  51. }
  52. publicstaticHandlergetInstance(){
  53. returnself;
  54. }
  55. publicvoidhandle(intid){
  56. //executesthdon'tneedlock
  57. try{
  58. Thread.sleep(random.nextInt(5));
  59. }catch(Exceptione){
  60. e.printStackTrace();
  61. }
  62. intmod=id%lockCount;
  63. try{
  64. locks[mod].lock();
  65. //executesth
  66. try{
  67. Thread.sleep(random.nextInt(5));
  68. }catch(Exceptione){
  69. e.printStackTrace();
  70. }
  71. }finally{
  72. locks[mod].unlock();
  73. }
  74. }
  75. }
  76. }
  77. /*
  78. Round:1
  79. ......
  80. Round:10
  81. Executesummary:Round(10)ThreadPerRound(200)ExecuteTime(843)ms
  82. */

ConcurrentStack和StackBenchmark

  1. /**
  2. *
  3. */
  4. packagetune.program.concurrent;
  5. importjava.util.concurrent.atomic.AtomicReference;
  6. /**
  7. *使用Treiber算法实现Stack:基于CAS以及AtomicReference。
  8. *
  9. *@authoryangwmAug25,201010:50:17AM
  10. */
  11. publicclassConcurrentStack<E>{
  12. AtomicReference<Node<E>>head=newAtomicReference<Node<E>>();
  13. publicvoidpush(Eitem){
  14. Node<E>newHead=newNode<E>(item);
  15. Node<E>oldHead;
  16. do{
  17. oldHead=head.get();
  18. newHead.next=oldHead;
  19. }while(!head.compareAndSet(oldHead,newHead));
  20. }
  21. publicEpop(){
  22. Node<E>oldHead;
  23. Node<E>newHead;
  24. do{
  25. oldHead=head.get();
  26. if(oldHead==null){
  27. returnnull;
  28. }
  29. newHead=oldHead.next;
  30. }while(!head.compareAndSet(oldHead,newHead));
  31. returnoldHead.item;
  32. }
  33. staticclassNode<E>{
  34. finalEitem;
  35. Node<E>next;
  36. publicNode(Eitem){
  37. this.item=item;
  38. }
  39. }
  40. }
  41. /**
  42. *
  43. */
  44. packagetune.program.concurrent;
  45. importjava.util.Stack;
  46. importjava.util.concurrent.CountDownLatch;
  47. importjava.util.concurrent.CyclicBarrier;
  48. /**
  49. *基准测试:Treiber算法实现Stack、同步实现的Stack
  50. *
  51. *@authoryangwmAug25,201011:36:14AM
  52. */
  53. publicclassStackBenchmark{
  54. publicstaticvoidmain(String[]args)throwsException{
  55. StackBenchmarkstackBenchmark=newStackBenchmark();
  56. stackBenchmark.run();
  57. }
  58. privateStack<String>stack=newStack<String>();
  59. privateConcurrentStack<String>concurrentStack=newConcurrentStack<String>();
  60. privatestaticfinalintTHREAD_COUNT=300;
  61. privateCountDownLatchlatch=newCountDownLatch(THREAD_COUNT);
  62. privateCyclicBarrierbarrier=newCyclicBarrier(THREAD_COUNT);
  63. publicvoidrun()throwsException{
  64. StackTaskstackTask=newStackTask();
  65. longbeginTime=System.currentTimeMillis();
  66. for(inti=0;i<THREAD_COUNT;i++){
  67. newThread(stackTask).start();
  68. }
  69. latch.await();
  70. longendTime=System.currentTimeMillis();
  71. System.out.println("StackconsumeTime:"+(endTime-beginTime)+"ms");
  72. latch=newCountDownLatch(THREAD_COUNT);
  73. barrier=newCyclicBarrier(THREAD_COUNT);
  74. ConcurrentStackTaskconcurrentStackTask=newConcurrentStackTask();
  75. beginTime=System.currentTimeMillis();
  76. for(inti=0;i<THREAD_COUNT;i++){
  77. newThread(concurrentStackTask).start();
  78. }
  79. latch.await();
  80. endTime=System.currentTimeMillis();
  81. System.out.println("ConcurrentStackconsumeTime:"+(endTime-beginTime)+"ms");
  82. }
  83. classStackTaskimplementsRunnable{
  84. @Override
  85. publicvoidrun(){
  86. try{
  87. barrier.await();
  88. }catch(Exceptione){
  89. e.printStackTrace();
  90. }
  91. for(inti=0;i<10;i++){
  92. stack.push(Thread.currentThread().getName());
  93. stack.pop();
  94. }
  95. latch.countDown();
  96. }
  97. }
  98. classConcurrentStackTaskimplementsRunnable{
  99. @Override
  100. publicvoidrun(){
  101. try{
  102. barrier.await();
  103. }catch(Exceptione){
  104. e.printStackTrace();
  105. }
  106. for(inti=0;i<10;i++){
  107. concurrentStack.push(Thread.currentThread().getName());
  108. concurrentStack.pop();
  109. }
  110. latch.countDown();
  111. }
  112. }
  113. }
  114. /*
  115. StackconsumeTime:94ms
  116. ConcurrentStackconsumeTime:63ms
  117. StackconsumeTime:78ms
  118. ConcurrentStackconsumeTime:62ms
  119. */

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics