【发布时间】:2013-04-13 05:18:36
【问题描述】:
我正在研究Multithreaded code,我正在尝试测量一个特定方法所花费的时间,因为我正在尝试对我们的大多数队友代码进行基准测试,就像我正在做Load and Performance 测试我们的Client code 和然后是我们的Service code。
所以对于这个性能测量,我正在使用-
System.nanoTime();
我有多线程代码,我从中生成多个线程并尝试测量该代码花费了多少时间。
下面是我试图测量任何代码性能的示例示例-在下面的代码中我试图测量-
beClient.getAttributes method
下面是代码-
public class BenchMarkTest {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
try {
for (int i = 0; i < 3 * 5; i++) {
executor.submit(new ThreadTask(i));
}
executor.shutdown();
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
} catch (InterruptedException e) {
}
}
}
下面是实现Runnable接口的类
class ThreadTask implements Runnable {
private int id;
public static ConcurrentHashMap<Long, AtomicLong> selectHistogram = new ConcurrentHashMap<Long, AtomicLong>();
public ThreadTask(int id) {
this.id = id;
}
@Override
public void run() {
long start = System.nanoTime();
attributes = beClient.getAttributes(columnsList);
long end = System.nanoTime() - start;
final AtomicLong before = selectHistogram.putIfAbsent(end / 1000000L, new AtomicLong(1L));
if (before != null) {
before.incrementAndGet();
}
}
}
无论我想测量什么代码,我通常将下面的行放在该方法的上方
long start = System.nanoTime();
这两行在相同的方法之后,但ConcurrentHashMap不同
long end = System.nanoTime() - start;
final AtomicLong before = selectHistogram.putIfAbsent(end / 1000000L, new AtomicLong(1L));
if (before != null) {
before.incrementAndGet();
}
今天我和我的一位资深人士开会,他说ConcurrentHashMap 的incrementAndGet 方法是一个阻塞调用。所以你的线程会在那里等待一段时间。
他让我做那个Asynchronous call。
是否有可能进行异步调用?
因为在我们所有的客户端代码和服务代码中来衡量每个方法的性能,我使用上面相同的三行,我通常在每个方法之前和之后放置来衡量这些方法的性能。程序完成后,我将这些地图的结果打印出来。
所以现在我正在考虑制作Asynchronous call?谁能帮我做这件事?
基本上,我正在尝试以异步方式测量特定方法的性能,以便每个线程都不会等待并被阻塞。
我想,我可以使用Futures 来做到这一点。谁能提供一个相关的例子?
感谢您的帮助。
【问题讨论】:
-
我在这里搞糊涂了,incrementAndGet 不是
ConcurrentHashMap的方法,而是AtomicLong的方法。这是你的问题吗? -
是的。我不知何故搞砸了。只需通过更改更新问题即可。
-
@TechGeeky 我对答案进行了更新,可能会提高您代码的性能。如果您愿意,请查看并使用它。干杯。
-
谢谢。您可以相应地更新答案吗?这样,我就不会错过任何关键的东西。如果我尝试这样理解,可能会错过代码中的一些重要内容。感谢您的帮助。
-
@TechGeeky 你去吧。在“完整更新的代码”下方查看。
标签: java asynchronous atomic concurrenthashmap