简体   繁体   中英

Thread safe field, avoid read write collisions

I'm trying to write synccollection and I had crashed with read/write problem

I run this code in each thread

public void run() {
    for (int j = 0; j < threadElemAmount; j++) {
        list.remove((int) (list.size() - 1));
    }
}

And code inside methods size and run

public T remove(int index){
    lock.lock();
    if (index >= size || index < 0)
        throw new IndexOutOfBoundsException("illegal index value, index = " + index + " size = " + size);
    T removedElement = (T) data[index];
    int movedElementsAmount = size - index - 1;
    //проверить кол-во перемещаемых элементов справа
    if (movedElementsAmount > 0) {
        System.arraycopy(data, index + 1, data, index, movedElementsAmount);
     }
     // очищаем последний
     data[--size] = null;
     lock.unlock();
     return removedElement;    
}

and size

public int size() {
    lock.lock();
    int result = size;
    lock.unlock();
    return result; 
}

I can't use synchronized keyword this is part of special case, just lock, it's almost the same. As a result the weakest place it's ulocked space between list.size() call and list.remove() call. How could I avoid the read/write problem?

You need to write a synchronized function for pop().

remove(index) is a poor replacement for a thread-safe pop function.

also, you should change your code to:

lock.lock()
try {
.
.
.
} finally {
    lock.unlock();
}

In order to make it exception-safe.

Last, but not least, size() doesn't need to be synchronized. Just return the size, since it's a read-only operation. You might want to make the size parameter volatile, but it's not especially necessary here.

Your options are;

  • expose the lock so it can be held during both options.
  • use synchronized with a lock which is visable.
  • add a removeLast() operation.
  • add a drainTo() operation.
  • use one of the built in thread safe collections which does this already.

It appears you want to drain N objects so the last option is likely to be best.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM