Does an object always see its latest internal state irrespective of thread? The 2019 Stack Overflow Developer Survey Results Are InDoes 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 executionsMultiple 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 ScheduledExecutorServiceHow to implement a singleThreadedScheduledExcecutor in wildfly
Get name of standard action overriden in Visualforce contorller
Match Roman Numerals
Inverse Relationship Between Precision and Recall
writing variables above the numbers in tikz picture
Did Scotland spend $250,000 for the slogan "Welcome to Scotland"?
Slides for 30 min~1 hr Skype tenure track application interview
How to notate time signature switching consistently every measure
Are spiders unable to hurt humans, especially very small spiders?
If a sorcerer casts the Banishment spell on a PC while in Avernus, does the PC return to their home plane?
Why couldn't they take pictures of a closer black hole?
Compute the product of 3 dictionaries and concatenate keys and values
How to support a colleague who finds meetings extremely tiring?
How do I free up internal storage if I don't have any apps downloaded?
Star Trek - X-shaped Item on Regula/Orbital Office Starbases
What information about me do stores get via my credit card?
What is the most efficient way to store a numeric range?
The phrase "to the numbers born"?
Mathematics of imaging the black hole
"as much details as you can remember"
Did any laptop computers have a built-in 5 1/4 inch floppy drive?
Is it possible for absolutely everyone to attain enlightenment?
For what reasons would an animal species NOT cross a *horizontal* land bridge?
What is the meaning of Triage in Cybersec world?
Correct punctuation for showing a character's confusion
Does an object always see its latest internal state irrespective of thread?
The 2019 Stack Overflow Developer Survey Results Are InDoes 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 executionsMultiple 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 ScheduledExecutorServiceHow to implement a singleThreadedScheduledExcecutor in wildfly
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
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, the object is accessing its own internal state inside of different threads (reading and incrementing). Is this code thread-safe or is it possible that we lose updates to the count
variable when it's scheduled in a different thread?
java multithreading concurrency
add a comment |
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, the object is accessing its own internal state inside of different threads (reading and incrementing). Is this code thread-safe or is it possible that we lose updates to the count
variable when it's scheduled in a different thread?
java multithreading concurrency
1
Nope; most definitely not.
– Boris the Spider
Apr 5 at 19:36
3
Just to be clear: When the answers below say "...no happens-before..." what they're saying is, Supposecount==N
. Then along comes worker thread A, which setscount = N+1
. Then one whole second later, worker thread B is chosen to call therun()
method, and worker thread B looks atcount
. It is possible at that point for worker thread B to still seecount == N
.
– Solomon Slow
Apr 5 at 19:49
add a comment |
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, the object is accessing its own internal state inside of different threads (reading and incrementing). Is this code thread-safe or is it possible that we lose updates to the count
variable when it's scheduled in a different thread?
java multithreading concurrency
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, the object is accessing its own internal state inside of different threads (reading and incrementing). Is this code thread-safe or is it possible that we lose updates to the count
variable when it's scheduled in a different thread?
java multithreading concurrency
java multithreading concurrency
edited Apr 6 at 0:06
Peter Mortensen
13.9k1987113
13.9k1987113
asked Apr 5 at 19:28
RandomQuestionRandomQuestion
3,072144580
3,072144580
1
Nope; most definitely not.
– Boris the Spider
Apr 5 at 19:36
3
Just to be clear: When the answers below say "...no happens-before..." what they're saying is, Supposecount==N
. Then along comes worker thread A, which setscount = N+1
. Then one whole second later, worker thread B is chosen to call therun()
method, and worker thread B looks atcount
. It is possible at that point for worker thread B to still seecount == N
.
– Solomon Slow
Apr 5 at 19:49
add a comment |
1
Nope; most definitely not.
– Boris the Spider
Apr 5 at 19:36
3
Just to be clear: When the answers below say "...no happens-before..." what they're saying is, Supposecount==N
. Then along comes worker thread A, which setscount = N+1
. Then one whole second later, worker thread B is chosen to call therun()
method, and worker thread B looks atcount
. It is possible at that point for worker thread B to still seecount == N
.
– Solomon Slow
Apr 5 at 19:49
1
1
Nope; most definitely not.
– Boris the Spider
Apr 5 at 19:36
Nope; most definitely not.
– Boris the Spider
Apr 5 at 19:36
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
Apr 5 at 19:49
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
Apr 5 at 19:49
add a comment |
3 Answers
3
active
oldest
votes
Does an 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
orscheduleWithFixedDelay
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.
Thank you for pointing out this happens-before guarantee aboutScheduledThreadPoolExecutor
.
– RandomQuestion
Apr 5 at 23:47
add a comment |
No, this code is not thread-safe because there isn't any happens-before relation between increments made in different threads started with ScheduledExecutorService
.
To fix it, you need to either mark the variable as volatile
or switch to AtomicInteger
or AtomicLong
.
UPDATE:
As @BoristheSpider mentioned, in general in case of increment/decrement making a 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.
@BoristheSpider taking into account howscheduleWithFixedDelay
work there will be no overlapped calls tocounter++
in that particular scenario. Sovolatile
should be OK.
– Ivan
Apr 5 at 19:41
There is a happens-before relation introduced between subsequent execution of a task scheduled withscheduleWithFixedDelay
.
– Sotirios Delimanolis
Apr 5 at 20:43
How comevolatile
is not enough? The semantics ofvolatile
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
Apr 5 at 20:51
1
@EdwinDalorzo in this particular casevolatile
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
Apr 5 at 20:54
To reiterate, the code they have posted is thread-safe. This answer is wrong.
– Sotirios Delimanolis
Apr 5 at 21:55
add a comment |
No, this code is not thread-safe since there isn't any happens before relation between different threads accessing count
.
1
Even then it's not thread safe, because++
isn't atomic.
– Andy Turner
Apr 5 at 19:37
1
@michid please correct me if I am wrong but shouldn'tcounter++
be synchronized too as increment operation is not atomic.
– Yug Singh
Apr 5 at 19:37
1
Doescounter++
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
Apr 5 at 19:39
@RandomQuestion yes. Because visibility.
– Boris the Spider
Apr 5 at 19:40
1
@RandomQuestion To reiterate, the code you have posted is thread-safe. This answer is wrong.
– Sotirios Delimanolis
Apr 5 at 21:55
|
show 2 more comments
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55542189%2fdoes-an-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
Does an 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
orscheduleWithFixedDelay
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.
Thank you for pointing out this happens-before guarantee aboutScheduledThreadPoolExecutor
.
– RandomQuestion
Apr 5 at 23:47
add a comment |
Does an 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
orscheduleWithFixedDelay
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.
Thank you for pointing out this happens-before guarantee aboutScheduledThreadPoolExecutor
.
– RandomQuestion
Apr 5 at 23:47
add a comment |
Does an 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
orscheduleWithFixedDelay
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.
Does an 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
orscheduleWithFixedDelay
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.
edited Apr 6 at 0:07
Peter Mortensen
13.9k1987113
13.9k1987113
answered Apr 5 at 20:40
Sotirios DelimanolisSotirios Delimanolis
213k41504594
213k41504594
Thank you for pointing out this happens-before guarantee aboutScheduledThreadPoolExecutor
.
– RandomQuestion
Apr 5 at 23:47
add a comment |
Thank you for pointing out this happens-before guarantee aboutScheduledThreadPoolExecutor
.
– RandomQuestion
Apr 5 at 23:47
Thank you for pointing out this happens-before guarantee about
ScheduledThreadPoolExecutor
.– RandomQuestion
Apr 5 at 23:47
Thank you for pointing out this happens-before guarantee about
ScheduledThreadPoolExecutor
.– RandomQuestion
Apr 5 at 23:47
add a comment |
No, this code is not thread-safe because there isn't any happens-before relation between increments made in different threads started with ScheduledExecutorService
.
To fix it, you need to either mark the variable as volatile
or switch to AtomicInteger
or AtomicLong
.
UPDATE:
As @BoristheSpider mentioned, in general in case of increment/decrement making a 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.
@BoristheSpider taking into account howscheduleWithFixedDelay
work there will be no overlapped calls tocounter++
in that particular scenario. Sovolatile
should be OK.
– Ivan
Apr 5 at 19:41
There is a happens-before relation introduced between subsequent execution of a task scheduled withscheduleWithFixedDelay
.
– Sotirios Delimanolis
Apr 5 at 20:43
How comevolatile
is not enough? The semantics ofvolatile
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
Apr 5 at 20:51
1
@EdwinDalorzo in this particular casevolatile
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
Apr 5 at 20:54
To reiterate, the code they have posted is thread-safe. This answer is wrong.
– Sotirios Delimanolis
Apr 5 at 21:55
add a comment |
No, this code is not thread-safe because there isn't any happens-before relation between increments made in different threads started with ScheduledExecutorService
.
To fix it, you need to either mark the variable as volatile
or switch to AtomicInteger
or AtomicLong
.
UPDATE:
As @BoristheSpider mentioned, in general in case of increment/decrement making a 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.
@BoristheSpider taking into account howscheduleWithFixedDelay
work there will be no overlapped calls tocounter++
in that particular scenario. Sovolatile
should be OK.
– Ivan
Apr 5 at 19:41
There is a happens-before relation introduced between subsequent execution of a task scheduled withscheduleWithFixedDelay
.
– Sotirios Delimanolis
Apr 5 at 20:43
How comevolatile
is not enough? The semantics ofvolatile
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
Apr 5 at 20:51
1
@EdwinDalorzo in this particular casevolatile
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
Apr 5 at 20:54
To reiterate, the code they have posted is thread-safe. This answer is wrong.
– Sotirios Delimanolis
Apr 5 at 21:55
add a comment |
No, this code is not thread-safe because there isn't any happens-before relation between increments made in different threads started with ScheduledExecutorService
.
To fix it, you need to either mark the variable as volatile
or switch to AtomicInteger
or AtomicLong
.
UPDATE:
As @BoristheSpider mentioned, in general in case of increment/decrement making a 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.
No, this code is not thread-safe because there isn't any happens-before relation between increments made in different threads started with ScheduledExecutorService
.
To fix it, you need to either mark the variable as volatile
or switch to AtomicInteger
or AtomicLong
.
UPDATE:
As @BoristheSpider mentioned, in general in case of increment/decrement making a 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.
edited Apr 6 at 0:12
Peter Mortensen
13.9k1987113
13.9k1987113
answered Apr 5 at 19:37
IvanIvan
5,72411022
5,72411022
@BoristheSpider taking into account howscheduleWithFixedDelay
work there will be no overlapped calls tocounter++
in that particular scenario. Sovolatile
should be OK.
– Ivan
Apr 5 at 19:41
There is a happens-before relation introduced between subsequent execution of a task scheduled withscheduleWithFixedDelay
.
– Sotirios Delimanolis
Apr 5 at 20:43
How comevolatile
is not enough? The semantics ofvolatile
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
Apr 5 at 20:51
1
@EdwinDalorzo in this particular casevolatile
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
Apr 5 at 20:54
To reiterate, the code they have posted is thread-safe. This answer is wrong.
– Sotirios Delimanolis
Apr 5 at 21:55
add a comment |
@BoristheSpider taking into account howscheduleWithFixedDelay
work there will be no overlapped calls tocounter++
in that particular scenario. Sovolatile
should be OK.
– Ivan
Apr 5 at 19:41
There is a happens-before relation introduced between subsequent execution of a task scheduled withscheduleWithFixedDelay
.
– Sotirios Delimanolis
Apr 5 at 20:43
How comevolatile
is not enough? The semantics ofvolatile
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
Apr 5 at 20:51
1
@EdwinDalorzo in this particular casevolatile
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
Apr 5 at 20:54
To reiterate, the code they have posted is thread-safe. This answer is wrong.
– Sotirios Delimanolis
Apr 5 at 21:55
@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
Apr 5 at 19:41
@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
Apr 5 at 19:41
There is a happens-before relation introduced between subsequent execution of a task scheduled with
scheduleWithFixedDelay
.– Sotirios Delimanolis
Apr 5 at 20:43
There is a happens-before relation introduced between subsequent execution of a task scheduled with
scheduleWithFixedDelay
.– Sotirios Delimanolis
Apr 5 at 20:43
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
Apr 5 at 20:51
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
Apr 5 at 20:51
1
1
@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
Apr 5 at 20:54
@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
Apr 5 at 20:54
To reiterate, the code they have posted is thread-safe. This answer is wrong.
– Sotirios Delimanolis
Apr 5 at 21:55
To reiterate, the code they have posted is thread-safe. This answer is wrong.
– Sotirios Delimanolis
Apr 5 at 21:55
add a comment |
No, this code is not thread-safe since there isn't any happens before relation between different threads accessing count
.
1
Even then it's not thread safe, because++
isn't atomic.
– Andy Turner
Apr 5 at 19:37
1
@michid please correct me if I am wrong but shouldn'tcounter++
be synchronized too as increment operation is not atomic.
– Yug Singh
Apr 5 at 19:37
1
Doescounter++
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
Apr 5 at 19:39
@RandomQuestion yes. Because visibility.
– Boris the Spider
Apr 5 at 19:40
1
@RandomQuestion To reiterate, the code you have posted is thread-safe. This answer is wrong.
– Sotirios Delimanolis
Apr 5 at 21:55
|
show 2 more comments
No, this code is not thread-safe since there isn't any happens before relation between different threads accessing count
.
1
Even then it's not thread safe, because++
isn't atomic.
– Andy Turner
Apr 5 at 19:37
1
@michid please correct me if I am wrong but shouldn'tcounter++
be synchronized too as increment operation is not atomic.
– Yug Singh
Apr 5 at 19:37
1
Doescounter++
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
Apr 5 at 19:39
@RandomQuestion yes. Because visibility.
– Boris the Spider
Apr 5 at 19:40
1
@RandomQuestion To reiterate, the code you have posted is thread-safe. This answer is wrong.
– Sotirios Delimanolis
Apr 5 at 21:55
|
show 2 more comments
No, this code is not thread-safe since there isn't any happens before relation between different threads accessing count
.
No, this code is not thread-safe since there isn't any happens before relation between different threads accessing count
.
edited Apr 6 at 0:09
Peter Mortensen
13.9k1987113
13.9k1987113
answered Apr 5 at 19:32
michidmichid
5,54921938
5,54921938
1
Even then it's not thread safe, because++
isn't atomic.
– Andy Turner
Apr 5 at 19:37
1
@michid please correct me if I am wrong but shouldn'tcounter++
be synchronized too as increment operation is not atomic.
– Yug Singh
Apr 5 at 19:37
1
Doescounter++
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
Apr 5 at 19:39
@RandomQuestion yes. Because visibility.
– Boris the Spider
Apr 5 at 19:40
1
@RandomQuestion To reiterate, the code you have posted is thread-safe. This answer is wrong.
– Sotirios Delimanolis
Apr 5 at 21:55
|
show 2 more comments
1
Even then it's not thread safe, because++
isn't atomic.
– Andy Turner
Apr 5 at 19:37
1
@michid please correct me if I am wrong but shouldn'tcounter++
be synchronized too as increment operation is not atomic.
– Yug Singh
Apr 5 at 19:37
1
Doescounter++
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
Apr 5 at 19:39
@RandomQuestion yes. Because visibility.
– Boris the Spider
Apr 5 at 19:40
1
@RandomQuestion To reiterate, the code you have posted is thread-safe. This answer is wrong.
– Sotirios Delimanolis
Apr 5 at 21:55
1
1
Even then it's not thread safe, because
++
isn't atomic.– Andy Turner
Apr 5 at 19:37
Even then it's not thread safe, because
++
isn't atomic.– Andy Turner
Apr 5 at 19:37
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
Apr 5 at 19:37
@michid please correct me if I am wrong but shouldn't
counter++
be synchronized too as increment operation is not atomic.– Yug Singh
Apr 5 at 19:37
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
Apr 5 at 19:39
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
Apr 5 at 19:39
@RandomQuestion yes. Because visibility.
– Boris the Spider
Apr 5 at 19:40
@RandomQuestion yes. Because visibility.
– Boris the Spider
Apr 5 at 19:40
1
1
@RandomQuestion To reiterate, the code you have posted is thread-safe. This answer is wrong.
– Sotirios Delimanolis
Apr 5 at 21:55
@RandomQuestion To reiterate, the code you have posted is thread-safe. This answer is wrong.
– Sotirios Delimanolis
Apr 5 at 21:55
|
show 2 more comments
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55542189%2fdoes-an-object-always-see-its-latest-internal-state-irrespective-of-thread%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
1
Nope; most definitely not.
– Boris the Spider
Apr 5 at 19:36
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 setscount = N+1
. Then one whole second later, worker thread B is chosen to call therun()
method, and worker thread B looks atcount
. It is possible at that point for worker thread B to still seecount == N
.– Solomon Slow
Apr 5 at 19:49