假设有一个多线程程序,其中15个线程写入和读取易失性SynchronousQueue。对于包含ConcurrentHashMap的易失对象,也会发生同样的情况。他们线程安全吗?
我了解使用易失性变量不能确保线程安全,因为它们缺乏同步变量的原子性,如here
所述
但是当您使用易失性同步/并发数据结构时会发生什么?
抱歉,伪代码只是一个想法。 假设有:
public class App implements Initializable {
private volatile Store store = new Store();
private volatile Producer[] producers = new Producer[15];
private volatile Consumer consumer = new Consumer();
private volatile SynchronousQueue<String[]> products;
ExecutorService(producers, consumer);
}
public class Store{
//Fully populated with 5000 > map.keyset() > 1000
private ConcurrentHashMap<Integer, String[]> map;
}
15个实例/线程:
public class Producer implements Runnable{
private static Store store;
private static SynchronousQueue>String[]> products;
public Producer(Store s, SynchronousQueue<String[]> p){
store = s;
products = p;
}
public run(){
read store.getMap();
create String[];
create id;
store.getMap().put(Integer, String[]);
products.put(String[]);
}
}
作为Singleton:
public class Consumer implements Runnable{
public Consumer(Store s, SynchronousQueue<String[]> p){
store = s;
products = p;
}
public run(){
read store.getMap();
take products
writeToFile();
}
}
“这15个生产者在商店中读取了ConcurrentHashMap,创建了一个产品,修改了ConcurrentHashMap,然后将新产品放入了SynchronousQueue。 同时,消费者不断获取SynchronousQueue的内容。”