DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Analyzing “java.lang.OutOfMemoryError: Failed to create a thread” Error
  • Fixing OutOfMemoryErrors in Java Applications
  • Understanding Root Causes of Out of Memory (OOM) Issues in Java Containers
  • Singleton: 6 Ways To Write and Use in Java Programming

Trending

  • Memory-Optimized Tables: Implementation Strategies for SQL Server
  • AI Speaks for the World... But Whose Humanity Does It Learn From?
  • Simpler Data Transfer Objects With Java Records
  • When Airflow Tasks Get Stuck in Queued: A Real-World Debugging Story
  1. DZone
  2. Coding
  3. Java
  4. Difference Between Volatile and Synchronized Keywords in Java

Difference Between Volatile and Synchronized Keywords in Java

Want to learn more about the difference between volatile and synchronized keywords? Check out this post to learn more about different keywords and variables in Java.

By 
Siddhartha Bhattacharjee user avatar
Siddhartha Bhattacharjee
·
Aug. 22, 18 · Analysis
Likes (23)
Comment
Save
Tweet
Share
64.7K Views

Join the DZone community and get the full member experience.

Join For Free

This article covers some basic, but very important, concepts in Java. 

volatile is a field modifier, while synchronized modifies code blocks and methods.

So, we can specify three variations of a simple accessor using those two keywords:

int i1;              
int geti1() {return i1;}

volatile int i2;              
int geti2() {return i2;}        

int i3;
synchronized int geti3() {return i3;}  


Above, we defined three integer variables:  i1 , i2,  and  i3 . And, we defined three corresponding getter methods:  geti1(), geti2(),  and geti3().

geti1() accesses the value currently stored in i1 in the current thread.

Threads can have local copies of variables, and the data does not have to be the same as the data held in other threads. In particular, another thread may have updated i1 in it's thread, but the value in the current thread could be different from that updated value. In fact, Java demonstrates the idea of a "main" memory, and this is the memory that holds the current "correct" value for variables. Threads can have their own copy of data for variables, and the thread copy can be different from the "main" memory.

Therefore, it is possible for the "main" memory to have a value of 1 for i1, for thread1 to have a value of 2 for i1, and for thread3 to have a value of 3 for i1 if thread1 and thread2 have both updated i1. But, the updated values have not yet been propagated to the "main" memory or other threads.

On the other hand, geti2() effectively accesses the value of i2 from the "main" memory. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have its data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Generally, volatile variables have a higher access and update overhead than "plain" variables. Typically, threads are allowed to have their own copy of data, which is for better efficiency.

There are two differences between volatile and synchronized:

First, synchronized obtains and releases locks on monitors, which can force only one thread at a time to execute a code block. That's a fairly well-known aspect to synchronized. But synchronized also synchronizes memory. In fact, synchronized synchronizes the whole of the thread memory with "main" memory. So, executing geti3() does the following:

  1. The thread acquires the lock on the monitor for the object this .
  2. The thread memory flushes all its variables, i.e. it has all of its variables effectively read from the "main" memory.
  3. The code block is executed. In this case, this means setting the return value to the current value of i3, which may have just been reset from "main" memory.
  4. Any changes to variables would normally be written out to the "main" memory, but for geti3(), we have no changes.
  5. The thread releases the lock on the monitor for the object this.

So, where volatile only synchronizes the value of one variable between the thread memory and the "main" memory, synchronized synchronizes the value of all variables between the thread memory and the "main" memory and locks and releases a monitor to control the ownership between multiple threads.

From this information, it can be concluded that synchronized is likely to have more overhead than volatile.

Memory (storage engine) Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Analyzing “java.lang.OutOfMemoryError: Failed to create a thread” Error
  • Fixing OutOfMemoryErrors in Java Applications
  • Understanding Root Causes of Out of Memory (OOM) Issues in Java Containers
  • Singleton: 6 Ways To Write and Use in Java Programming

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!