Best way to prevent concurrency changes

Below is some pseudo code.

public class MyObject
{   
    private List<Object> someStuff;
    private Timer timer;

    public MyObject()
    {
        someStuff = new ArrayList<Object>();

        timer = new Timer(new TimerTask(){

            public void run()
            {
                for(Object o : someStuff)
                {
                    //do some more stuff involving add and removes possibly
                }
            }
        }, 0, 60*1000);
    }

    public List<Object> getSomeStuff()
    {
        return this.someStuff;
    }
}

So the problem is that other objects not listed in the code above get getSomeStuff () to get the list for read-only purposes. When this happens, I get a concurrentmodificationexception in the timer thread. I tried to make the getSomeStuff method synchronized and even tried to synchronize the blocks in the timer thread, but still kept getting an error. What is the easiest way to stop concurrent access to a list?

+3
source share
2 answers

java.util.concurrent.CopyOnWriteArrayList, ( Collection.toArray) .

, , .

:

for (Iterator<SomeClass> i = list.iterator(); i.hasNext();) {
    SomeClass next = i.next();
    if (need_to_remove){
       i.remove(i);                
    }
}

for (int i = list.size() - 1; i >= 0; i--){            
    if (need_to_remove) {
        list.remove(i);                
    }
}

, , , . :

    private final ReadWriteLock lock = new ReentrantReadWriteLock();


    final Lock w = lock.writeLock();
    w.lock();
    try {
        // modifications of the list
    } finally {
        w.unlock();
    }

      .................................

    final Lock r = lock.readLock();
    r.lock();
    try {
        // read-only operations on the list
        // e.g. copy it to an array
    } finally {
        r.unlock();
    }
    // and iterate outside the lock 

, .

+11

getSomeStuff(). , , , .

ImmutableList , , .

+3

All Articles