ReentrantLock VS Synchronized

Here is a simple benchmark case for testing the performance between ReentrantLock and Synchronized.


Machine: 2 phycial processors with hyperthreading enabled (4 logical processors)

OS: windows server 2003

JVM version: 1.6

Threads Number: 4

Benchmark result:
Synchronized - 25786ms
ReentrantLock - 10656ms

This shows ReentrantLock has much better performance than synchronized keyword. However, some people said there should be no different between ReentrantLock and Synchronized keyword in 1.6. Any wrong?


Test Case(note: you can also use of semaphore to setup barrier for all threads):
import java.util.HashMap;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Lock;

public class HighContentionSimulator implements Runnable {

private static HashMap map = new HashMap();

public static int LOCK = 0;
public static int SYNC = 1;

private Lock lock = new ReentrantLock();

private int mode = 0;

private int count = 100;

private char[] charTable = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'};

public HighContentionSimulator()
{

}

public HighContentionSimulator(int mode, int count)
{
this.mode = mode;
this.count = count;
}


public void run()
{
try
{
while (count > 0)
{
if (mode == LOCK)
{
runLock();
}
else if (mode == SYNC)
{
runSync();
}
else
{
throw new Exception("invalid mode!");
}
count--;
}

}
catch(Exception e)
{
e.printStackTrace();
}


}

public synchronized void runSync()
{
System.out.print("synchronized mode");
operation();
}

public void runLock()
{
System.out.print("lock mode");
lock.lock();
try
{
operation();
}
finally
{
lock.unlock();
}
}

public void operation()
{
int seed = 10000;
int key = (int)Math.random()* seed;
int countValue = (int)Math.random() * charTable.length;
StringBuffer sb = new StringBuffer();
for (int i=0; i<countValue; i++)
{
sb.append(charTable[(int)Math.random() * charTable.length]);
}
Object o = map.get(key);
String value = sb.toString();
if (o != null)
{
if (value.equalsIgnoreCase((String)o))
{
return;
}
}
map.put(key, value);
}

public static void main(String[] args)
{
int threadNumber = 4;
int count = 99999;
long start = System.currentTimeMillis();
Thread[] threads = new Thread[4];
for (int i=0; i<threadNumber; i++)
{
threads[i] = new Thread(new HighContentionSimulator(HighContentionSimulator.LOCK, count));
threads[i].start();
}

for (int i=0; i<threadNumber; i++)
{
try
{
threads[i].join();
}
catch(Exception e)
{
e.printStackTrace();
}
}
System.out.println("time cost: " + (System.currentTimeMillis() - start));

}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值