【问题标题】:Mulitple threads are trying to write with milliseconds as key, but instead of one key many keys are created in ConcurrentHashMap多个线程尝试以毫秒为键写入,但在 ConcurrentHashMap 中创建了多个键而不是一个键
【发布时间】:2017-08-03 16:35:43
【问题描述】:
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
}

单独的线程,通过删除超过 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();
}

【问题讨论】:

  • 您可以使用the diamond operator 显着缩短该声明,就像使用initializingObservation 一样。
  • 你能提供一个minimal reproducible example吗?您只展示了将(假设)每 10 秒添加一个新条目的代码部分 - 基于该代码,只有一个人希望在您的地图中看到多个键...
  • @assylias 我希望你能理解这个解释。问题是在删除超过 10 秒的密钥时,其他线程来检查并认为没有条目并尝试同时创建新条目。所以最后,我有多个键,并且值由不必要的多个键而不是一个键分隔。我的目标是每 10 秒通过比较它们的时间值来捕获一些观察结果。
  • @assylias 但是,当我从中读取然后通过 remove() 方法删除所有条目时,我希望在读取映射内容的过程中没有其他线程写入映射,然后删除它们。
  • @biziclop 我在最后添加了代码进行测试。我总是得到多个键。我希望你明白我的目标。我的目标是使用数据包到达时间创建 10 秒的存储桶。安全地写入、读取和删除线程。

标签: java concurrency concurrenthashmap


【解决方案1】:

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

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

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

使用此代码 -

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

更改后,代码可以正常工作
请注意,尽管代码确实仍有改进/重构的空间

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    • 2015-12-21
    相关资源
    最近更新 更多