最近学习了LongAdder和Striped64,打算写一个qps统计工具,刚好项目上也需要。
借鉴了一下前人的文章:https://www.cnblogs.com/ganRegister/p/9369131.html
优化点:
1、增加了一个最大qps的统计
2、最上锁部分的代码进行了一些简化
/** * 最大qps */ private volatile long maxSummary; try { enterNextBucketLock.lock(); //可以尝试用tryLock //其他线程出来 if (passTime - lastPassTimeCloseToTargetBucket >= bucketTimeSlice) { int nextTargetBucketPosition = (int) (passTime / bucketTimeSlice) % bucketNum; Bucket nextBucket = buckets[nextTargetBucketPosition]; if (!nextBucket.equals(currentBucket)) { //跨槽 long summary = buckets[targetBucketPosition].sum(); if (summary > maxSummary) { //增加了最大qps的统计 maxSummary = summary; } nextBucket.reset(passTime); //目标槽位变动 targetBucketPosition = nextTargetBucketPosition; } lastPassTimeCloseToTargetBucket = passTime; nextBucket.incr(); return; } else { currentBucket = buckets[targetBucketPosition]; } } finally { enterNextBucketLock.unlock(); }