由于并发访问,TreeMap中是否存在此空指针异常?

Raj*_*hna 2 java nullpointerexception treemap non-thread-safe

我知道TreeMap不是线程安全的.我正在尝试将TreeMap与ConcurrentSkipListMap进行比较.我使用的代码如下所示,我想确定我得到的错误是由于TreeMap不是线程安全而不是因为其他一些.

java中java.util.TreeMap.fixAfterInsertion(TreeMap.java:2127)的java.util.TreeMap.rotateLeft(TreeMap.java:2060)中的线程"pool-1-thread-52"java.lang.NullPointerException中的异常. util.TreeMap.put(TreeMap.java:574)位于java.util.concurrent.ThreadPoolExecutor $的java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)的ThreadTestTreeMap $ 1.run(ThreadTestTreeMap.java:39) java.lang.Thread.run上的Worker.run(ThreadPoolExecutor.java:615)(Thread.java:745)

import com.google.common.collect.Ordering;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ThreadTestTreeMap {
    public static Map<String, Object> map;
    public static int THREADS =  100;
    public static long averageTime = 0;

public static void main(String args[]) throws InterruptedException {
    for (int i = 0; i < 1; i++) {
        map = new TreeMap<>(Ordering.natural());
//            map = new ConcurrentSkipListMap<>(Ordering.natural());

        long time = System.nanoTime();
        ExecutorService service = Executors.newFixedThreadPool(THREADS);

        for (int j = 0; j < THREADS; j++) {
            final int finalJ = j;
            service.execute(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep(THREADS - finalJ);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    long threadId = Thread.currentThread().getId();
                    map.put("tag"+threadId, "hello");
            }});
        }
        service.shutdown();
        service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
        long timeUsed = (System.nanoTime() - time) / 1000000L;
        averageTime += timeUsed;
        System.out.println("All threads are completed in "
                + timeUsed + " ms");
    }
    System.out.println("The average time is " + averageTime / 10 + " ms");
}
}
Run Code Online (Sandbox Code Playgroud)

And*_*ner 5

无论是否NullPointerException是并发修改的直接结果,它在Javadoc中声明TreeMap:

请注意,此实现不同步.如果多个线程同时访问映射,并且至少有一个线程在结构上修改了映射,则必须在外部进行同步.

当您在没有同步的情况下在多个线程中修改映射时,您不会使用该类,因为它是要使用的.

添加外部同步:)