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

posted on 2012-02-07 11:02  子非鱼焉  阅读(187)  评论(0编辑  收藏  举报

导航