maciejka
maciejka

Reputation: 948

Synchronize access to particular indexes in int array

I use the int array.

I use that method to fill indexes in array.

public void makeSelectionOfGivenNumber(int number) throws InterruptedException 
{
    if (this.table[number]!= 0) 
    {
        int multiple;
        multiple = number + number;

        while (multiple <= upperRange) 
        {
            this.table[multiple] = 0;
            multiple += number;
        }
    }
}

For example, one thread starts from 2 and eliminates all multiples, a second thread starts from 5 and makes the same activities. In some case the simultaneously the value in index 10 (in both cases are multiples). How to use in this case semaphores or other tools to lock that only one thread has access on particular index, not the whole array. I want that these two threads would work in parallel on the same table.

Upvotes: 1

Views: 201

Answers (1)

segabriel
segabriel

Reputation: 26

I think You need to create an additional array of locks (ReadWriteLock, a dimension of the array is how you want) and before each attempt to read/change in the target array to take a lock on reading or on writing the element into the array. To take the lock need to calculate an index from the required index of target array and the capacity of the additional array.

Maybe I'm not quite correctly understood the task

public class SomeTask {

    private final ReadWriteLock[] locks = locks(5);
    private int[] table;
    private int upperRange;

    public SomeTask(int[] table, int upperRange) {
        this.table = table;
        this.upperRange = upperRange;
    }

    public void makeSelectionOfGivenNumber(int number) {
        if (this.table[number] != 0) {
            int multiple;
            multiple = number + number;
            while (multiple <= upperRange) {
                ReadWriteLock lock = getLock(multiple);
                try {
                    lock.writeLock().lock();
                    this.table[multiple] = 0;
                } finally {
                    lock.writeLock().unlock();
                }
                multiple += number;
            }
        }
    }

    private ReadWriteLock getLock(int number) {
        return locks[(locks.length - 1) & number];
    }

    private ReadWriteLock[] locks(int size) {
        ReadWriteLock[] result = new ReadWriteLock[size];
        for (int i = 0; i < size; i++) {
            result[i] = new ReentrantReadWriteLock();
        }
        return result;
    }

Upvotes: 1

Related Questions