This is not thread safe. If two threads call addValue
at the same time it is very likely that your HasMap
will become corrupt.
You could fix it by using a ConcurrentHasMap.
See:
Hashmap concurrency issue
and especially
A Beautiful Race Condition
Here's a demonstration of using your Load
class that would probably crash horribly.
public class Load {
private final Map<String, String> confs = new HashMap<String, String>();
public void addValue(String key, String value) {
confs.put(key, value);
}
public String getValue(String key) {
//synchronized (lock)
return confs.get(key);
}
}
public class Loader implements Runnable {
private final Load load;
public Loader (Load load) {
this.load = load;
}
@Override
public void run() {
for (int i = 0; i < 100000; i++) {
load.addValue("" + i, "Value:" + i);
}
}
}
public void test() throws InterruptedException {
System.out.println("Hello");
Load load = new Load();
Loader l1 = new Loader(load);
Loader l2 = new Loader(load);
Thread t1 = new Thread(l1);
Thread t2 = new Thread(l2);
t1.start();
t2.start();
t1.join();
t2.join();
}