java - 如何同步多线程 map 更新

标签 java multithreading

我想知道如何同步以下多线程,以便我仍然可以并行运行线程而不会导致保存多个对象。

public void setupRender() {
    ExecutorService executorService = Executors.newFixedThreadPool(10);

    final Map<Integer, String> map = Collections.synchronizedMap(new HashMap<Integer, String>());

    for (int i = 0; i < 10; i++) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                parse(map); 
            }
        });
        System.out.println("map size " + map.size() + " loop " + i);
    }
}

public void parse(Map<Integer, String> map) {
    for (int j = 0; j < 100; j++) {
        if (map.containsKey(j)) {
            System.out.println("Update");
            //session.update(map.getKey(j));
        } else {
            System.out.println("add to map " + j);
            String obj = "test";
            map.put(j, obj);
            System.out.println("save");
            //session.save(obj);
        }

        if (j % 50 == 0) {
            System.out.println("commit");
            //tx.commit();
        }
    }
}

结果,请注意相同键的多个对象如何添加到映射中,但更糟糕的是保存到数据库中,导致重复的数据库输入。

map size 0 loop 0
map size 0 loop 1
add to map 0
commit
add to map 1
add to map 0
commit
add to map 2
add to map 3
add to map 4
add to map 2
add to map 5
add to map 6
map size 1 loop 2
add to map 7
add to map 8
add to map 9
commit
map size 10 loop 3
commit
add to map 5

最佳答案

您可以使用ConcurrentHashMapputIfAbsent来保证一致性和性能。在这种情况下,您的 session 更新可以同时运行。

putIfAbsent:
    - returns the previous value associated with the specified key, 
      or null if there was no mapping for the key

public void parse(ConcurrentHashMap<Integer, String> map) {
    for (int j = 0; j < 100; j++) {    
        String obj = "test";

        Object returnedValue = map.putIfAbsent(j, obj);

        boolean wasInMap = returnedValue != null;

        if (wasInMap) {
            System.out.println("Update");
            //session.update(map.getKey(j));
        } else {
            System.out.println("add to map " + j);

            map.put(j, obj);
            System.out.println("save");
            //session.save(obj);
        }
    }
}

您还可以放置一个回调,该回调将有条件地创建一个新实例:

class Callback{
    abstract void saveOrUpdate(boolean wasInMap);    
}

public void parse(Map<Integer, String> map) {
    for (int j = 0; j < 100; j++) {    
        String obj = "test";

        Callback callback = (wasInMap) -> { //Java 8 syntax to be short
            if (wasInMap) {
                System.out.println("Update");
                //session.update(map.getKey(j));
            } else {
                System.out.println("add to map " + j);

                map.put(j, obj);
                System.out.println("save");
                //session.save(obj);
            }
        }

        Object returnedValue = map.putIfAbsent(j, callback);

        callback.saveOrUpdate(returnedValue != null);
    }
}

关于java - 如何同步多线程 map 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19642756/

相关文章:

java - 如何在 Delphi 中调试从 Java 调用的 DLL?

java - scala 覆盖引用内部类的 java 类方法

android - 在 Kotlin 中,处理程序线程会等待另一个线程完成吗?

ios - UIProgressView 不更新状态

java - 如何指定在 .jar 中使用的运行时/进程的文件路径?

java - 旋转 以度为单位的 View 变换(仅在 x 轴上)

C# 在使用循环访问内存时比 Java 慢一半?

生产者消费者上的Java多线程

c# - 在 C# 中锁定线程

c++ - 在 main 内部创建的线程和在函数内部创建的线程的行为是否应该不同?