java中时间监视器_StopWatch任务执行时间监视器

本文通过Java的StopWatch类监控了两种不同的并发操作:`normaluse`和`gooduse`,其中`normaluse`使用ConcurrentHashMap进行同步操作,`gooduse`利用LongAdder实现线程安全计数。实验结果显示,`gooduse`的执行时间(286ms)比`normaluse`(1308ms)更优。StopWatch的输出详细展示了两个任务的执行时间占比。
摘要由CSDN通过智能技术生成

//循环次数

private static int LOOP_COUNT = 10000000;

//线程数量

//元素数量

private static int ITEM_COUNT1 = 10;

private static Map normaluse() throws InterruptedException {

ConcurrentHashMap freqs = new ConcurrentHashMap<>(ITEM_COUNT1);

ForkJoinPool forkJoinPool = new ForkJoinPool(THREAD_COUNT);

forkJoinPool.execute(() -> IntStream.rangeClosed(1, LOOP_COUNT).parallel().forEach(i -> {

//获得一个随机的Key

String key = "item" + ThreadLocalRandom.current().nextInt(ITEM_COUNT1);

synchronized (freqs) {

if (freqs.containsKey(key)) {

//Key存在则+1

freqs.put(key, freqs.get(key) + 1);

} else {

//Key不存在则初始化为1

freqs.put(key, 1L);

}

}

}

));

forkJoinPool.shutdown();

forkJoinPool.awaitTermination(1, TimeUnit.HOURS);

return freqs;

}

private static Map gooduse() throws InterruptedException {

ConcurrentHashMap freqs = new ConcurrentHashMap<>(ITEM_COUNT1);

ForkJoinPool forkJoinPool = new ForkJoinPool(THREAD_COUNT);

forkJoinPool.execute(() -> IntStream.rangeClosed(1, LOOP_COUNT).parallel().forEach(i -> {

String key = "item" + ThreadLocalRandom.current().nextInt(ITEM_COUNT1);

//利用computeIfAbsent()方法来实例化LongAdder,然后利用LongAdder来进行线程安全计数

freqs.computeIfAbsent(key, k -> new LongAdder()).increment();

}

));

forkJoinPool.shutdown();

forkJoinPool.awaitTermination(1, TimeUnit.HOURS);

//因为我们的Value是LongAdder而不是Long,所以需要做一次转换才能返回

return freqs.entrySet().stream()

.collect(Collectors.toMap(

e -> e.getKey(),

e -> e.getValue().longValue())

);

}

public static String good() throws InterruptedException {

StopWatch stopWatch = new StopWatch();

stopWatch.start("normaluse");

Map normaluse = normaluse();

stopWatch.stop();

//校验元素数量

Assert.isTrue(normaluse.size() == ITEM_COUNT1, "normaluse size error");

//校验累计总数

Assert.isTrue(normaluse.entrySet().stream()

.mapToLong(item -> item.getValue()).reduce(0, Long::sum) == LOOP_COUNT

, "normaluse count error");

stopWatch.start("gooduse");

Map gooduse = gooduse();

stopWatch.stop();

Assert.isTrue(gooduse.size() == ITEM_COUNT1, "gooduse size error");

Assert.isTrue(gooduse.entrySet().stream()

.mapToLong(item -> item.getValue())

.reduce(0, Long::sum) == LOOP_COUNT

, "gooduse count error");

log.info(stopWatch.prettyPrint());

return "OK";

}

执行结果:

-----------------------------------------

ms     %     Task name

-----------------------------------------

01308  082%  normaluse

00286  018%  gooduse

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值