From what I read, there is no "good" general solution to unit-test thread-safety. But I would like a good solution for a specific problem.
Let's consider this (dummy) dynamic list implementation. The add
method is clearly not thread-safe. Since it is pretty obvious to make it thread-safe (let us consider we will not implement any remove
method and keep it dummy), how would one unit-test the piece of code to show it is actually not thread-safe and show that the thread-safety fix actually works (or seems to work)?
public class ArrayList {
private int capacity = 2;
private Object[] content = new Object[capacity];
private int size;
public void add(Object object) {
if (size == capacity) {
ensureCapacity();
}
content[size++] = object;
}
public Object get(int index) {
if (index >= size) {
throw new IndexOutOfBoundsException();
}
return content[index];
}
private void ensureCapacity() {
int extendedCapacity = capacity * 2;
Object[] extended = new Object[extendedCapacity];
System.arraycopy(content, 0, extended, 0, size);
this.capacity = extendedCapacity;
this.content = extended;
}
}