Skip to content

Instantly share code, notes, and snippets.

@juliano
Created December 16, 2011 12:38
Show Gist options
  • Save juliano/1485888 to your computer and use it in GitHub Desktop.
Save juliano/1485888 to your computer and use it in GitHub Desktop.
ArrayList Thread Safe
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public final class ArrayListThreadSafe {
private final ArrayList<Object> array;
private final AtomicInteger occupiedPositions;
private final Lock readLock;
private final Lock writeLock;
public ArrayListThreadSafe() {
array = new ArrayList<Object>();
occupiedPositions = new AtomicInteger();
ReentrantReadWriteLock rrwl = new ReentrantReadWriteLock();
readLock = rrwl.readLock();
writeLock = rrwl.writeLock();
}
public Object get(final int index, final long timeout, final TimeUnit timeUnit) {
try {
if (readLock.tryLock(timeout, timeUnit)) {
return array.get(index);
}
} catch (InterruptedException e) {
throw new IllegalStateException("unable to access the object", e);
} finally {
readLock.unlock();
}
throw new IllegalStateException("unable to access the object");
}
public void put(final int index, final Object element, final long timeout,
final TimeUnit timeUnit) {
try {
if (writeLock.tryLock(timeout, timeUnit)) {
occupiedPositions.incrementAndGet();
array.add(index, element);
}
} catch (InterruptedException e) {
throw new IllegalStateException("unable to access the object", e);
} finally {
writeLock.unlock();
}
}
public int occupiedPositions() {
return occupiedPositions.get();
}
public String toString() {
return toString(100, MILLISECONDS);
}
public String toString(final long timeout, final TimeUnit timeUnit) {
try {
if (readLock.tryLock(timeout, timeUnit)) {
return array.toString();
}
} catch (InterruptedException e) {
throw new IllegalStateException("unable to access the object", e);
} finally {
readLock.unlock();
}
throw new IllegalStateException("unable to access the object");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment