I'm trying to write a "swap-list", think double buffer but for objects instead of raw bytes. Basically I'm doing this to cut down on contention, so one task can do a lot of removals while the swapped list is added to.
public class SwapList<T> {
List<T> A;
List<T> B;
volatile boolean swap;
public SwapList() {
A = Collections.synchronizedList( new ArrayList<T>());
B = Collections.synchronizedList( new ArrayList<T>());
swap = false;
}
public void swap() {
swap = !swap;
}
public List<T> getA() {
return swap ? A : B;
}
public List<T> getB() {
return swap ? B : A;
}
public int size() {
return A.size() + B.size();
}
public void clear() {
A.clear();
B.clear();
}
}
Several threads could be like this, only one of them would call swap(), and get the old A by calling getB()
// declared statically in same package
public static SwapList<String> list = new SwapList<>();
// one thread does this
int i = 1000;
while( i-- > 0 ) {
list.getA().add("A");
// another thread does this
int i = 1000;
list.swap();
while( i-- > 0 ) {
list.getB().add("B");
Both threads are started like this, but I've tried other things like, an "executor" service.
Thread b = new Thread() {
@Override
public void run() {
int i = lim; // lim is some int
list.swap(); // only the second one will call swap
while( i-- > 0 ) {
list.getB().add("B");
}
}
};
// later
a.start();
b.start();
a.join();
b.join();
System.out.println( list.getA() );
However I often get an unexpected ["A","A","A",null,"A","A",...]
Where could the null values be coming from?