我知道TreeMap https://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html不是线程安全的。我正在尝试将 TreeMap 与并发跳表映射 https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentSkipListMap.html。我使用的代码如下所示,我想确定我收到的错误是否是由于 TreeMap 不是线程安全的,而不是因为其他原因。
线程“pool-1-thread-52”中的异常 java.lang.NullPointerException
在 java.util.TreeMap.rotateLeft(TreeMap.java:2060)
在 java.util.TreeMap.fixAfterInsertion(TreeMap.java:2127)
在 java.util.TreeMap.put(TreeMap.java:574)
在 ThreadTestTreeMap$1.run(ThreadTestTreeMap.java:39)
在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
在 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
在 java.lang.Thread.run(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");
}
}
无论是否NullPointerException
是并发修改的直接结果,它指出在 Javadoc 中TreeMap https://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html:
请注意,此实现不是同步的。如果多个线程同时访问一个映射,并且至少有一个线程在结构上修改了该映射,则must与外部同步。
当您在多个线程中修改映射而不进行同步时,您没有按照预期使用该类。
添加外部同步:)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)