Java在并发环境下设置唯一标识

使用hashcode
 
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());
...

你可能感兴趣的:(java)