search
HomeJavajavaTutorialThe 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!

Statement
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
Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

Is Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksIs Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksMay 13, 2025 am 12:03 AM

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

Demystifying the JVM: Your Key to Understanding Java ExecutionDemystifying the JVM: Your Key to Understanding Java ExecutionMay 13, 2025 am 12:02 AM

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Is java still a good language based on new features?Is java still a good language based on new features?May 12, 2025 am 12:12 AM

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

What Makes Java Great? Key Features and BenefitsWhat Makes Java Great? Key Features and BenefitsMay 12, 2025 am 12:11 AM

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Top 5 Java Features: Examples and ExplanationsTop 5 Java Features: Examples and ExplanationsMay 12, 2025 am 12:09 AM

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.

See all articles

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

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.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.