Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 995413
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T06:43:07+00:00 2026-05-16T06:43:07+00:00

I have read When to use ‘volatile’ in Java? but I’m still confused. How

  • 0

I have read “When to use ‘volatile’ in Java?” but I’m still confused. How do I know when I should mark a variable volatile? What if I get it wrong, either omitting a volatile on something that needs it or putting volatile on something that doesn’t? What are the rules of thumb when figuring out what variables should be volatile in multithreaded code?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T06:43:08+00:00Added an answer on May 16, 2026 at 6:43 am

    You basically use it when you want to let a member variable be accessed by multiple threads but do not need compound atomicity (not sure if this is the right terminology).

    class BadExample {
        private volatile int counter;
    
        public void hit(){
            /* This operation is in fact two operations:
             * 1) int tmp = this.counter;
             * 2) this.counter = tmp + 1;
             * and is thus broken (counter becomes fewer
             * than the accurate amount).
             */
            counter++;
        }
    }
    

    the above is a bad example, because you need compound atomicity.

     class BadExampleFixed {
        private int counter;
    
        public synchronized void hit(){
            /*
             * Only one thread performs action (1), (2) at a time
             * "atomically", in the sense that other threads can not 
             * observe the intermediate state between (1) and (2).
             * Therefore, the counter will be accurate.
             */
            counter++;
        }
    }
    

    Now to a valid example:

     class GoodExample {
        private static volatile int temperature;
    
        //Called by some other thread than main
        public static void todaysTemperature(int temp){
            // This operation is a single operation, so you 
            // do not need compound atomicity
            temperature = temp;
        }
    
        public static void main(String[] args) throws Exception{
            while(true){
               Thread.sleep(2000);
               System.out.println("Today's temperature is "+temperature);
            }
        }
    }
    

    Now, why can’t you just use private static int temperature? In fact you can (in the sense that that your program won’t blow up or something), but the change to temperature by the other thread may or may not be “visible” to the main thread.

    Basically this means that it is even possible that your app. keeps writing Today's temperature is 0 forever if you don’t use volatile (in practice, the value tends to become eventually visible. However, you should not risk not using volatile when necessary, since it can lead to nasty bugs (caused by in-completely constructed objects etc.).

    If you put volatile keyword on something that doesn’t need volatile, it won’t affect your code’s correctness (i.e. the behaviour will not change). In terms of performance, it will depend on the JVM implementation. In theory you might get a tiny performance degradation because the compiler can’t do reordering optimisations, have to invalidate CPU cache etc., but then again the compiler could prove that your field cannot ever be accessed by multiple threads and remove the effect of volatile keyword completely and compile it to identical instructions.

    EDIT:
    Response to this comment:

    Ok, but why can’t we make todaysTemperature synchronized and create a synchronized getter for temperature?

    You can and it will behave correctly. Anything that you can with volatile can be done with synchronized, but not vice versa. There are two reasons you might prefer volatile if you can:

    1. Less bug prone: This depends on the context, but in many cases using volatile is less prone to concurrency bugs, like blocking while holding the lock, deadlocks etc.
    2. More performant: In most JVM implementations, volatile can have significantly higher throughput and better latency. However in most applications the difference is too small to matter.
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have read that you should use volatile when a thread accesses a variable
I have read that you should not use get json for retrieving sensitive data
I have read that after select we use column-names but I have found a
I have read tutorials and several stack overflow posts that suggest I should use
I have read other related posts, but am still not quite sure how, or
Possible Duplicate: Why use getters and setters? I have read books on Java, saying
i want to use google app hosting , but i have read that they
I have read about Java enums and use them regularly. However, I don't understand
I have read (and generally agree) that to increase code legibility, you should use
I would love to use closures in Java. I have read that they may

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.