Search code examples
javamultithreadingmultidimensional-arraymutexjava.util.concurrent

Thread safe object array


I use 2-dimensional array in Java. But now, I want to use this class for multi-thread. How can I do that?

I know that how can I do a thread safe function (add synchronized keyword). What happens if clear and getItem functions are triggered at the same time? How can I do thread safe inctance for this case?

public class ThreadSafeArray {
    int ROW_MAX_COUNT = 1024;

    int rowCount = 0;
    int counterForRow = 0;
    private Object [][] objInstances = new Object[ROW_MAX_COUNT][];

    public synchronized void addItem(Object obj) {
        if(counterForRow == ROW_MAX_COUNT) {
            objInstances[++rowCount] = new Object[ROW_MAX_COUNT];
            counterForRow = 0;
        }

        objInstances[rowCount][counterForRow++] = obj;
    }

    public synchronized  void clear() {
        objInstances = new Object[ROW_MAX_COUNT][];
        rowCount = 0;
        counterForRow = 0;
    }

    public synchronized Object getItem(int index) {
        int row = index / ROW_MAX_COUNT;
        int column = index % ROW_MAX_COUNT;

        if((row <= rowCount) && (column <= counterForRow)) {
            return objInstances[row][column];
        }
        return null;
    }
}

Solution

  • IN your code, clearand getItem are instance methods. Putting synchronized on an instance method means that the thread has to acquire the lock (the "intrinsic lock") on the object instance that the method is called on before the thread can start executing any code in that method.

    Making instance methods synchronized has two effects(from java guide):

    • First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
    • Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.

    So,your class is already thread-safe for these two methods.