Java allocation problem – is this an atom?

I have some questions about Java

>String

I have a class:

public class Test {
 private String s;

 public synchronized void setS(String str){
  s = s + " - " + str;
 }

 public String getS(){
  return s;
 }
}

I use "synchronization" in my setter and avoid it in my getter, because in my application, there are a lot of data acquisition and few settings Settings must be synchronized to avoid inconsistencies My question is: get and set variable atoms? I mean, in a multithreaded environment, thread1 will set the variable s, and thread2 will get "s" Is there any way to get something different from the old value or the new value of S (assuming we have only two threads)? In my application, getting new values is not a problem, not an old problem But can I get anything else?

>How about the acquisition and placement of HashMap?

With that in mind

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);
        }
}

Place and get atoms? How does HashMap handle putting elements into it? Does it first delete the old value and put the current one? Can I get old value or new value?

Thank you in advance!

Solution

In the first case, string is safe for unsafe publishing (in the "new" Java Memory Model (JMM)), so this is OK

Theoretically, there are some problems that are not volatile and have no latest value, but the latest meaning is not clear You can use a compare sand swap (CAS) loop to replace locks, but this may not give you more performance gain, regardless of whether locks may be contested or not

In the case of HashMap, if another thread writes, even a single writer thread, an asynchronous mapping is not safe In fact, this was found to lead to an infinite cycle of production systems running popular software The code in question actually uses two locks for the map, which is at the top (although you need to explicitly keep the same lock if you use an iterator) It is not the final decision whether to prevent the unsafe release of packaging If the map is unstable and you create a new map for each input, this can make it safe without synchronization

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>