同步与重入锁定性能
在多线程系统的队列实现方面,我遇到了一些惊喜。这里是:-
场景:- 1 个生产者,1 个消费者:- 生产者将一个整数放入队列中。使用者只需将其从队列中删除即可。
队列的底层数据结构:- TreeSet(我从未想过我会使用),LinkedList,LinkedBlockingQueue(大小不确定)
代码:- 的树集作为队列:-
while (i < 2000000) {
synchronized (objQueue) {
if (!(objQueue.size() > 0)) {
try {
objQueue.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Integer x = objQueue.first();
if (x != null) {
objQueue.remove(x);
++i;
}
}
}
编辑:-
while (i < 2000000) {
synchronized (objQueue) {
objQueue.add(i);
++i;
objQueue.notify();
}
}
对于链接阻止队列:-
while (i < 2000000){
try {
objQueue.put(i);
++i;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Thread.currentThread().interrupt();
}
}
while (i < 2000000) {
try {
objQueue.take();
++i;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Thread.currentThread().interrupt();
}
}
对于 LinkedList :- 具有同步的类似代码。
问题:-
1)当我通过Visual VM测量性能时,我观察到对于生产者代码,TreeSet的性能优于LinkedBlockingQueue和LinkedList,即使它需要O(log n)时间,在Linked结构中创建对象是一个很大的开销。为什么理论与实践完全不同?为什么在队列实现中,我们更喜欢链接的数组结构而不是树结构?
2)与ReeentrantLock相比,同步显然是赢家,因为TreeSet的表现优于LinkedList,后者的表现优于LinkedBlockingQueue。我希望我可以附加可视 VM 结果。它不是在投票与文章,http://www.ibm.com/developerworks/java/library/j-jtp10264/index.html
操作在
戴尔Vostro 1015,酷睿2双核2.10,2GB内存,带32位操作系统,带
JVM: Java HotSpot(TM) Client VM (20.1-b02, mixed mode) Java: version 1.6.0_26, vendor Sun Microsystems Inc.