GionJh
GionJh

Reputation: 2894

Thread populating collection and Java memory model

I noticed that If I let a thread populate a collection, at the end of the thread after the join, I see the collection populated as expected.

In respect to the Java memory model, is this always guaranteed to happen ?

what if the thread is storing the references of the objects in the list in the cpu cache ?
In this case after the join the joining thread would have to guarantee to see the changes ?

final ArrayList<Person> persons = new ArrayList();
Thread myThread = new MyThread(persons);
myThread.start();
myThread.join();

// persons ?

Thread

public class MyThread extends Thread {
    
    ArrayList<Person> persons;

    public MyThread(ArrayList<Person> persons){
     this.persons = persons;
    }

    public void run(){
      persons.add(new Person(...))
      // add more
    }
  }

Upvotes: 1

Views: 71

Answers (2)

Stephen C
Stephen C

Reputation: 718758

Yes, it is guaranteed by the memory model.

  • There is a happens before between the start() call and the first action of the child thread's run() method.

  • There is a happens before between the last action (of any kind) of the child thread and the join() returning in the parent thread.

This is specified in JLS 17.4.5

These are sufficient to ensure that the child thread sees a properly initialized list and the parent thread sees a correctly populated list ... after the join().

Upvotes: 6

Johannes Kuhn
Johannes Kuhn

Reputation: 15163

From the Java Language Specification § 17.4.5

...
All actions in a thread happen-before any other thread successfully returns from a join() on that thread.
...

Upvotes: 4

Related Questions