I have the use-case, where a queue holds UploadItem(s). The queue must be thread-safe. UploadItem has a method canUpload(). UploadItems are added to the queue at the tail, but peek() and poll() must return the first UploadItem where canUpload() is true. This may be the item at the head or a newer item. Essentially, I want items to be ignored until they are ready for upload, and I want the queue to return the oldest item that's ready.
To solve the job, I have extended a ConcurrentLinkedQueue and I have overridden peek() and poll(). I have synchronized the overriden methods and I am using an iterator to retrieve the first valid item.
public class UploadQueue extends ConcurrentLinkedQueue<UploadItem> {
public UploadQueue() {}
@Override public synchronized UploadItem peek() {
for (UploadItem item : this) {
if (item.canUpload()) {
return item;
}
}
return null;
}
@Override public synchronized UploadItem poll() {
for (UploadItem item : this) {
if (item.canUpload()) {
remove(item);
return item;
}
}
return null;
}
}
Is this a good implementation or can this be done more efficient? Does using the iterator to retrieve items have any adverse effects? I can't pick items using an index and get() so it seems I must use the iterator. I can't track items in an internal variable either, because they are linked and changed by outside functions.
This will be run on Android and Android still uses Java 6. In face of Lock-Free Concurrent Linked List in Java and ConcurrentLinkedQueue$Node remains in heap after remove(), is there any risk that some Android phones may still have the Java memory leak? Does anybody know if Java is typically updated/patched on Android (within its major version)?