多线程尝试以毫秒为单位写入密钥,但是在ConcurrentHashMap中创建了许多密钥而不是一个密钥

时间:2017-08-03 16:35:43

标签: java concurrency concurrenthashmap

ConcurrentHashMap<Long, CopyOnWriteArrayList<Observation>
mostRecentObservationDB = new ConcurrentHashMap<Long,
    CopyOnWriteArrayList<Observation>(524288, 0.75f, 32);

这是我的地图。我试图同时读取和写入多个线程,但不知何故它总是创建多个键。

long timeInMilliseconds = System.currentTimeMillis();

if (/* the last key older than 10 seconds comparing to the new key*/) {
    CopyOnWriteArrayList<Observation> initializingObservation = new CopyOnWriteArrayList<>();
    initializingObservation.add(obs);

    mostRecentObservationDB.putIfAbsent(timeInMilliseconds, initializingObservation);
} else {
  // Update
}

Seperate Thread,它通过删除超过10秒的键来过滤此哈希映射。

while (true) {
    try {
        Thread.sleep(4000);
        if(/*Time (key) older than 10 seconds*/) {
            mostRecentObservationDB.remove(key);
        }

    } catch (Exception e) {

    }
}

问题是在删除密钥后,它会在初始化时创建多个密钥。这是我的日志。

key -> 1501779153776, value
key -> 1501779153826, value
key -> 1501779153876, value
key -> 1501779153896, value

我希望在删除操作时将它们存储为一个键。这就是它应该存储的方式。

key -> 1501779153776, value

然而,当我从中读取然后通过remove()方法删除所有条目时,我希望在我正在读取地图内容然后删除它们时没有其他线程写入地图。

这是表现奇怪的代码:

public static void main(String[] args) {
    ConcurrentHashMap<Long, String> tenSecondBucket =
        new ConcurrentHashMap<Long, String>();

    Thread writingThread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1);

                    if(tenSecondBucket.size() > 0) {
                        // getting last key
                        long lastKey = 0;
                        for (long keyValue : tenSecondBucket.keySet()) {
                            lastKey = keyValue;
                        }

                        if(System.currentTimeMillis() - lastKey > 10000) {
                            tenSecondBucket.put(System.currentTimeMillis(), "secondEntry");
                        } else {
                            tenSecondBucket.put(lastKey, "updatedEntry");
                        }
                    } else {
                        tenSecondBucket.put(System.currentTimeMillis(), "newEntry");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });

    writingThread.start();

    Thread removingThread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(4000);

                    if(tenSecondBucket.size() > 0) {
                        tenSecondBucket.keySet().stream().forEach(key -> {
                            if(System.currentTimeMillis() - key > 10000) {
                                tenSecondBucket.remove(key);
                            }
                        });
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });

    removingThread.start();

    Thread readingThread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(4000);

                    if(tenSecondBucket.size() > 0) {
                        tenSecondBucket.keySet().stream().forEach(key -> {
                            System.out.println("testing key which is timestamp " + key);
                        });
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });

    readingThread.start();
}

1 个答案:

答案 0 :(得分:1)

问题在于你导出“lastKey”的方式。您似乎需要地图中存在的最高时间值,并且您假设它将是tenSecondBucket.keySet()的最后一个条目。但是,keySet()方法返回一个Set,它本质上不是有序的(在任何情况下,映射都不维护有序的键列表)

所以你需要替换这段代码 -

long lastKey = 0;
for (long keyValue : tenSecondBucket.keySet()) {
     lastKey = keyValue;
}

使用此代码 -

long lastKey = 0;
for (long keyValue : tenSecondBucket.keySet()) {
    lastKey = keyValue > lastKey? keyValue : lastKey;
}

更改后,代码正常工作 请注意,代码仍然有改进/重构的空间