简体   繁体   English

Java中的同步hashmap只读访问

[英]Synchronized hashmap read-only access in Java

In Java, there are 3 threads that want to access (read-only) an immutable hashmap to do something. 在Java中,有3个线程想要访问(只读)不可变的hashmap来执行某些操作。 Is SynchronizedMap class below the fastest solution for that purpose? SynchronizedMap类是否是为此目的最快的解决方案? If not, then what would be faster to use? 如果没有,那么什么会更快使用?

import com.carrotsearch.hppc.IntObjectMap;
import com.carrotsearch.hppc.IntObjectOpenHashMap;

public class abc {
    public static void main(String[] args) {

        final IntObjectMap<int[]> map = new IntObjectOpenHashMap<int[]>();
        for (int i = 0; i < 4; i++) {
            map.put(i, new int[] {1, 2, 3, 4, 5});
        }

        Thread[] threads = new Thread[3];

        class SynchronizedMap {

            private final Object syncObject = new Object();

            public final int[] read(int i) {

                final int[] value;

                synchronized (syncObject) {

                    // code that reads-only immutable map object
                    value = map.get(i);

                }

                return value;

            }
        }

        final SynchronizedMap syncMap = new SynchronizedMap();

        class AccessMap implements Runnable {

            private int id;
            AccessMap(int index) { id = index; }

            public void run() {

                // code that reads-only immutable map object like this:
                for (int i = 0; i < 4; i++) {

                    final int[] array = syncMap.read(i);

                    for (int j = 0; j < array.length; j++)
                        System.out.println(id + ": " + array[j] + " ");

                }

            }
        }

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(new AccessMap(i) {});
            threads[i].start();
        }

        for (int i = 0; i < threads.length; i++) {
            try {
                threads[i].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}

Is SynchronizedMap class below the fastest solution for that purpose? SynchronizedMap类是否是为此目的最快的解决方案?

No. If the HashMap is truly immutable/read-only then a volatile Map<...> is the way to go. 不。如果HashMap是真正的不可变/只读,那么可以使用volatile Map<...>

volatile IntObjectMap<int[]> readOnlyMap = new IntObjectOpenHashMap<int[]>();

If you are starting your threads after your map is built then you don't even need the volatile . 如果构建映射启动线程则甚至不需要volatile The only time you would need the volatile is if you are swapping in a new map that is being accessed by currently running threads. 只有当你正在交换当前正在运行的线程正在访问的新映射时,才需要volatile

final IntObjectMap<int[]> readOnlyMap = new IntObjectOpenHashMap<int[]>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM