Java engineer interview - volatile keyword

王林
Release: 2020-11-03 15:47:33
forward
1846 people have browsed it

Java engineer interview - volatile keyword

1. What exactly does volatile do?

(volatile guarantees orderliness and visibility, but cannot guarantee atomicity)

(Video tutorial recommended : java video tutorial)

1. Instruction rearrangement is prohibited

2. The visibility is guaranteed when different threads operate on this variable, that is, one thread modifies it If a certain variable value is set, the new value is immediately visible to other threads

3. Atomicity is not guaranteed (thread unsafe)

2. Comparison of synchronized keyword and volatile keyword

The volatile keyword is a lightweight implementation of thread synchronization, so the volatile performance is definitely better than the synchronized keyword. However, the volatile keyword can only be used for variables and the synchronized keyword can modify methods and code blocks.

(Recommendations for more related interview questions: java interview questions and answers)

The synchronized keyword was introduced after JavaSE1.6, mainly to reduce lock acquisition and release The execution efficiency has been significantly improved after the introduction of biased locks, lightweight locks and various other optimizations due to the performance consumption caused by locks. There are still more scenarios where the synchronized keyword is used in actual development.

Multi-threaded access to the volatile keyword will not block, but the synchronized keyword may block.

The volatile keyword can guarantee the visibility of data, but it cannot guarantee the atomicity of the data. The synchronized keyword can guarantee both (synchronized guarantees three major properties, atomicity, orderliness, and visibility).

The volatile keyword is mainly used to solve the visibility of variables between multiple threads, while the synchronized keyword solves the synchronization of access to resources between multiple threads.

Related recommendations:Getting started with java

The above is the detailed content of Java engineer interview - volatile keyword. 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