Home  >  Article  >  Java  >  Java engineer interview - volatile keyword

Java engineer interview - volatile keyword

王林
王林forward
2020-11-03 15:47:331853browse

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete