Is it possible to access a shared variable with another thread with no concurrency problem?

5

I have this code

List<Object> myList = new ArrayList<>();

public void RunOperation(){
    myThread = new Thread() {
        @Override
        public void run() {
            for (int i = 0; i < ReallyHighNumber; i++) {
                myList.add(SimulationStep(i));
            }
        }
    };
    myThread.start();
}

public List<Object> GetData(){
    return myList;
}

I want to return partial values while the thread executes, since the number of reps may get too large. One of the workarounds was to run the operation 100 times after each GetData (), but it is not appropriate.

I tried to use a volatile and atomic variable, but I do not know if it was a wrong use, but it continued to give competition problem when calling GetData ().

The synchronized method with wait () and notify () did not resolve either, as it expects the thread to terminate the loop.

Does anyone know which method or path to use to resolve this problem?

Thanks for the help!

    
asked by anonymous 23.12.2018 / 00:54

1 answer

0

You did not specify the concurrency problem that is happening, but I imagine it to be the simultaneous access by two threads to the myList variable.

Try to initialize the variable like this and see if it solves:

List<Object> myList = Collections.synchronizedList(new ArrayList<>());

As for the use of synchronized , it works if you only put it within for and within getData() .

    
23.12.2018 / 15:06