同步代码比未同步的代码执行得更快 [英] Synchronized code performs faster than unsynchronized one

查看:129
本文介绍了同步代码比未同步的代码执行得更快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得出了这个惊人的结果,我绝对不知道其原因: 我有两种方法简化为:

I came out with this stunning result which i absolutely do not know the reason for: I have two methods which are shortened to:

private static final ConcurrentHashMap<Double,Boolean> mapBoolean = 
        new ConcurrentHashMap<Double, Boolean>();
private static final ConcurrentHashMap<Double,LinkedBlockingQueue<Runnable>> map
        = new ConcurrentHashMap<Double, LinkedBlockingQueue<Runnable>>();


protected static <T> Future<T> execute(final Double id, Callable<T> call){
// where id is the ID number of each thread
synchronized(id)
{
   mapBoolean.get();// then do something with the result
   map.get();//the do somethign with the result
}
}

protected static <T> Future<T> executeLoosely(final Double id, Callable<T> call){

 mapBoolean.get();// then do something with the result
 map.get();//the do somethign with the result

 }

}

在分析超过500个线程时,每个线程分别调用上述方法400次,我发现execute(..)的性能比executeLoosely(..)至少好500倍,这很奇怪,因为executeLoosely不是同步,因此更多线程可以同时处理代码.

On profiling with over 500 threads, and each thread calling each of the above methods 400 times each, I found out that execute(..) performs atleast 500 times better than executeLoosely(..) which is weird because executeLoosely is not synchronized and hence more threads can process the code simultaneously.

任何原因?

推荐答案

在我假设没有500核的机器上使用500个线程的开销,使用任务的时间大约是100-1000x执行JVM可以检测到的代码的Map不会执行任何操作,可能会产生随机结果. ;)

The overhead of using 500 threads on a machine which I assume doesn't have 500 cores, using tasks which takes about 100-1000x as long as a lookup on a Map to execute code which the JVM could detect doesn't do anything, is likely to produce a random outcome. ;)

您可能会遇到的另一个问题是,使用一个线程可以更快地执行测试,因为它偏向了对一个线程的访问,因此可以受益于使用同步.也就是说,它将您的多线程测试重新转换为单线程测试,这在第一时间是最快的.

Another problem you could have is that a test which faster being performed with one thread can benefit from using synchronized because it biases access to one thread. i.e. it turns your multi-threaded test back into a single threaded one which is the fastest in the first place.

您应该比较使用单个线程进行循环得到的时间.如果这样更快(我相信会更快),那么它就不是一个有用的多线程测试.

You should compare the timings you get with a single thread doing a loop. If this is faster (which I believe it would be) then its not a useful multi-threaded test.

我的猜测是,您要在未同步的代码之后运行同步的代码.即在JVM预热了一点之后.交换执行这些测试的顺序并多次运行,您将获得不同的结果.

My guess is that you are running the synchronized code after the unsynchronised code. i.e. after the JVM has warmed up a little. Swap the order you perform these tests and run them many times and you will get different results.

这篇关于同步代码比未同步的代码执行得更快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆