Does object always see its latest internal state irrespective of thread?Does a finally block always get executed in Java?Java: serial thread confinement questionJava difference between fixed threadpool and scheduled threadpoolJackrabbit and concurrent modificationHow to stop a Runnable scheduled for repeated execution after a certain number of executionsvolatile keyword for objects in C++Multiple threads accessing inner classHow can a loop be completed by two thread? say loop from count=1 to count=4 by ist thread and count =5 to 8 by 2nd thread?If I keep a reference to a Runnable, when does the Thread it ran on get released?How to stop a schedule ScheduledExecutorService

Multi tool use
Multi tool use

Convert two switches to a dual stack, and add outlet - possible here?

Codimension of non-flat locus

Can a monk's single staff be considered dual wielded, as per the Dual Wielder feat?

Decision tree nodes overlapping with Tikz

Roll the carpet

Did Shadowfax go to Valinor?

What defenses are there against being summoned by the Gate spell?

how to check a propriety using r studio

Arrow those variables!

How much of data wrangling is a data scientist's job?

Approximately how much travel time was saved by the opening of the Suez Canal in 1869?

What is a clear way to write a bar that has an extra beat?

Modeling an IP Address

NMaximize is not converging to a solution

Languages that we cannot (dis)prove to be Context-Free

Why doesn't H₄O²⁺ exist?

Two films in a tank, only one comes out with a development error – why?

What's that red-plus icon near a text?

Are the number of citations and number of published articles the most important criteria for a tenure promotion?

How do I deal with an unproductive colleague in a small company?

Are astronomers waiting to see something in an image from a gravitational lens that they've already seen in an adjacent image?

Can a Cauchy sequence converge for one metric while not converging for another?

RSA: Danger of using p to create q

Why are electrically insulating heatsinks so rare? Is it just cost?



Does object always see its latest internal state irrespective of thread?


Does a finally block always get executed in Java?Java: serial thread confinement questionJava difference between fixed threadpool and scheduled threadpoolJackrabbit and concurrent modificationHow to stop a Runnable scheduled for repeated execution after a certain number of executionsvolatile keyword for objects in C++Multiple threads accessing inner classHow can a loop be completed by two thread? say loop from count=1 to count=4 by ist thread and count =5 to 8 by 2nd thread?If I keep a reference to a Runnable, when does the Thread it ran on get released?How to stop a schedule ScheduledExecutorService






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








8















Let's say I have a runnable with a simple integer count variable which is incremented every time runnable runs. One instance of this object is submitted to run periodically in a scheduled executor service.



class Counter implements Runnable 
private int count = 0;

@Override
public void run()
count++;



Counter counter = new Counter();
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5);
executorService.scheduleWithFixedDelay(counter, 1, 1, TimeUnit.SECONDS);


Here, object is accessing its own internal state inside of different threads (reading and incrementing). Is this code thread safe or it's possible that we lose updates to count variable when it's scheduled in a different thread?










share|improve this question






















  • Nope; most definitely not.

    – Boris the Spider
    2 hours ago






  • 3





    Just to be clear: When the answers below say "...no happens-before..." what they're saying is, Suppose count==N. Then along comes worker thread A, which sets count = N+1. Then one whole second later, worker thread B is chosen to call the run() method, and worker thread B looks at count. It is possible at that point for worker thread B to still see count == N.

    – Solomon Slow
    2 hours ago


















8















Let's say I have a runnable with a simple integer count variable which is incremented every time runnable runs. One instance of this object is submitted to run periodically in a scheduled executor service.



class Counter implements Runnable 
private int count = 0;

@Override
public void run()
count++;



Counter counter = new Counter();
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5);
executorService.scheduleWithFixedDelay(counter, 1, 1, TimeUnit.SECONDS);


Here, object is accessing its own internal state inside of different threads (reading and incrementing). Is this code thread safe or it's possible that we lose updates to count variable when it's scheduled in a different thread?










share|improve this question






















  • Nope; most definitely not.

    – Boris the Spider
    2 hours ago






  • 3





    Just to be clear: When the answers below say "...no happens-before..." what they're saying is, Suppose count==N. Then along comes worker thread A, which sets count = N+1. Then one whole second later, worker thread B is chosen to call the run() method, and worker thread B looks at count. It is possible at that point for worker thread B to still see count == N.

    – Solomon Slow
    2 hours ago














8












8








8


2






Let's say I have a runnable with a simple integer count variable which is incremented every time runnable runs. One instance of this object is submitted to run periodically in a scheduled executor service.



class Counter implements Runnable 
private int count = 0;

@Override
public void run()
count++;



Counter counter = new Counter();
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5);
executorService.scheduleWithFixedDelay(counter, 1, 1, TimeUnit.SECONDS);


Here, object is accessing its own internal state inside of different threads (reading and incrementing). Is this code thread safe or it's possible that we lose updates to count variable when it's scheduled in a different thread?










share|improve this question














Let's say I have a runnable with a simple integer count variable which is incremented every time runnable runs. One instance of this object is submitted to run periodically in a scheduled executor service.



class Counter implements Runnable 
private int count = 0;

@Override
public void run()
count++;



Counter counter = new Counter();
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5);
executorService.scheduleWithFixedDelay(counter, 1, 1, TimeUnit.SECONDS);


Here, object is accessing its own internal state inside of different threads (reading and incrementing). Is this code thread safe or it's possible that we lose updates to count variable when it's scheduled in a different thread?







java multithreading concurrency






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 3 hours ago









RandomQuestionRandomQuestion

3,055144579




3,055144579












  • Nope; most definitely not.

    – Boris the Spider
    2 hours ago






  • 3





    Just to be clear: When the answers below say "...no happens-before..." what they're saying is, Suppose count==N. Then along comes worker thread A, which sets count = N+1. Then one whole second later, worker thread B is chosen to call the run() method, and worker thread B looks at count. It is possible at that point for worker thread B to still see count == N.

    – Solomon Slow
    2 hours ago


















  • Nope; most definitely not.

    – Boris the Spider
    2 hours ago






  • 3





    Just to be clear: When the answers below say "...no happens-before..." what they're saying is, Suppose count==N. Then along comes worker thread A, which sets count = N+1. Then one whole second later, worker thread B is chosen to call the run() method, and worker thread B looks at count. It is possible at that point for worker thread B to still see count == N.

    – Solomon Slow
    2 hours ago

















Nope; most definitely not.

– Boris the Spider
2 hours ago





Nope; most definitely not.

– Boris the Spider
2 hours ago




3




3





Just to be clear: When the answers below say "...no happens-before..." what they're saying is, Suppose count==N. Then along comes worker thread A, which sets count = N+1. Then one whole second later, worker thread B is chosen to call the run() method, and worker thread B looks at count. It is possible at that point for worker thread B to still see count == N.

– Solomon Slow
2 hours ago






Just to be clear: When the answers below say "...no happens-before..." what they're saying is, Suppose count==N. Then along comes worker thread A, which sets count = N+1. Then one whole second later, worker thread B is chosen to call the run() method, and worker thread B looks at count. It is possible at that point for worker thread B to still see count == N.

– Solomon Slow
2 hours ago













3 Answers
3






active

oldest

votes


















3














No this code is not thread-safe because there is no happens-before relation between increments made in different threads started with ScheduledExecutorService.



To fix it you need to either mark variable as volatile or switch to AtomicInteger or AtomicLong.



UPDATE:
As @BoristheSpider mentioned, in general in case of increment/decrement making variable volatile is not enough since increment/decrement is not atomic itself and calling it from several threads concurrently will cause race conditions and missed updates. However in this particular case scheduleWithFixedDelay() guarantees (according to Javadoc) that there will be overlapping executions of scheduled task so volatile will also work in this particular case even with increment.






share|improve this answer

























  • @BoristheSpider taking into account how scheduleWithFixedDelay work there will be no overlapped calls to counter++ in that particular scenario. So volatile should be OK.

    – Ivan
    2 hours ago












  • There is a happens-before relation introduced between subsequent execution of a task scheduled with scheduleWithFixedDelay.

    – Sotirios Delimanolis
    1 hour ago











  • How come volatile is not enough? The semantics of volatile should hold in every case and it would solve this problem. In the past, the writing of doubles and longs could have been more difficult to do atomically since those occupied more than one 32-bit register. However, as far as I can tell, that should not affect the semantics of volatile. Or am I missing something?

    – Edwin Dalorzo
    1 hour ago











  • @EdwinDalorzo in this particular case volatile is enough. But in general case not because increment is effectively translated into 3 operations: read, add, write and is prone to race condition in multithreaded environment

    – Ivan
    1 hour ago











  • To reiterate, the code they have posted is thread-safe. This answer is wrong.

    – Sotirios Delimanolis
    36 mins ago


















2














No this is code is not thread safe since there is no happens before relation between different threads accessing count.






share|improve this answer




















  • 1





    Even then it's not thread safe, because ++ isn't atomic.

    – Andy Turner
    2 hours ago






  • 1





    @michid please correct me if I am wrong but shouldn't counter++ be synchronized too as increment operation is not atomic.

    – Yug Singh
    2 hours ago






  • 1





    Does counter++ need to be synchronized even if it's guaranteed that only one thread will be running this runnable at a time (like in the code in the question)?

    – RandomQuestion
    2 hours ago












  • @RandomQuestion yes. Because visibility.

    – Boris the Spider
    2 hours ago












  • I agree with the comments here that accesses to counter++ should be synchronized and that merely declaring it volatile is not sufficient. I edited my answer accordingly focusing on the happens-before relation.

    – michid
    2 hours ago


















0














Does object always see its latest internal state irrespective of thread?



Just to be clear for the purposes of this question and its answers, an object doesn't do anything, it's just memory. Threads are the executing entity. It's misleading to say does an object see whatever. It's the thread that's doing the seeing/reading of object state.



This isn't specified in the javadoc, but



Executors.newScheduledThreadPool(5);


returns a ScheduledThreadPoolExecutor.



Your code is using



executorService.scheduleWithFixedDelay(counter, 1, 1, TimeUnit.SECONDS);


The javadoc for ScheduledThreadPoolExecutor#scheduledWithFixedDelay states




Submits a periodic action that becomes enabled first after the given
initial delay, and subsequently with the given delay between the
termination of one execution and the commencement of the next.




The class javadoc further clarifies




Successive executions of a periodic task scheduled via
scheduleAtFixedRate or scheduleWithFixedDelay do not overlap.
While different executions may be performed by different threads, the
effects of prior executions happen-before those of subsequent ones
.




As such, each execution of Counter#run is guaranteed to see the value of count after it's been incremented by the previous execution. For example, the third execution will read a count value of 2 before it performs its increment.



You don't need volatile or any other additional synchronization mechanism for this specific use case.






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55542189%2fdoes-object-always-see-its-latest-internal-state-irrespective-of-thread%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    No this code is not thread-safe because there is no happens-before relation between increments made in different threads started with ScheduledExecutorService.



    To fix it you need to either mark variable as volatile or switch to AtomicInteger or AtomicLong.



    UPDATE:
    As @BoristheSpider mentioned, in general in case of increment/decrement making variable volatile is not enough since increment/decrement is not atomic itself and calling it from several threads concurrently will cause race conditions and missed updates. However in this particular case scheduleWithFixedDelay() guarantees (according to Javadoc) that there will be overlapping executions of scheduled task so volatile will also work in this particular case even with increment.






    share|improve this answer

























    • @BoristheSpider taking into account how scheduleWithFixedDelay work there will be no overlapped calls to counter++ in that particular scenario. So volatile should be OK.

      – Ivan
      2 hours ago












    • There is a happens-before relation introduced between subsequent execution of a task scheduled with scheduleWithFixedDelay.

      – Sotirios Delimanolis
      1 hour ago











    • How come volatile is not enough? The semantics of volatile should hold in every case and it would solve this problem. In the past, the writing of doubles and longs could have been more difficult to do atomically since those occupied more than one 32-bit register. However, as far as I can tell, that should not affect the semantics of volatile. Or am I missing something?

      – Edwin Dalorzo
      1 hour ago











    • @EdwinDalorzo in this particular case volatile is enough. But in general case not because increment is effectively translated into 3 operations: read, add, write and is prone to race condition in multithreaded environment

      – Ivan
      1 hour ago











    • To reiterate, the code they have posted is thread-safe. This answer is wrong.

      – Sotirios Delimanolis
      36 mins ago















    3














    No this code is not thread-safe because there is no happens-before relation between increments made in different threads started with ScheduledExecutorService.



    To fix it you need to either mark variable as volatile or switch to AtomicInteger or AtomicLong.



    UPDATE:
    As @BoristheSpider mentioned, in general in case of increment/decrement making variable volatile is not enough since increment/decrement is not atomic itself and calling it from several threads concurrently will cause race conditions and missed updates. However in this particular case scheduleWithFixedDelay() guarantees (according to Javadoc) that there will be overlapping executions of scheduled task so volatile will also work in this particular case even with increment.






    share|improve this answer

























    • @BoristheSpider taking into account how scheduleWithFixedDelay work there will be no overlapped calls to counter++ in that particular scenario. So volatile should be OK.

      – Ivan
      2 hours ago












    • There is a happens-before relation introduced between subsequent execution of a task scheduled with scheduleWithFixedDelay.

      – Sotirios Delimanolis
      1 hour ago











    • How come volatile is not enough? The semantics of volatile should hold in every case and it would solve this problem. In the past, the writing of doubles and longs could have been more difficult to do atomically since those occupied more than one 32-bit register. However, as far as I can tell, that should not affect the semantics of volatile. Or am I missing something?

      – Edwin Dalorzo
      1 hour ago











    • @EdwinDalorzo in this particular case volatile is enough. But in general case not because increment is effectively translated into 3 operations: read, add, write and is prone to race condition in multithreaded environment

      – Ivan
      1 hour ago











    • To reiterate, the code they have posted is thread-safe. This answer is wrong.

      – Sotirios Delimanolis
      36 mins ago













    3












    3








    3







    No this code is not thread-safe because there is no happens-before relation between increments made in different threads started with ScheduledExecutorService.



    To fix it you need to either mark variable as volatile or switch to AtomicInteger or AtomicLong.



    UPDATE:
    As @BoristheSpider mentioned, in general in case of increment/decrement making variable volatile is not enough since increment/decrement is not atomic itself and calling it from several threads concurrently will cause race conditions and missed updates. However in this particular case scheduleWithFixedDelay() guarantees (according to Javadoc) that there will be overlapping executions of scheduled task so volatile will also work in this particular case even with increment.






    share|improve this answer















    No this code is not thread-safe because there is no happens-before relation between increments made in different threads started with ScheduledExecutorService.



    To fix it you need to either mark variable as volatile or switch to AtomicInteger or AtomicLong.



    UPDATE:
    As @BoristheSpider mentioned, in general in case of increment/decrement making variable volatile is not enough since increment/decrement is not atomic itself and calling it from several threads concurrently will cause race conditions and missed updates. However in this particular case scheduleWithFixedDelay() guarantees (according to Javadoc) that there will be overlapping executions of scheduled task so volatile will also work in this particular case even with increment.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 2 hours ago

























    answered 2 hours ago









    IvanIvan

    5,69911022




    5,69911022












    • @BoristheSpider taking into account how scheduleWithFixedDelay work there will be no overlapped calls to counter++ in that particular scenario. So volatile should be OK.

      – Ivan
      2 hours ago












    • There is a happens-before relation introduced between subsequent execution of a task scheduled with scheduleWithFixedDelay.

      – Sotirios Delimanolis
      1 hour ago











    • How come volatile is not enough? The semantics of volatile should hold in every case and it would solve this problem. In the past, the writing of doubles and longs could have been more difficult to do atomically since those occupied more than one 32-bit register. However, as far as I can tell, that should not affect the semantics of volatile. Or am I missing something?

      – Edwin Dalorzo
      1 hour ago











    • @EdwinDalorzo in this particular case volatile is enough. But in general case not because increment is effectively translated into 3 operations: read, add, write and is prone to race condition in multithreaded environment

      – Ivan
      1 hour ago











    • To reiterate, the code they have posted is thread-safe. This answer is wrong.

      – Sotirios Delimanolis
      36 mins ago

















    • @BoristheSpider taking into account how scheduleWithFixedDelay work there will be no overlapped calls to counter++ in that particular scenario. So volatile should be OK.

      – Ivan
      2 hours ago












    • There is a happens-before relation introduced between subsequent execution of a task scheduled with scheduleWithFixedDelay.

      – Sotirios Delimanolis
      1 hour ago











    • How come volatile is not enough? The semantics of volatile should hold in every case and it would solve this problem. In the past, the writing of doubles and longs could have been more difficult to do atomically since those occupied more than one 32-bit register. However, as far as I can tell, that should not affect the semantics of volatile. Or am I missing something?

      – Edwin Dalorzo
      1 hour ago











    • @EdwinDalorzo in this particular case volatile is enough. But in general case not because increment is effectively translated into 3 operations: read, add, write and is prone to race condition in multithreaded environment

      – Ivan
      1 hour ago











    • To reiterate, the code they have posted is thread-safe. This answer is wrong.

      – Sotirios Delimanolis
      36 mins ago
















    @BoristheSpider taking into account how scheduleWithFixedDelay work there will be no overlapped calls to counter++ in that particular scenario. So volatile should be OK.

    – Ivan
    2 hours ago






    @BoristheSpider taking into account how scheduleWithFixedDelay work there will be no overlapped calls to counter++ in that particular scenario. So volatile should be OK.

    – Ivan
    2 hours ago














    There is a happens-before relation introduced between subsequent execution of a task scheduled with scheduleWithFixedDelay.

    – Sotirios Delimanolis
    1 hour ago





    There is a happens-before relation introduced between subsequent execution of a task scheduled with scheduleWithFixedDelay.

    – Sotirios Delimanolis
    1 hour ago













    How come volatile is not enough? The semantics of volatile should hold in every case and it would solve this problem. In the past, the writing of doubles and longs could have been more difficult to do atomically since those occupied more than one 32-bit register. However, as far as I can tell, that should not affect the semantics of volatile. Or am I missing something?

    – Edwin Dalorzo
    1 hour ago





    How come volatile is not enough? The semantics of volatile should hold in every case and it would solve this problem. In the past, the writing of doubles and longs could have been more difficult to do atomically since those occupied more than one 32-bit register. However, as far as I can tell, that should not affect the semantics of volatile. Or am I missing something?

    – Edwin Dalorzo
    1 hour ago













    @EdwinDalorzo in this particular case volatile is enough. But in general case not because increment is effectively translated into 3 operations: read, add, write and is prone to race condition in multithreaded environment

    – Ivan
    1 hour ago





    @EdwinDalorzo in this particular case volatile is enough. But in general case not because increment is effectively translated into 3 operations: read, add, write and is prone to race condition in multithreaded environment

    – Ivan
    1 hour ago













    To reiterate, the code they have posted is thread-safe. This answer is wrong.

    – Sotirios Delimanolis
    36 mins ago





    To reiterate, the code they have posted is thread-safe. This answer is wrong.

    – Sotirios Delimanolis
    36 mins ago













    2














    No this is code is not thread safe since there is no happens before relation between different threads accessing count.






    share|improve this answer




















    • 1





      Even then it's not thread safe, because ++ isn't atomic.

      – Andy Turner
      2 hours ago






    • 1





      @michid please correct me if I am wrong but shouldn't counter++ be synchronized too as increment operation is not atomic.

      – Yug Singh
      2 hours ago






    • 1





      Does counter++ need to be synchronized even if it's guaranteed that only one thread will be running this runnable at a time (like in the code in the question)?

      – RandomQuestion
      2 hours ago












    • @RandomQuestion yes. Because visibility.

      – Boris the Spider
      2 hours ago












    • I agree with the comments here that accesses to counter++ should be synchronized and that merely declaring it volatile is not sufficient. I edited my answer accordingly focusing on the happens-before relation.

      – michid
      2 hours ago















    2














    No this is code is not thread safe since there is no happens before relation between different threads accessing count.






    share|improve this answer




















    • 1





      Even then it's not thread safe, because ++ isn't atomic.

      – Andy Turner
      2 hours ago






    • 1





      @michid please correct me if I am wrong but shouldn't counter++ be synchronized too as increment operation is not atomic.

      – Yug Singh
      2 hours ago






    • 1





      Does counter++ need to be synchronized even if it's guaranteed that only one thread will be running this runnable at a time (like in the code in the question)?

      – RandomQuestion
      2 hours ago












    • @RandomQuestion yes. Because visibility.

      – Boris the Spider
      2 hours ago












    • I agree with the comments here that accesses to counter++ should be synchronized and that merely declaring it volatile is not sufficient. I edited my answer accordingly focusing on the happens-before relation.

      – michid
      2 hours ago













    2












    2








    2







    No this is code is not thread safe since there is no happens before relation between different threads accessing count.






    share|improve this answer















    No this is code is not thread safe since there is no happens before relation between different threads accessing count.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 2 hours ago

























    answered 2 hours ago









    michidmichid

    5,54921938




    5,54921938







    • 1





      Even then it's not thread safe, because ++ isn't atomic.

      – Andy Turner
      2 hours ago






    • 1





      @michid please correct me if I am wrong but shouldn't counter++ be synchronized too as increment operation is not atomic.

      – Yug Singh
      2 hours ago






    • 1





      Does counter++ need to be synchronized even if it's guaranteed that only one thread will be running this runnable at a time (like in the code in the question)?

      – RandomQuestion
      2 hours ago












    • @RandomQuestion yes. Because visibility.

      – Boris the Spider
      2 hours ago












    • I agree with the comments here that accesses to counter++ should be synchronized and that merely declaring it volatile is not sufficient. I edited my answer accordingly focusing on the happens-before relation.

      – michid
      2 hours ago












    • 1





      Even then it's not thread safe, because ++ isn't atomic.

      – Andy Turner
      2 hours ago






    • 1





      @michid please correct me if I am wrong but shouldn't counter++ be synchronized too as increment operation is not atomic.

      – Yug Singh
      2 hours ago






    • 1





      Does counter++ need to be synchronized even if it's guaranteed that only one thread will be running this runnable at a time (like in the code in the question)?

      – RandomQuestion
      2 hours ago












    • @RandomQuestion yes. Because visibility.

      – Boris the Spider
      2 hours ago












    • I agree with the comments here that accesses to counter++ should be synchronized and that merely declaring it volatile is not sufficient. I edited my answer accordingly focusing on the happens-before relation.

      – michid
      2 hours ago







    1




    1





    Even then it's not thread safe, because ++ isn't atomic.

    – Andy Turner
    2 hours ago





    Even then it's not thread safe, because ++ isn't atomic.

    – Andy Turner
    2 hours ago




    1




    1





    @michid please correct me if I am wrong but shouldn't counter++ be synchronized too as increment operation is not atomic.

    – Yug Singh
    2 hours ago





    @michid please correct me if I am wrong but shouldn't counter++ be synchronized too as increment operation is not atomic.

    – Yug Singh
    2 hours ago




    1




    1





    Does counter++ need to be synchronized even if it's guaranteed that only one thread will be running this runnable at a time (like in the code in the question)?

    – RandomQuestion
    2 hours ago






    Does counter++ need to be synchronized even if it's guaranteed that only one thread will be running this runnable at a time (like in the code in the question)?

    – RandomQuestion
    2 hours ago














    @RandomQuestion yes. Because visibility.

    – Boris the Spider
    2 hours ago






    @RandomQuestion yes. Because visibility.

    – Boris the Spider
    2 hours ago














    I agree with the comments here that accesses to counter++ should be synchronized and that merely declaring it volatile is not sufficient. I edited my answer accordingly focusing on the happens-before relation.

    – michid
    2 hours ago





    I agree with the comments here that accesses to counter++ should be synchronized and that merely declaring it volatile is not sufficient. I edited my answer accordingly focusing on the happens-before relation.

    – michid
    2 hours ago











    0














    Does object always see its latest internal state irrespective of thread?



    Just to be clear for the purposes of this question and its answers, an object doesn't do anything, it's just memory. Threads are the executing entity. It's misleading to say does an object see whatever. It's the thread that's doing the seeing/reading of object state.



    This isn't specified in the javadoc, but



    Executors.newScheduledThreadPool(5);


    returns a ScheduledThreadPoolExecutor.



    Your code is using



    executorService.scheduleWithFixedDelay(counter, 1, 1, TimeUnit.SECONDS);


    The javadoc for ScheduledThreadPoolExecutor#scheduledWithFixedDelay states




    Submits a periodic action that becomes enabled first after the given
    initial delay, and subsequently with the given delay between the
    termination of one execution and the commencement of the next.




    The class javadoc further clarifies




    Successive executions of a periodic task scheduled via
    scheduleAtFixedRate or scheduleWithFixedDelay do not overlap.
    While different executions may be performed by different threads, the
    effects of prior executions happen-before those of subsequent ones
    .




    As such, each execution of Counter#run is guaranteed to see the value of count after it's been incremented by the previous execution. For example, the third execution will read a count value of 2 before it performs its increment.



    You don't need volatile or any other additional synchronization mechanism for this specific use case.






    share|improve this answer





























      0














      Does object always see its latest internal state irrespective of thread?



      Just to be clear for the purposes of this question and its answers, an object doesn't do anything, it's just memory. Threads are the executing entity. It's misleading to say does an object see whatever. It's the thread that's doing the seeing/reading of object state.



      This isn't specified in the javadoc, but



      Executors.newScheduledThreadPool(5);


      returns a ScheduledThreadPoolExecutor.



      Your code is using



      executorService.scheduleWithFixedDelay(counter, 1, 1, TimeUnit.SECONDS);


      The javadoc for ScheduledThreadPoolExecutor#scheduledWithFixedDelay states




      Submits a periodic action that becomes enabled first after the given
      initial delay, and subsequently with the given delay between the
      termination of one execution and the commencement of the next.




      The class javadoc further clarifies




      Successive executions of a periodic task scheduled via
      scheduleAtFixedRate or scheduleWithFixedDelay do not overlap.
      While different executions may be performed by different threads, the
      effects of prior executions happen-before those of subsequent ones
      .




      As such, each execution of Counter#run is guaranteed to see the value of count after it's been incremented by the previous execution. For example, the third execution will read a count value of 2 before it performs its increment.



      You don't need volatile or any other additional synchronization mechanism for this specific use case.






      share|improve this answer



























        0












        0








        0







        Does object always see its latest internal state irrespective of thread?



        Just to be clear for the purposes of this question and its answers, an object doesn't do anything, it's just memory. Threads are the executing entity. It's misleading to say does an object see whatever. It's the thread that's doing the seeing/reading of object state.



        This isn't specified in the javadoc, but



        Executors.newScheduledThreadPool(5);


        returns a ScheduledThreadPoolExecutor.



        Your code is using



        executorService.scheduleWithFixedDelay(counter, 1, 1, TimeUnit.SECONDS);


        The javadoc for ScheduledThreadPoolExecutor#scheduledWithFixedDelay states




        Submits a periodic action that becomes enabled first after the given
        initial delay, and subsequently with the given delay between the
        termination of one execution and the commencement of the next.




        The class javadoc further clarifies




        Successive executions of a periodic task scheduled via
        scheduleAtFixedRate or scheduleWithFixedDelay do not overlap.
        While different executions may be performed by different threads, the
        effects of prior executions happen-before those of subsequent ones
        .




        As such, each execution of Counter#run is guaranteed to see the value of count after it's been incremented by the previous execution. For example, the third execution will read a count value of 2 before it performs its increment.



        You don't need volatile or any other additional synchronization mechanism for this specific use case.






        share|improve this answer















        Does object always see its latest internal state irrespective of thread?



        Just to be clear for the purposes of this question and its answers, an object doesn't do anything, it's just memory. Threads are the executing entity. It's misleading to say does an object see whatever. It's the thread that's doing the seeing/reading of object state.



        This isn't specified in the javadoc, but



        Executors.newScheduledThreadPool(5);


        returns a ScheduledThreadPoolExecutor.



        Your code is using



        executorService.scheduleWithFixedDelay(counter, 1, 1, TimeUnit.SECONDS);


        The javadoc for ScheduledThreadPoolExecutor#scheduledWithFixedDelay states




        Submits a periodic action that becomes enabled first after the given
        initial delay, and subsequently with the given delay between the
        termination of one execution and the commencement of the next.




        The class javadoc further clarifies




        Successive executions of a periodic task scheduled via
        scheduleAtFixedRate or scheduleWithFixedDelay do not overlap.
        While different executions may be performed by different threads, the
        effects of prior executions happen-before those of subsequent ones
        .




        As such, each execution of Counter#run is guaranteed to see the value of count after it's been incremented by the previous execution. For example, the third execution will read a count value of 2 before it performs its increment.



        You don't need volatile or any other additional synchronization mechanism for this specific use case.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 1 hour ago

























        answered 1 hour ago









        Sotirios DelimanolisSotirios Delimanolis

        212k41500590




        212k41500590



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55542189%2fdoes-object-always-see-its-latest-internal-state-irrespective-of-thread%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            XH G76 38H7GH7DWlnQYDd3NBLD
            33NQS,vQ4TTgz hieoXnG6DzSbcF,9Warc,ugzFxput,A,j7DlMT TJF

            Popular posts from this blog

            Typsetting diagram chases (with TikZ?) Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)How to define the default vertical distance between nodes?Draw edge on arcNumerical conditional within tikz keys?TikZ: Drawing an arc from an intersection to an intersectionDrawing rectilinear curves in Tikz, aka an Etch-a-Sketch drawingLine up nested tikz enviroments or how to get rid of themHow to place nodes in an absolute coordinate system in tikzCommutative diagram with curve connecting between nodesTikz with standalone: pinning tikz coordinates to page cmDrawing a Decision Diagram with Tikz and layout manager

            SQL Server 2016 - excessive memory grant warning on poor performing query The Next CEO of Stack OverflowFix for slow SQL_INLINE_TABLE_VALUED_FUNCTIONLarge memory grant requestsPoor performing Query -Tsql execution plan - estimated number of rows =1 Paste the PlanMSSQL - Query had to wait for memory grantRow estimates always too lowBad performance using “NOT IN”Warning about memory “Excessive Grant” in the query plan - how to find out what is causing it?Optimizing table valued function SQL ServerWhen does SQL Server warn about an Excessive Memory Grant?Warning in Execution Plan

            What is the result of assigning to std::vector::begin()? The Next CEO of Stack OverflowWhat are the differences between a pointer variable and a reference variable in C++?What does the explicit keyword mean?Concatenating two std::vectorsHow to find out if an item is present in a std::vector?Why is “using namespace std” considered bad practice?What is the “-->” operator in C++?What is the easiest way to initialize a std::vector with hardcoded elements?What is The Rule of Three?What are the basic rules and idioms for operator overloading?Why are std::begin and std::end “not memory safe”?