ブログ@kaorun55

HoloLensやKinectなどのDepthセンサーを中心に書いています。

TDD BootCamp の宿題・その2 #tddbc

マルチスレッドのやつ。
C# だとダメだったので Java でやった。
TestNG の @Test アノテーション属性にスレッドテストがあったのでそれで試す。

失敗するとこんな感じ

#ぶっちゃけなんでぶつかってるのか分からない^^;


テストコード

import static org.testng.Assert.assertEquals;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;


public class LruCacheTest {
	LruCache<String, String> cache;

	@BeforeMethod
	public void setup() throws Exception {
		cache = new LruCache<String, String>();
	}

	@Test
	public void 作成時はサイズが0() throws Exception {
		assertEquals(0, cache.size());
	}

	@Test
	public void 一つ加えると一つ増える() throws Exception {
		put("a");
		assertEquals(1, cache.size());
	}

	@Test
	public void 一つ加えるとそれが取得できる() throws Exception {
		put("a");
		assertGet("a");
	}

	@Test( threadPoolSize=2, invocationCount=10)
	public void スレッドセーフ() throws Exception {
		String id = Long.toString(Thread.currentThread().getId());
		put( id );
		assertGet(id);
	}

	private void put( String key  ) {
		cache.put(key, key);
	}

	private void assertGet( String key ) {
		assertEquals(key, cache.get(key));
	}
}

プロダクトコード

import java.util.HashMap;
import java.util.Map;

import org.hamcrest.Matcher;


public class LruCache<K,V> {
	final Map<K, V> cache;

	public LruCache() {
		cache = new HashMap<K, V>(2);
	}

	public int size() {
		return cache.size();
	}

	public void put(K key, V value) {
		synchronized (cache) {
			cache.put(key, value);
		}
	}

	public V get(K key) {
		return cache.get( key );
	}
}

あと

Eclipse の自動補完ステキ
VisualStudio 2010 でもそれなりに出来るようなので、それも書く