ITeye博客

ReentrantLock VS Synchronized

willpower · 2008-10-20 17:57 · Performance Test/Analysis/Tuning 性能分析优化 · Markdown

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)

暂无评论。

评论功能维护中,当前仅展示历史评论。