I have a map defined
private static HashMap<Object, Object> myMap;
It is populated in a single thread and then that single thread spawns more threads that alter the data inside the map elements, but do not alter the map structure (no removes/puts/etc). Also, each thread alters one and only one unique member of the map (no two threads alter the same member).
My question is: will the main thread see the changes to the hashmap members, once all changes are complete? If not, would adding volatile to the declaration work, or would it only guarantee other threads see changes to the structure? Thanks
EDIT: Code that hopefully highlights what I'm doing in a more clear way
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class TestingRandomStuff {
public static void main(String[] args) throws Exception {
HashMap<Object, Object> myMap = new HashMap();
ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
//myMap is populated by this thread, and the objects inside are initialized, but are left largely empty
populate();
for (Object o : myMap.values()) {
Runnable r = new Task(o);
pool.execute(r);
}
pool.shutdown();
try {
pool.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
} catch (InterruptedException e) {;}
//How do I gurantee that the objects inside myMap are displayed correctly with all the data that was just loaded by seperate threads,
//or is it already guranteed?
displayObjectData();
}
public static class Task implements Runnable {
private Object o;
public Task(Object o) {this.o = o;}
public void run() {
try {
o.load(); //o contains many complicated instance variables that will be created and written to
} catch (Exception e) {;}
}
}
}
String
is immutable. Can you give a more realistic example?String
s are immutable, but you aren't removing/putting?volatile
won't help as @shmosel points out. Adding asynchronized
block would be the simplet way to make this work - other solutions require a much deeper understanding of the structure of what you are changing and how you are changing it.