Home > Java > javaTutorial > body text

What are the ways to implement thread safety in java

王林
Release: 2019-11-27 14:55:05
forward
5485 people have browsed it

What are the ways to implement thread safety in java

To achieve thread safety generally requires at least two features: Atomicity and Visibility.

Implementation method:

1) Use synchronize: It is atomic and visible, so if the synchronize modified operation is used, then It comes with visibility, synchronized uses pessimistic locking to achieve thread safety;

2) Use atomic classes instead of basic data types. Atomic classes use optimistic locks to achieve thread safety and multi-threading. To execute a in the environment, you can use the AtomicInteger classincrementAndGet() method to implement it. Volatile is also used to ensure visibility; use Unsafe to call the native local methodCAS, CAS uses bus locking or cache locking to ensure atomicity;

Recommended online video tutorial: java video tutorial

3) Using the volatile keyword, volatile does not necessarily have atomicity. For example, using volatile-modified variables or -- operations (num), we need to make volatile-modified variables need to be atomic, then we can generally Set on the boolean type variable, as follows:

volatile boolean tag = true;
线程1 while(tag){};
线程2 while(tag){};
Copy after login

If there is a variable that increases or decreases, we can use the atomic class (AtomicInteger).

4) Use ThreadLocal to isolate each thread;

5) We can also use other locks, such as reentrant locks (ReentrantLock ) Ensure thread safety;

6) We can also use critical sections, mutexes, and semaphores to ensure thread safety.

This article is recommended by the java introductory learning column. Everyone is welcome to learn and communicate together.

The above is the detailed content of What are the ways to implement thread safety in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
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