1
Instant instant;
void updateBy(){
   instant = Instant.now();
}

if yes, How to prove Instant is thread safe?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724

2 Answers2

6

According to the docs for Instant under the implementation notes:

This class is immutable and thread-safe.

GBlodgett
  • 12,704
  • 4
  • 31
  • 45
2

How to prove Instant is thread safe?

Analyze (using sound mathematical / formal methods) the source code to prove that it meets all of the requirements for thread safety. That is the only way to prove something is thread-safe.

You can't prove this by testing.

You can test non-thread-safe code any way you want and have the safety tests pass. But that doesn't prove anything. The tests may still fail on a different OS platform, or a different (possibly future) releases of Java.

(You can prove by testing is that something is NOT thread-safe. If the test shows undisputable symptoms of non-thread-safe behavior, that is an "existence proof".)

This should be moot for the Instant class. The javadoc specifies that the Instant class is thread-safe. Unless you have a specific reason to believe that the class is not thread-safe (which would be a genuine JVM bug) then it is advisable to not waste your time looking for things that probably don't exist.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Bit of a leap from a mistake in the javadocs to a genuine JVM bug. – shmosel Nov 21 '18 at 02:11
  • Not in this case. The javadoc is a clear, unambiguous statement that the *intention* is for `Instant` to be thread-safe. It would be laughable to claim that was a spec mistake, after 4 major releases of Java. – Stephen C Nov 21 '18 at 02:14
  • More laughable than a JVM bug? What if the class was refactored and they dropped a `final`? – shmosel Nov 21 '18 at 02:16
  • No. A JVM bug is a bug. They do happen. My point is that in this case it would be (hypothethically) laughable / intellectually dishonest for them to claim this (hypothetical situation) was a javadoc bug *rather than* a JVM bug. (Now I'm not saying that is always the case. But in **this** case ....) – Stephen C Nov 21 '18 at 02:19
  • I'm sure they happen. But it's not obvious to me that a class not behaving to spec necessarily indicates a JVM bug. – shmosel Nov 21 '18 at 02:22
  • It depends on how clear the spec is. In this case, the spec is crystal clear. Totally unambiguous. It is indisputable what the spec writer meant. (Except if you got a clever Oracle lawyer and an ignorant jury :-) ) – Stephen C Nov 21 '18 at 02:23