Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does creating a new Thread have a side effect of flushing the cache?

I want to know whether creating a new thread in Java triggers a cache flush. Suppose I do something like this, in this sequence:

  1. A thread runs and sets a variable X.
  2. The thread creates a new thread.
  3. The new thread accesses X.

My question is this: is the new thread, either at the time it is created or at the time it begins execution, guaranteed to see the update made to X by the old thread in step 1? I understand that if the old thread changes the value of X in the future, it is not guaranteed that the new thread will see these changes. That's fine. I just want to know whether the new thread will see the right values when it starts without need for explicit synchronization.

When I first decided to look into this topic, I thought a simple google search would immediately reveal the answer, but for some reason, I can't find any result that addresses this question.

like image 322
Gravity Avatar asked Dec 14 '11 19:12

Gravity


People also ask

Is volatile thread safe?

Therefore, the volatile keyword does not provide thread safety when non-atomic operations or composite operations are performed on shared variables. Operations like increment and decrement are composite operations.

What is thread cache in Java?

In Java, threads doesn't cache any object or variable, they just have a reference to an instance of an object. Talking about thread cache memory is more like talking about operative systems threads...


1 Answers

Yes, it is.

In java, there is 'happens-before' relation that specifies what memory effects are visible between two actions. If "A happens-before B", then action B is guaranteed to see all changes done by action A.

Starting a thread creates 'happens-before' relation between "thread.start()" call and all code that executes on new thread. New thread is therefore guaranteed to see memory effect of changing variable X on first thread.

For quick overview of happens-before relation, see Memory Visibility part of java.util.concurrent package overview. In your case, interesting bits are:

  • Each action in a thread happens-before every action in that thread that comes later in the program's order.
  • A call to start on a thread happens-before any action in the started thread.

More links if you are curious:

  • Java Memory Model is described in Chapter 17 of the Java Language Specification
  • Java Memory Model FAQ
  • Everything else about JMM
like image 145
Peter Štibraný Avatar answered Sep 18 '22 23:09

Peter Štibraný