本人最近写了一段代码,用到了AtomicInteger对这个变量,但是期待的结果与代码的实际运行
结果相差好大,现将代码奉上,求各位大牛给下解决方案。
class IDGeneration {
private final static ConcurrentHashMap idMap = new ConcurrentHashMap();
private static final long baseTime = 1462377600000L;
private Lock lock;
IDGeneration() {
lock = new ReentrantLock();
}
@SuppressWarnings("unused")
public Long generateRelativeIncrementUniqueId(String flag) {
String dateString = GengratedUnqueId.formatDate(new Date(),
GengratedUnqueId.PATTERN);
Long currentTime = (System.currentTimeMillis() - baseTime);
AtomicInteger queueId = new AtomicInteger(0);
int i = 0;
Long tempValue = null;
lock.lock();
try {
queueId = idMap.get(currentTime);
if (queueId == null) {
queueId = new AtomicInteger(0);
idMap.clear();
idMap.put(currentTime, queueId);
tempValue = (currentTime << 5 | queueId.get());
} else {
queueId.getAndIncrement();
idMap.put(currentTime, queueId);
tempValue = (currentTime << 5 | queueId.get());
}
} finally {
lock.unlock();
}
return tempValue;
return null;
}
}
这是测试代码:
public static void main(String[] args) throws Exception {
static ConcurrentHashMap<Long, String> map = new ConcurrentHashMap<Long, String>();
final IDGeneration idGeneration = new IDGeneration();
for (int i = 0; i < 100; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
long value = idGeneration
.generateRelativeIncrementUniqueId();
map.put(value, "");
}
});
thread.start();
}
TimeUnit.SECONDS.sleep(5);
System.out.println("map.size===" + map.size());
}