ConcurrentHashMap同時性テスト

3135 ワード

package concurrentMap;

import java.util.concurrent.ConcurrentHashMap;

import org.apache.hadoop.io.IntWritable;

/**
 * 
 * @author Administrator
 * 
 */
public class ConcurrencyHashMapTest9 {

	public ConcurrencyHashMapTest9() {
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			int thread_Num = 10;

			// case 1
			ConcurrentHashMap pMsgs = new ConcurrentHashMap();
			for (int i = 0; i < 10000; i++)
				pMsgs.put(i, i);

			Thread[] tGroup = new Thread[thread_Num];
			for (int i = 0; i < thread_Num; i++) {
				tGroup[i] = new Thread(new Worker(pMsgs));
				tGroup[i].start();
			}
			for (int i = 0; i < thread_Num; i++) {
				tGroup[i].join();
			}

			System.out.println(pMsgs.get(5));

			// case 2
			ConcurrentHashMap pMsgs1 = new ConcurrentHashMap();
			for (int i = 0; i < 10000; i++)
				pMsgs1.put(i, new IntWritable(i));

			Thread[] tGroup1 = new Thread[thread_Num];
			for (int i = 0; i < thread_Num; i++) {
				tGroup1[i] = new Thread(new Worker1(pMsgs1));
				tGroup1[i].start();
			}

			for (int i = 0; i < thread_Num; i++) {
				tGroup1[i].join();
			}

			System.out.println(pMsgs1.get(5));

			// case 3
			ConcurrentHashMap pMsgs2 = new ConcurrentHashMap();
			for (int i = 0; i < 10000; i++)
				pMsgs2.put(i, new IntWritable(i));
			Thread[] tGroup2 = new Thread[thread_Num];
			for (int i = 0; i < thread_Num; i++) {
				tGroup2[i] = new Thread(new Worker2(pMsgs2));
				tGroup2[i].start();
			}

			for (int i = 0; i < thread_Num; i++) {
				tGroup2[i].join();
			}
			System.out.println(pMsgs2.get(5));
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class Worker implements Runnable {
	ConcurrentHashMap pMsgs;

	public Worker(ConcurrentHashMap pMsgs) {
		this.pMsgs = pMsgs;
	}

	@Override
	public void run() {
		Integer value = pMsgs.get(5);   // value Integer, , , C , 
		synchronized (value) {
			value = value + 1;
		}
	}
}

class Worker1 implements Runnable {
	ConcurrentHashMap pMsgs;

	public Worker1(ConcurrentHashMap pMsgs) {
		this.pMsgs = pMsgs;
	}

	@Override
	public void run() {
		IntWritable value = pMsgs.get(5);  // , value , Worker2 
		synchronized (value) {
			value.set(value.get() + 1);
		}
	}
}

class Worker2 implements Runnable {
	public static Object mutex = new Object();
	ConcurrentHashMap pMsgs;

	public Worker2(ConcurrentHashMap pMsgs) {
		this.pMsgs = pMsgs;
	}

	@Override
	public void run() {
		synchronized (mutex) {        
			IntWritable value = pMsgs.get(5);  // Worker1 , !
			// System.out.println(Thread.currentThread().getName() + " value:"+ value);
			value.set(value.get() + 1);
		}
	}
}