rohan sethi
rohan sethi

Reputation: 388

Why thread cannot update the ArrayList field?

My structure looks like :

public class ReadCSV {

    volatile List<FlightDetails> detail;


 main()  {

    ReadCSV obj=new ReadCSV();

    obj.detail=Collections.synchronizedList(new ArrayList<FlightDetails>());

    new Thread(new Runnable(){

        @Override
        public void run() {


            try {
                ...
                //pass the object along
                readAndParseFile("someFile.csv",obj);

            } catch (IOException e) {
                ...
            }

               // prints  Alright
            System.out.println(obj.detail.get(0).getDep_loc());
        }       
    }).start();

    // Throws AIOB Exception
    System.out.println(obj.detail.get(0).getArr_loc());
}

static void readAndParseFile(String csvFileName, ReadCSV obj) { 

...
..
//make changes to the object
 obj.detail.add()

// works fine

}

While passing the object without the thread, the changes are made.But the changes are not reflected even after making the field Volatile.

1) what is wrong in the above code? 2) Is it alright to follow this approach? 3) what is the general way to do such jobs?

I am very new to multi threading .

Upvotes: 0

Views: 115

Answers (2)

Horonchik
Horonchik

Reputation: 477

you need to wait till your reader thread has finished.

you can use futures or Thread.join()

Upvotes: 0

laune
laune

Reputation: 31290

If you have a Thread object that does some task and you want to see the results, wait for its termination.

 Thread p = new Thread(new Runnable(){
     //...
 });  // no start here
 p.start();  // let it run
 p.join();   // wait for its end

There is not much gain in executing another thread while the starting thread has nothing better to do than to wait for the started thread's end.

Upvotes: 1

Related Questions