The difference and connection between synchronized and volatile in Java
This article mainly introduces the relevant information about the difference and connection between volatile and synchronized in Java. I hope this article can help everyone understand this part of the content. Friends in need can refer to it
The difference and connection between volatile and synchronized in java
This may be the best article comparing the effects of volatile and synchronized. Volatile is a variable modifier, and synchronized is a method or block modifier. So we use these two keywords to specify three simple ways to access variables
int i1; int geti1() {return i1;} volatile int i2; int geti2() {return i2;} int i3; synchronized int geti3() {return i3;}
geti1() immediately obtains the i1 variable in the current thread value in . A thread can obtain a local copy of a variable, and the value of the variable obtained is not necessarily the same as the value obtained by other threads. In particular, if other threads modify the value of i1, the value of i1 obtained by the current thread may be different from the modified value. In fact, Java has a main memory mechanism that uses a main memory to save the current correct value of the variable. Threads copy the values of variables to their own independent memory, and the memory copies of these threads may be different from the values in main memory. So in practice, it may happen that the value of i1 in the main memory is 1, and both thread 1 and thread 2 have changed i1, but the updated value has not been transferred back to the main memory or other threads. Then it may be that in the thread The value of i1 in thread 1 is 2, but the value of i1 in thread 2 is 3.
On the other hand, geti2() can effectively obtain the value of i2 from main memory. A volatile variable does not allow a thread to copy the value of the variable from main memory to its own storage space. Therefore, a variable declared as volatile will obtain data synchronously in all threads. No matter you change the variable in any thread, other threads will immediately get the same result. Because it is more efficient for threads to access or change their own data copies, volatile type variables consume some performance.
So if volatile variables can already synchronize data between threads, what are synchronizes used for? There are two differences between the two. First, synchronized acquires and releases locks controlled by the listener. If both threads use a listener (that is, the same object lock), then the listener can force only one thread to process the code block at a time. This is the most general Synchronize. In addition, synchronized can also synchronize memory. In practice, synchronized makes all thread memory synchronized with main memory. So the execution process of geti3() is as follows:
1. The thread acquires the object's lock from the listener. (It is assumed here that the listener is not locked, otherwise the thread cannot obtain the object lock until the listener is unlocked)
2. The thread memory updates all variables, which means that it will read the variables in the main memory Make your own variables guaranteed to be valid. (The JVM will use a "dirty" flag to optimize the process so that only variables with the "dirty" flag are updated. For details, check 17.9 of the JAVA specification)
3. The code block is executed ( In this example, set the return value to the current value of i3 just reset from main memory. )
4. Any changes to the variables will be written back to main memory. But there is no change in geti3() in this example.
5. The thread releases the object's lock to the listener.
So volatile can only synchronize the value of one variable between thread memory and main memory, while synchronized synchronizes the value of all variables between thread memory and main memory, and by locking and Release the listener to achieve this. Obviously, synchronized will be more expensive in performance than volatile.
About the difference between the two
1. The essence of volatile is to tell the jvm that the value of the current variable in the register (working memory) is uncertain. It needs to be read from main memory; synchronized locks the current variable. Only the current thread can access the variable, and other threads are blocked.
2.volatile can only be used at the variable level; synchronized can be used at the variable, method, and class levels
3.volatile can only be implemented The modification visibility of variables cannot guarantee atomicity; while synchronized can guarantee the modification visibility and atomicity of variables
4.volatile will not cause thread blocking; synchronized may cause Thread blocking.
5. Variables marked volatile will not be optimized by the compiler; variables marked synchronized can be optimized by the compiler
The reasons for the red font part are as follows:
When thread A modifies the variable before it ends, another thread B can see the modified value and can modify the variable without waiting for A to release the lock, because the Volatile variable Unlocked
The above is the detailed content of The difference and connection between synchronized and volatile in Java. For more information, please follow other related articles on the PHP Chinese website!

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.
