TransWikia.com

Thread populating collection and Java memory model

Stack Overflow Asked by GionJh on November 4, 2021

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
    }
  }

2 Answers

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.
...

Answered by Johannes Kuhn on November 4, 2021

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().

Answered by Stephen C on November 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP