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
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.
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!

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.

JRE is the environment in which Java applications run, and its function is to enable Java programs to run on different operating systems without recompiling. The working principle of JRE includes JVM executing bytecode, class library provides predefined classes and methods, configuration files and resource files to set up the running environment.

JVM ensures efficient Java programs run through automatic memory management and garbage collection. 1) Memory allocation: Allocate memory in the heap for new objects. 2) Reference count: Track object references and detect garbage. 3) Garbage recycling: Use the tag-clear, tag-tidy or copy algorithm to recycle objects that are no longer referenced.

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1
Easy-to-use and free code editor