Consider a statistics class in Java counting successes and failures.
public class Stat {
long successes=0, failures=0;
public success() {successes += 1;}
public failed() {failures += 1;}
public logStats() { ... read the values and log them ... }
}
The logStats()
method shall be called from another thread regularly to log the current statistics counters. This code is wrong then, because the logger thread may not see the most recent values, since nothing is synchronized or volatile or atomic.
Because I am using long
not even volatile
would suffice. And even this makes the increment more expensive than without. Assuming that counting is done in really high frequency, while the logs run only once a minute, is there a way to force the fresh values to be distributed to all threads when entering logStats()
? Would it work to make only logStats()
synchronized
. Kind of a half-sided synchronization. I know the books say don't do it. I am just trying to understand whether in this specific setting it would work and why.
In addition I should note that only one thread ever does the counting.
EDIT Please read carefully what the question is. I am not asking how to implement this differently. I am asking whether and why there is some half-sided consistency enforcement whereby the write thread does not care but the reader thread actively forces to see the most recent values. My hunch is that it may work with only one synchronize
but I cannot explain yet why or why not.