2

I'm reading "Effective Java" and in the chapter where he's talking about threads, I stepped into this snippet:

private static int nextSerialNumber = 0;

public static int generateSerialNumber(){
    return nextSerialNumber++;
}

A bit later, talking that snippet but in case there is no synchronization, he says:

More surprisingly, it is possible for one thread to call generateSerialNumber repeatedly, obtaining a sequence of serial numbers from zero to n, after which another thread calls generateSerialNumber and obtains a serial number of zero. Without synchronization, the second thread might see none of the updates made by the first. This is a result of the aforementioned memory model issue.

I can't understand how this is possible. For the thread to obtain "a sequence of serial numbers from zero to n", the increment must be done, otherwise the thread will read always the same value. If the increment is done, then the variable is set, because being an int, the writing is atomic. So, if the static variable is changed by a thread, although it might be the same one, another thread must be able to read that value. So how is possible that another thread, calling generateSerialNumber, can obtain a serial number of zero?

2 Answers 2

4

because being an int, the writing is atomic.

That just means it's not possible for another thread to see a half-updated value, it's either the old one or the new one (in 64-bit systems this extends to long variables).

It has nothing to do with the basic visibility problem meaning that unless your variable is volatile or you're using synchronization the value can and will be cached by different threads for performance purposes and you will see old cached values instead of up to date ones.

In addition, nextSerialNumber++; is not atomic as it consists of read-update-write steps, so making nextSerialNumber volatile won't fix this code. The method needs to be synchronized.

5
  • I got this. So the second thread is not able to read the updated version of the field because he could be reading a cached value? My assumption was that if a int is written, than that value would be available to whoever is reading that field.
    – acejazz
    Jan 2, 2018 at 10:07
  • 1
    If the second thread has a cached value and you don't explicitly tell it that it can't use the cached value, it will use it for improved performance. The updated value is available, but if the thread is under the impression that it hasn't been updated, it will use its cache because it's quicker.
    – Kayaman
    Jan 2, 2018 at 10:09
  • Great, thanks. I guess the caching mechanism is depending on the JVM implementation.
    – acejazz
    Jan 2, 2018 at 10:10
  • 1
    Not really. The JVM does have something to do with it, but in the end it's all about the low level workings of the CPU and its L1, L2, L3 caches.
    – Kayaman
    Jan 2, 2018 at 10:12
  • 1
    @acejazz The caching depends on the CPU and how its caching works, how threads are scheduled by the OS, etc. Jan 2, 2018 at 10:12
2

The current value of nextSerialNumber might be cached in a cache local to the core, and updates to that value might also be cached for a while until they are flushed to main memory. So when using multiple threads, scheduled on different cores, they might have their own local cached version of nextSerialNumber.

When not explicitly instructed, the code (and CPU) will assume it is fine to use this local cached version, and happily read and update the cached variable, while another thread scheduled on a different core will happily do the same with its own cached version.

When using concurrency primitives like synchronized and volatile, this changes. For a synchronized-block (simplified) the Java implementation will make sure those values will be retrieved from main memory when first read and written back to main memory at the end of a synchronized block, it does the same for volatile variables, but then at each read and write.

In reality things are a bit more complicated, with happens-before relations between threads, etc. But basically, your question boils down to "blame caching".

3
  • What about the cache coherency protocol that guarantees all cores will have a coherent view of data in the cache ?
    – LWimsey
    Jan 2, 2018 at 10:25
  • 1
    @LWimsey which "the"? There are multiple protocols and they tend to be a) very architecture specific and b) not something that removes the need for concurrency-aware programming on modern user-grade platforms.
    – Kayaman
    Jan 2, 2018 at 10:41
  • 2
    @LWimsey That would be a CPU detail that Java has no control over. In that case the CPU provides better guarantees than required by the Java Memory Model, and you still deal with the finicky details of happens-before relations and atomicity. The Java Memory Model in essence only promises certain visibility guarantees under certain conditions (and requires it of Java implementations), and you need to meet those conditions if you want those guarantees. In theory, a Java VM could simulate its own caching between threads by really copying values, etc, and then CPU coherency is out of the picture. Jan 2, 2018 at 10:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.