Skip to content

Instantly share code, notes, and snippets.

@olim7t
Created May 5, 2011 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olim7t/957409 to your computer and use it in GitHub Desktop.
Save olim7t/957409 to your computer and use it in GitHub Desktop.
ToArrayTest.java
package test;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* Illustrates a case when Collection.size() cannot reliably indicate how many elements were dumped by
* Collection.toArray().
*
* Assuming that the array is reused and was previously filled with unrelated values, the fact that toArray()
* writes null after the last element is the only way to find out how many elements were actually dumped.
*
* PS: ConcurrentLinkedQueue does not permit null elements.
*/
public class ToArrayTest {
static final ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<Integer>();
static Thread filler = new Thread() {
@Override public void run() {
try {
while (!isInterrupted()) {
queue.offer(0);
sleep(1);
}
}
catch (InterruptedException e) {} // exit
}
};
public static void main(String[] args) throws InterruptedException {
Integer[] dest = new Integer[100000];
filler.start();
Thread.sleep(1000);
int sizeBefore = 0, dumpedSize = 0;
while (sizeBefore == dumpedSize) {
sizeBefore = queue.size();
queue.toArray(dest);
dumpedSize = countUntilNull(dest);
}
filler.interrupt();
System.out.println("Size before : " + sizeBefore);
System.out.println("Dumped size : " + dumpedSize);
}
private static int countUntilNull(Integer[] array) {
int size = -1;
while (array[++size] != null);
return size;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment