Home Java javaTutorial A brief introduction to the Java multi-threading keywords volatile, lock and synchronized

A brief introduction to the Java multi-threading keywords volatile, lock and synchronized

Sep 25, 2018 pm 03:36 PM
java multithreading

This article brings you a brief introduction to the Java multi-threading keywords volatile, lock and synchronized. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. help.

1. Volatile

The memory semantics of volatile writing and volatile reading:

Thread A writes a volatile variable, which is essentially thread A writing to the memory that will be read next. A thread of this volatile variable issued a message (which modified the shared variable). When thread B reads a volatile variable, in essence, thread B receives the message sent by a previous thread (the modification of the shared variable before writing the volatile variable). Thread A writes a volatile variable, and then thread B reads the volatile variable. This process is essentially thread A sending a message to thread B through main memory.

Memory semantics of lock release and lock acquisition:

Thread A releases a lock. In essence, thread A sends a message to a thread that will next acquire the lock (thread A shares a Variable modification) message. Thread B acquires a lock. In essence, thread B receives a message sent by a previous thread (which modified the shared variable before releasing the lock). Thread A releases the lock, and then thread B acquires the lock. This process is essentially thread A sending a message to thread B through main memory.

Summary: The role of the volatile keyword is to make variables visible (visible) across multiple threads, but volatile alone cannot guarantee thread safety. The volatile keyword does not have the synchronized keyword. Atomic.

2. lock

Lock is an interface:

public interface Lock {  
   void lock();     
   void lockInterruptibly() throws InterruptedException;
    boolean tryLock();
    boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
    void unlock();
    Condition newCondition();
}
Copy after login

lock(), tryLock(), tryLock(long time, TimeUnit unit) and lockInterruptibly() are used to Get the lock.

The unLock() method is used to release the lock. The tryLock() method has a return value, which means it is used to try to acquire the lock. If the acquisition is successful, it returns true. If the acquisition fails (that is, the lock has been acquired by another thread), it returns false, which means that this method is no matter what. will return immediately. You won't be waiting there when you can't get the lock. The tryLock(long time, TimeUnit unit) method is similar to the tryLock() method, but the difference is that this method will wait for a certain period of time when it cannot get the lock. If it cannot get the lock within the time limit, it will return false. Returns true if the lock was obtained initially or during the waiting period. The lockInterruptibly() method is special. When acquiring a lock through this method, if the thread is waiting to acquire the lock, the thread can respond to the interrupt, that is, interrupt the waiting state of the thread. That is to say, when two threads want to acquire a lock through lock.lockInterruptibly() at the same time, if thread A acquires the lock at this time, and thread B is only waiting, then the threadB.interrupt() method is called on thread B. Can interrupt the waiting process of thread B.

lock can be interrupted during the process of acquiring the lock. lock can try to acquire the lock. If the lock is held by another thread, it will return false and will not cause the current thread to sleep. When lock tries to acquire the lock, it passes in a time parameter. If the lock is not acquired within this time range, the request is terminated. synchronized will automatically release the lock, but lock will not automatically release the lock. Note: lock() can be used to lock a piece of code, so that other code needs to wait before the lock is released. It should be noted that lock will not automatically release the lock like synchronized, so it must be placed in a try-finally block. , ensuring the lock is released.

Lock and synchronized have the following differences:

1) Lock is an interface, while synchronized is a keyword in Java, and synchronized is a built-in language implementation;

2) When an exception occurs, synchronized will automatically release the lock occupied by the thread, so it will not cause a deadlock; while when an exception occurs, if Lock does not actively release the lock through unLock(), it is likely to cause a deadlock. , so when using Lock, you need to release the lock in the finally block;

3) Lock can allow the thread waiting for the lock to respond to the interrupt, but synchronized cannot. When using synchronized, the waiting thread will wait forever and cannot Respond to interruption;

 4) Through Lock, you can know whether the lock has been successfully acquired, but synchronized cannot do this.

 5) Lock can improve the efficiency of multiple threads reading operations. In terms of performance, if the competition for resources is not fierce, the performance of the two is almost the same. When the competition for resources is very fierce (that is, there are a large number of threads competing at the same time), the performance of Lock is far better than that of synchronized. Therefore, it should be selected according to the appropriate situation when using it. ReentrantLock means "reentrant lock". The concept of reentrant lock is described in the next section. ReentrantLock is the only class that implements the Lock interface, and ReentrantLock provides more methods.

3. synchronized

1. When two concurrent threads access the synchronized (this) synchronization code block in the same object object, only one thread can be executed at a time. Another thread must wait for the current thread to finish executing this code block before it can execute this code block.

2. However, when a thread accesses a synchronized (this) synchronized code block of object, another thread can still access the non-synchronized (this) synchronized code block in the object.

3. What is particularly critical is that when a thread accesses a synchronized (this) synchronized code block of object, other threads' access to all other synchronized (this) synchronized code blocks in object will be blocked.

4. The third example is also applicable to other synchronization code blocks. That is to say, when a thread accesses a synchronized(this) synchronized code block of object, it obtains the object lock of this object. As a result, other threads' access to all synchronized code parts of the object object is temporarily blocked. Scope of the synchronized keyword: Within an object instance, synchronized aMethod(){} can prevent multiple threads from accessing the synchronized method of this object at the same time (if an object has multiple synchronized methods, as long as one thread accesses one of the synchronized methods method, other threads cannot access any synchronized method in this object at the same time). At this time, the synchronized methods of different object instances do not interfere with each other. In other words, other threads can still access the synchronized method in another object instance of the same class at the same time; in the scope of a certain class, synchronized static aStaticMethod{} prevents multiple threads from accessing the synchronized static method in this class at the same time. It works on all object instances of the class.

The above is the detailed content of A brief introduction to the Java multi-threading keywords volatile, lock and synchronized. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of usage scenarios and functions of volatile keyword in Java Detailed explanation of usage scenarios and functions of volatile keyword in Java Jan 30, 2024 am 10:01 AM

Detailed explanation of the role and application scenarios of the volatile keyword in Java 1. The role of the volatile keyword In Java, the volatile keyword is used to identify a variable that is visible between multiple threads, that is, to ensure visibility. Specifically, when a variable is declared volatile, any modifications to the variable are immediately known to other threads. 2. Application scenarios of the volatile keyword The status flag volatile keyword is suitable for some status flag scenarios, such as a

Java development optimization method for file reading multi-thread acceleration performance Java development optimization method for file reading multi-thread acceleration performance Jun 30, 2023 pm 10:54 PM

In Java development, file reading is a very common and important operation. As your business grows, so do the size and number of files. In order to increase the speed of file reading, we can use multi-threading to read files in parallel. This article will introduce how to optimize file reading multi-thread acceleration performance in Java development. First, before reading the file, we need to determine the size and quantity of the file. Depending on the size and number of files, we can set the number of threads reasonably. Excessive number of threads may result in wasted resources,

Exception handling in Java multi-threaded environment Exception handling in Java multi-threaded environment May 01, 2024 pm 06:45 PM

Key points of exception handling in a multi-threaded environment: Catching exceptions: Each thread uses a try-catch block to catch exceptions. Handle exceptions: print error information or perform error handling logic in the catch block. Terminate the thread: When recovery is impossible, call Thread.stop() to terminate the thread. UncaughtExceptionHandler: To handle uncaught exceptions, you need to implement this interface and assign it to the thread. Practical case: exception handling in the thread pool, using UncaughtExceptionHandler to handle uncaught exceptions.

Explore the working principles and characteristics of java multithreading Explore the working principles and characteristics of java multithreading Feb 21, 2024 pm 03:39 PM

Explore the working principles and characteristics of Java multithreading Introduction: In modern computer systems, multithreading has become a common method of concurrent processing. As a powerful programming language, Java provides a rich multi-threading mechanism, allowing programmers to better utilize the computer's multi-core processor and improve program running efficiency. This article will explore the working principles and characteristics of Java multithreading and illustrate it with specific code examples. 1. The basic concept of multi-threading Multi-threading refers to executing multiple threads at the same time in a program, and each thread processes different

Java Multithreading Performance Optimization Guide Java Multithreading Performance Optimization Guide Apr 11, 2024 am 11:36 AM

The Java Multithreading Performance Optimization Guide provides five key optimization points: Reduce thread creation and destruction overhead Avoid inappropriate lock contention Use non-blocking data structures Leverage Happens-Before relationships Consider lock-free parallel algorithms

Java multi-thread debugging technology revealed Java multi-thread debugging technology revealed Apr 12, 2024 am 08:15 AM

Multi-threaded debugging technology answers: 1. Challenges in multi-threaded code debugging: The interaction between threads leads to complex and difficult-to-track behavior. 2. Java multi-thread debugging technology: line-by-line debugging thread dump (jstack) monitor entry and exit events thread local variables 3. Practical case: use thread dump to find deadlock, use monitor events to determine the cause of deadlock. 4. Conclusion: The multi-thread debugging technology provided by Java can effectively solve problems related to thread safety, deadlock and contention.

Multi-thread safety issues in Java - solutions to java.lang.ThreadDeath Multi-thread safety issues in Java - solutions to java.lang.ThreadDeath Jun 25, 2023 am 11:22 AM

Java is a programming language widely used in modern software development, and its multi-threaded programming capabilities are also one of its greatest advantages. However, due to the concurrent access problems caused by multi-threading, multi-thread safety issues often occur in Java. Among them, java.lang.ThreadDeath is a typical multi-thread security issue. This article will introduce the causes and solutions of java.lang.ThreadDeath. 1. Reasons for java.lang.ThreadDeath

Detailed explanation of Java multi-threaded concurrency lock Detailed explanation of Java multi-threaded concurrency lock Apr 11, 2024 pm 04:21 PM

The Java concurrency lock mechanism ensures that shared resources are accessed by only one thread in a multi-threaded environment. Its types include pessimistic locking (acquire the lock and then access) and optimistic locking (check for conflicts after accessing). Java provides built-in concurrency lock classes such as ReentrantLock (mutex lock), Semaphore (semaphore) and ReadWriteLock (read-write lock). Using these locks can ensure thread-safe access to shared resources, such as ensuring that when multiple threads access the shared variable counter at the same time, only one thread updates its value.

See all articles