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 8081827
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T16:51:41+00:00 2026-06-05T16:51:41+00:00

Should we declare the private fields as volatile if the instanced are used in

  • 0

Should we declare the private fields as volatile if the instanced are used in multiple threads?

In Effective Java, there is an example where the code doesn’t work without volatile:

import java.util.concurrent.TimeUnit;

// Broken! - How long would you expect this program to run?
public class StopThread {
    private static boolean stopRequested; // works, if volatile is here

    public static void main(String[] args) throws InterruptedException {
        Thread backgroundThread = new Thread(new Runnable() {
            public void run() {
                int i = 0;
                while (!stopRequested)
                    i++;
            }
        });
        backgroundThread.start();
        TimeUnit.SECONDS.sleep(1);
        stopRequested = true;
    }
}

The explanations says that

while(!stopRequested)
    i++;

is optimized to something like this:

if(!stopRequested)
    while(true)
        i++;

so further modifications of stopRequested aren’t seen by the background thread, so it loops forever. (BTW, that code terminates without volatile on JRE7.)

Now consider this class:

public class Bean {
    private boolean field = true;

    public boolean getField() {
        return field;
    }

    public void setField(boolean value) {
        field = value;
    }
}

and a thread as follows:

public class Worker implements Runnable {
    private Bean b;

    public Worker(Bean b) {
        this.b = b;
    }

    @Override
    public void run() {
        while(b.getField()) {
            System.err.println("Waiting...");
            try { Thread.sleep(1000); }
            catch(InterruptedException ie) { return; }
        }
    }
}

The above code works as expected without using volatiles:

public class VolatileTest {
    public static void main(String [] args) throws Exception {
        Bean b = new Bean();

        Thread t = new Thread(new Worker(b));
        t.start();
        Thread.sleep(3000);

        b.setField(false); // stops the child thread
        System.err.println("Waiting the child thread to quit");
        t.join();
        // if the code gets, here the child thread is stopped
        // and it really gets, with JRE7, 6 with -server, -client
    }
}

I think because of the public setter, the compiler/JVM should never optimize the code which calls getField(), but this article says that there is some “Volatile Bean” pattern (Pattern #4), which should be applied to create mutable thread-safe classes. Update: maybe that article applies for IBM JVM only?

The question is: which part of JLS explicitly or implicitly says that private primitive fields with public getters/setters must be declared as volatile (or they don’t have to)?

Sorry for a long question, I tried to explain the problem in details. Let me know if something is not clear. Thanks.

  • 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-06-05T16:51:45+00:00Added an answer on June 5, 2026 at 4:51 pm

    Before I answer your question I want to address

    BTW, that code terminates without volatile on JRE7

    This can change if you were to deploy the same application with different runtime arguments. Hoisting isn’t necessarily a default implementation for JVMs so it can work in one and not in another.

    To answer your question there is nothing preventing the Java compiler from executing your latter example like so

    @Override
    public void run() {
        if(b.getField()){
            while(true) {
                System.err.println("Waiting...");
                try { Thread.sleep(1000); }
                catch(InterruptedException ie) { return; }
            }
        }
    }
    

    It is still sequentially consistent and thus maintains Java’s guarantees – you can read specifically 17.4.3:

    Among all the inter-thread actions performed by each thread t, the
    program order of t is a total order that reflects the order in which
    these actions would be performed according to the intra-thread
    semantics of t.

    A set of actions is sequentially consistent if all actions occur in a
    total order (the execution order) that is consistent with program
    order, and furthermore, each read r of a variable v sees the value
    written by the write w to v such that:

    In other words – So long as a thread will see the read and write of a field in the same order regardless of the compiler/memory re ordering it is considered sequentially consistent.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am unsure if the volatile keyword should also be used for non-primitives. I
I guess the procedure should be something like this: declare @db varchar(100) declare @user
Should all structs and classes be declared in the header file? If I declare
I wondered if it makes sense to declare a private method as final as
Should I initialize class fields at declaration like this? public class SomeTest extends TestCase
in python there is way to declare def 's without putting it in class.
I have a question with singlton. Where should I declare the static member of
Looking at the example code on MSDN : This ' Declares a type. Dim
A question about inheritance in java... class Base { private int val = 10;
Is there any nice pattern in .Net for ensuring that IDisposable fields owned by

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.