Is it possible to access a shared variable with another thread without a competition problem?

Asked

Viewed 56 times

6

I have that 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 runs, since the number of repetitions can get very large. One of the solutions was to run the operation 100 times after each Getdata(), but it is not appropriate.

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

The Synchronized method with Wait() and notify() did not resolve either, as it waits for the thread to end the loop.

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

Thanks for the help !

1 answer

1

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

Try initializing the variable like this and see if it solves:

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

Regarding the use of the block synchronized, it works if you just put it inside the for and within the getData().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.