Home > Java > javaTutorial > Analysis of the basic concepts of thread safety in Java

Analysis of the basic concepts of thread safety in Java

黄舟
Release: 2017-09-18 09:36:11
Original
1343 people have browsed it

This article mainly introduces the analysis of the basic concepts of Java thread safety. I hope it can give you a reference and friends who need it can learn more.

Initial understanding of Java thread safety. Generally speaking, JAVA thread safety refers to a characteristic of Java objects in a multi-threaded running environment, which means that each call can get the correct logical result under normal (different from special call situations). In essence, synchronization control logic is added to the method behavior of the object, and the caller can use the object safely and securely without any additional synchronization control.

1. Definition of thread safety

When multiple threads access an object, if these threads do not need to be considered Scheduling and alternate execution in the runtime environment do not require additional synchronization or any other coordination operations on the caller. The behavior of calling this object can obtain the correct result, then this object is thread-safe. This definition is very strict. It requires that all thread-safe codes have one characteristic: the code itself encapsulates all necessary correctness guarantee means, so that the caller does not need to care about multi-threading issues, and there is no need to implement Rehe measures to ensure multi-threading. correct call.

2. Thread safety in Java language

In order to have a deeper understanding of thread safety, follow the thread safety "Security strength" is sorted from strong to weak: immutable, absolutely thread-safe, relatively thread-safe, thread-compatible and thread-antagonistic.

2.1 Immutability

After jDK1.5, immutable objects must be thread-safe, regardless of whether Neither the method implementation of the object nor the caller of the method need to implement any thread safety measures. For properties, objects or methods modified by the final keyword, their external visible state will never change. If the shared data is a basic data type, then it can be guaranteed to be immutable by using the final keyword when defining it. For example, the String class object is a typical immutable object. When we call substring(), replace(), and concat(), these methods will not affect its original value and will only return a newly constructed string object.

2.2 Relative thread safety

Relative thread safety is what we usually call thread safety, it requires Ensure that individual operations on this object are thread-safe. Most thread-safe classes in Java belong to this type, such as Vector, HashTable, etc.

2.3 Thread compatibility

#Thread compatibility means that the object itself is not thread-safe, but it can be passed through the call The client correctly uses synchronization methods to ensure that objects can be used safely in concurrent environments.

2.3 Thread conflict

Thread conflict means that no matter whether the calling end adopts synchronization measures, it cannot Code used concurrently in a threaded environment. Since the Java language is inherently multi-threaded, code that excludes multi-threading such as thread opposition rarely appears. Common thread opposition operations include the suspend() and resume() methods of the Thread class, System.setIn(), etc.

3. Thread safety implementation method

##3.1 Mutually exclusive synchronization

Mutual exclusion synchronization is the most common means of ensuring concurrency correctness. Synchronization refers to ensuring that when multiple threads concurrently access shared data, the shared data is guaranteed to be accessed by only one thread at the same time. Thread usage. Mutex is a means to achieve synchronization. Critical sections, mutexes and semaphores are the main ways to implement mutual exclusion. Mutual exclusion is the cause, synchronization is the effect, mutual exclusion is the method, and synchronization is the purpose.


In Java, the most basic mutually exclusive synchronization method is the synchronized keyword. In addition, you can also use the reentrant lock (ReentrantLock) in the java.util.concurrent package to achieve synchronization. They are very similar in usage, but there are some differences in code writing. One is a mutual exclusion lock at the API level (the lock() and unlock() methods are completed with try/finally statement blocks), and the other is a mutual exclusion lock at the native syntax level. Repulse lock. However, reentrant locks have the following three items more than synchronized:

Waiting can be interrupted: It means that when the thread holding the lock does not release the lock for a long time, the waiting thread can choose to give up waiting and deal with other things instead. The interrupt feature is helpful in handling synchronized blocks that take very long execution times.

Fair lock can be achieved: Fair lock means that when multiple threads are waiting for the same lock, they must obtain the lock in sequence according to the time order of applying for the lock; unfair lock does not guarantee this. The lock in synchronized is unfair, and the reentrant lock is also unfair by default, but you can require the use of fair lock through the constructor with a Boolean value.


The lock can be bound to multiple conditions: it means that a reentrant lock object can be bound to multiple Condition objects at the same time. In synchronized, the wait() and notify() or notifyAll() methods of the lock object can implement a If you want to associate an implicit condition with more than one condition, you have to add an additional lock. However, you don't need to do this for reentrant locks. You only need to call the newCondition() method multiple times.

3.2 Non-blocking synchronization

The most important problem of mutually exclusive synchronization is caused by thread blocking and waking up Performance issues, it is a pessimistic concurrency strategy, always thinking that as long as correct synchronization measures are not taken, problems will occur. But we have another option: an optimistic concurrency strategy based on conflict detection. In layman's terms, the operation is performed first. If no other threads compete for the shared data, the operation is successful; if there is contention for the shared data, a conflict occurs. , then take other compensation measures. Many implementations of this optimistic concurrency strategy do not need to suspend the thread, so it is called non-blocking synchronization.

Summarize

The above is the detailed content of Analysis of the basic concepts of thread safety in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template