static final ConcurrentMap<Integer, Object> allObjects = new ConcurrentHashMap<Integer, Object>();
private static Integer allocateId(Object obj) {
Integer id = Integer.valueOf(System.identityHashCode(obj));
for (;;) {
// Loop until a unique ID is acquired.
// It should be found in one loop practically.
if (allObjects.putIfAbsent(id, obj) == null) {
// Successfully acquired.
return id;
} else {
// Taken by other Thread at almost the same moment.
id = Integer.valueOf(id.intValue() + 1);
}
}
}
使用时间戳:
...
Integer id = Integer.valueOf(System.currentTimeMillis());
...