Hi,
I've got some questions about Java's assigment.
Strings
I've got a class:
public class Test {
private String s;
public synchronized void setS(String str){
s = s + " - " + str;
}
public String getS(){
return s;
}
}
I'm using "synchronized" in my setter, and avoiding it in my getter, because in my app, there are a tons of data gettings, and very few settings. Settings must be synchronized to avoid inconsistency. My question is: is getting and setting a variable atomic? I mean, in a multithreaded environment, Thread1 is about to set variable s, while Thread2 is about to get "s". Is there any way the getter method could get something different than the s's old value or the s's new value (suppose we've got only two threads)?
In my app it is not a problem to get the new value, and it is not a problem to get the old one. But could I get something else?
What about HashMap's getting and putting?
considering this:
public class Test {
private Map<Integer, String> map = Collections.synchronizedMap(new HashMap<Integer, String>());
public synchronized void setMapElement(Integer key, String value){
map.put(key, value);
}
public String getValue(Integer key){
return map.get(key);
}
}
Is putting and getting atomic? How does HashMap handle putting an element into it? Does it first remove the old value and put the now one? Could I get other than the old value or the new value?
Thanks in advance!