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

来源:互联网 发布:mac os系统如果支持win 编辑:程序博客网 时间:2024/05/14 09:36
使用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());...
原创粉丝点击