知道为什么我从HashMap中删除密钥时没有得到java.util.ConcurrentModificationException吗?

问题描述 投票:0回答:1

我想要实现的是,如果密钥是要删除的密钥。将密钥更改为当前时间,但是其值应该相同。

我的代码段是:

public class hello
{
    private static HashMap<String,String> fileMap;
    private static final String KEY_REMOVED = "d";
    static {
        fileMap = new HashMap<String, String>();
        fileMap.put("a", "hello");
        fileMap.put(KEY_REMOVED, "bye");
        fileMap.put("c", "hi");
    }

    public static void main(String []args){
        System.out.println("Hello World");
        upload();
}

    private static void upload() throws  ConcurrentModificationException {

        for (Map.Entry<String, String> entry : fileMap.entrySet()) {
            System.out.println("Uploading key " + entry.getKey());

            String fileName = entry.getKey();

            if (fileName.equals(KEY_REMOVED)) {
                fileName = new Timestamp(System.currentTimeMillis()).getTime();
                String temp2 = fileMap.remove(VIDEO_MP4_ASSET);
                System.out.println("hashmap after removing key is " + fileMap);
                System.out.println("adding  key to hashmap " + fileName);
                fileMap.put(fileName, temp2);

            } else {

                System.out.println("continue");
            }
            System.out.println("hashmap is " + fileMap);
        }
    }

理想情况下,在删除密钥时,我们应该得到ConcurrentModificationException。我担心我现在没有得到它。但是我的代码可能稍后会中断。是吗?

java hashmap concurrentmodification
1个回答
0
投票

不需要迭代器来检测任何并发修改并引发异常。确实,要保证任何任意并发修改都存在并发修改异常是相当困难的。您永远不要依赖于抛出此异常。

在您的示例中,如果要保证不进行任何并行修改,则需要为迭代目的创建密钥集的临时副本。最好的方法是更改​​行号


0
投票
© www.soinside.com 2019 - 2024. All rights reserved.