Need Fool Proof Synchronization of ArrayList in A Multi-threaded Environment

前端 未结 4 901
闹比i
闹比i 2021-02-15 15:33

I\'ve been at this for a week now doing my research on how to properly synchronize an ArrayList.

My main issue in a nutshell is I have a \"master\" ArrayList of objects.

4条回答
  •  情话喂你
    2021-02-15 16:13

    Use CopyOnWriteArrayList, and synchronize on write operations only

    CopyOnWriteArrayList list = ...
    
    final Object writeLock = new Object();
    
    void writeOpA()
    {
        synchronized(writeLock)
        {
            read/write list
        }
    }
    void writeOpB()
    {
        synchronized(writeLock)
        {
            read/write list
        }
    }
    

    Therefore no two write sessions will overlap with each other.

    Reads require no lock. But a read session may see a changing list. If we want a read session to see a snapshot of the list, either use iterator(), or take a snapshot by toArray().


    It's probably even better if you do the copy-on-write yourselves

    volatile Foo data = new Foo(); // ArrayList in your case
    
    final Object writeLock = new Object();
    
    void writeOpA()
    {
        synchronized(writeLock)
        {
            Foo clone = data.clone();
            // read/write clone
            data = clone;
        }
    }
    void writeOpB()
    {
        // similar...
    }
    
    void readSession()
    {
        Foo snapshot = data;
        // read snapshot
    }
    

提交回复
热议问题