"how can one break this (non?) thread safe object?" Code Answer


visibility problems can occur when a value your program has written to a variable is cached in the cpu cache and not written to ram immediately. for this reason if thread a running on cpu a is writting a value without correct synchronization and thread b reads this value from cpu b he might see a stale value in ram and not the most recent value (present only in the cpu cache of processor a).

in the example given you are using none of the mechanisms java provides to ensure safe publication. that is synchronization, volatile or final fields set in the constructor.

therefore one could imagine that in your example the reference to the create clone object becomes availabe but the values written to clones fields remains in the cpu cache. in this case other threads would not be able to read the up to date values.

to give some reference. look at this example

class finalfieldexample {
  final int x;
  int y;
  static finalfieldexample f;
  public finalfieldexample() {
    x = 3;
    y = 4;

  static void writer() {
    f = new finalfieldexample();

  static void reader() {
    if (f != null) {
      int i = f.x;
      int j = f.y;

the class above is an example of how final fields should be used. a thread executing reader is guaranteed to see the value 3 for f.x, because it is final. it is not guaranteed to see the value 4 for y, because it is not final.

the argument you are making would hold for this example as well, wouldn't it? the instance is created, fields set in the constructor etc. however it is not thread-safe, since the value written to y needs not become visible to other threads. (the cited example is from jsr 133 (java memory model) faq: http://www.cs.umd.edu/~pugh/java/memorymodel/jsr-133-faq.html#reordering)

update: you have asked for code that demonstrates the problem. i asked a similar (more open) question once: how to demonstrate java multithreading visibility problems? the interesting thing with the code sample given is, that it will behave differently with different minor versions of java, on different operating systems and wether using the client or server jvm. in that regard i found the sample quite interesting. what is important to note is, that it might well be impossible to actually create sample code that leads to a visibility problem with your code today. however next year cpu generation might implement a different caching policy and suddenly the problem appears. if you follow the guidelines of the java language specification your save.

By CoderLim on February 5 2022

Answers related to “how can one break this (non?) thread safe object?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.