Do we have to simply back Java that class is thread-safe, that class is not thread-safe?
What is the difference between a man and a fish? Isn't there a way to teach people to fish? Teach us directly how to determine if a class is thread-safe?
What is thread safety in Java:
Thread synchronization means that when a program accesses a thread-safe method or statement, the other can no longer manipulate it, and must wait until the end of the visit to access the thread-safe method.
What is thread safety:
If your code is in a process where multiple threads are running at the same time, these threads may run the code at the same time. If the result of each run is the same as the single-threaded run, and the value of the other variable is the same as expected, it is thread-safe.
Or, the interface provided by a class or program for a thread is an atomic operation or a switchover between multiple threads does not result in ambiguity in the execution of the interface, that is, we do not have to consider the problem of synchronization.
Thread safety issues are caused by global variables and static variables.
In general, this global variable is thread-safe if there are only read operations for global variables and static variables in each thread, and if multiple threads are concurrently performing write operations, it is generally necessary to consider thread synchronization, which may affect thread safety.
The students who have seen the source of the vector will know that many of his operations are synchronized modified, such as his added elements. (Do not know what synchronized means of self-Baidu!) )
| 123 |
publicsynchronized voidaddElement(E obj) { modCount++; ensureCapacityHelper(elementCount + 1); elementData[elementCount++] = obj;} |
And HashMap all operations are not added synchronized decoration, rather than his put source
| 12345678910111213141516171819 |
public V put(K key, V value) { if (key == null) return putForNullKey(value); int hash = hash(key.hashCode()); int i = indexFor(hash, table.length); for(Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; if (e.hash == hash &&((k = e.key) == key || key.equals(k))) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; addEntry(hash, key, value, i); return null; } |
Then look at the source code of the Add method of ArrayList
| 12345 |
publicboolean add(E e) { ensureCapacity(size + 1); // Increments modCount!! elementData[size++] = e; returntrue; } |
Look at the StringBuffer append source, he is synchronized modified
| 12345 |
publicsynchronized StringBuffer append(String str) { super.append(str); returnthis; } |
Finally, the SetProperty method of properties, he is synchronized modified
| 12345 |
publicsynchronized Object setProperty(String key, String value) { return put(key, value); } |
This makes it possible to determine who is thread-safe.
The so-called thread safety problem