Java练习题

1.实现一个类似于ConcurrentHashMap的分段加锁

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SegmentLock {
	private static final int DEFAULT_INITIAL_CAPACITY = 16;

	private static final int MAXIMUM_CAPACITY = 1 << 30;

	private static final int MAX_SEGMENTS = 1 << 16; // slightly conservative

	final int segmentMask;

	final int segmentShift;

	private Pair<Lock, Map<String, Counter>>[] segmentLocks;

	public SegmentLock(final int concurrentLevel) {
		int size = 1;
		int shift = 0;
		while (size < concurrentLevel) {
			size <<= 1;
			shift += 1;
		}

		segmentMask = size;
		segmentShift = 32 - shift;

		for (int i = 0; i < size; i++) {
			segmentLocks[i] = new Pair(new ReentrantLock(), new HashMap<String, Counter>());
		}
	}

	public Pair<Lock, Map<String, Counter>> get(final String key) {
		return segmentLocks[(hash(key.hashCode()) >> segmentShift) & segmentMask];
	}

	private static int hash(int h) {
		h += (h << 15) ^ 0xffffcd7d;
		h ^= (h >>> 10);
		h += (h << 3);
		h ^= (h >>> 6);
		h += (h << 2) + (h << 14);
		return h ^ (h >>> 16);
	}

	static class Pair<Left, Right> {
		private final Left left;
		private final Right right;

		public Pair(final Left left, final Right right) {
			this.left = left;
			this.right = right;
		}
	}

	static class Counter {
		private int count;

		public int increaseAndGet() {
			return ++count;
		}

		public int decreaseAndGet() {
			return --count;
		}

		public int get() {
			return count;
		}
	}
}

  

2.怎样初始化一个泛型数组?

   new ArrayList<String>[]();

 

posted @ 2016-05-06 10:36  无心流泪  阅读(315)  评论(0编辑  收藏  举报