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 函数中的 volatile 变量如何保证线程安全?Java 函数中的 volatile 变量如何保证线程安全?May 04, 2024 am 10:15 AM

Java中volatile变量保证线程安全的方法:可见性:确保一个线程对volatile变量的修改立即对其他线程可见。原子性:确保对volatile变量的某些操作(如写入、读取和比较交换)是不可分割的,不会被其他线程打断。

详解Java中volatile关键字的使用场景及其作用详解Java中volatile关键字的使用场景及其作用Jan 30, 2024 am 10:01 AM

Java中volatile关键字的作用及应用场景详解一、volatile关键字的作用在Java中,volatile关键字用于标识一个变量在多个线程之间可见,即保证可见性。具体来说,当一个变量被声明为volatile时,任何对该变量的修改都会立即被其他线程所知晓。二、volatile关键字的应用场景状态标志volatile关键字适用于一些状态标志的场景,例如一

Java并发编程之volatile与JMM多线程内存模型实例分析Java并发编程之volatile与JMM多线程内存模型实例分析May 27, 2023 am 08:58 AM

一、通过程序看现象在开始为大家讲解Java多线程缓存模型之前,我们先看下面的这一段代码。这段代码的逻辑很简单:主线程启动了两个子线程,一个线程1、一个线程2。线程1先执行,sleep睡眠2秒钟之后线程2执行。两个线程使用到了一个共享变量shareFlag,初始值为false。如果shareFlag一直等于false,线程1将一直处于死循环状态,所以我们在线程2中将shareFlag设置为true。publicclassVolatileTest{publicstaticbooleanshareFl

C++编译错误:不能调用从volatile类型转换的成员函数,怎么处理?C++编译错误:不能调用从volatile类型转换的成员函数,怎么处理?Aug 21, 2023 pm 09:28 PM

C++是一门强类型语言,严格限制了变量的类型转换,但是在某些情况下,我们可能需要对volatile类型对象进行类型转换,特别是在嵌入式开发中,我们常常需要访问硬件寄存器,而这些寄存器通常都是volatile类型的。然而,由于volatile类型的对象具有特殊的语义,所以C++编译器会对其进行一些特殊的限制,这就导致了“不能调用从volatile类型转换的成员

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

了解Java中volatile的作用:保证多线程间数据的可见性和有序性了解Java中volatile的作用:保证多线程间数据的可见性和有序性Jan 30, 2024 am 08:53 AM

了解Java中volatile的作用:保证多线程间数据的可见性和有序性,需要具体代码示例在Java多线程编程中,为了确保多个线程之间的数据同步,我们常常需要使用volatile关键字。volatile关键字可以保证可见性和有序性,确保多个线程对某个变量的读写操作是正确的。一、可见性在多线程环境下,如果一个线程对某个共享变量进行修改,那么其他线程是否能够立即看

归纳整理JAVA装饰器模式(实例详解)归纳整理JAVA装饰器模式(实例详解)May 05, 2022 pm 06:48 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于设计模式的相关问题,主要将装饰器模式的相关内容,指在不改变现有对象结构的情况下,动态地给该对象增加一些职责的模式,希望对大家有帮助。

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

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 agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools