-1

Let's consider this piece of code:

class Foo {
  //Possibly any other immutable type
  static Instant ins = Instant.now();

  static void thread1() {
    while(true) System.out.println(ins.toString());
  }

  static void thread2() {
    while(true) ins=Instant.now();
  }
}

(Assuming thread1 and thread2 are run in different threads)

Can this result in any undefined behaviour or crash directly?

Can, at any point, have thread1 reference to invalid object? (invalid meaning incomplete or null, not "old")

Will any value from thread2 be "flushed" from the cache at some point?

Kryštof Vosyka
  • 566
  • 3
  • 15
  • 3
    [What operations in Java are considered atomic?](//stackoverflow.com/a/4756578) – 001 Jun 26 '21 at 14:39

1 Answers1

1

References cannot be undefined or invalid. They can be null. On a 32 bit system, 64 bit primitives (long and double) can experience "word tearing" where the upper 32 bits and the lower 32 bits do not agree.

Language spec on non-atomic treatment of long and double: https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.7 That same section explains that "references are always atomic."

It's not guaranteed that values will be "flushed from a cache." In the case of your code above, with such a small loop, it's possible that values will be hoisted into registers for speed, and won't be cache at all. There's no way to flush a register.

markspace
  • 10,621
  • 3
  • 25
  • 39