首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

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

2012-08-27 
Java在并发环境下设置唯一标识使用hashcode static final ConcurrentMapInteger, Object allObjects n

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

热点排行