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());
...
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章