LockFreeQueue Example
/*
* Copyright (c) 2008 IBM Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.amino.examples;
import java.util.Queue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.amino.ds.lockfree.LockFreeQueue;
public class QueueExample {
private static final int ELEMENT_NUM = 1000;
public static void main(String[] argvs) {
ExecutorService exec = Executors.newFixedThreadPool(4);
final Queue<String> queueStr = new LockFreeQueue<String>();
Future[] results = new Future[ELEMENT_NUM];
for (int i = 0; i < ELEMENT_NUM; ++i) {
results[i] = exec.submit(new EnqueueTask(queueStr));
}
try {
for (int i = 0; i < ELEMENT_NUM; ++i) {
results[i].get();
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
exec.shutdown();
try {
exec.awaitTermination(60, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Size of queue is " + queueStr.size());
for (int i = 1; i <= ELEMENT_NUM; ++i) {
if (!queueStr.contains(i)) {
System.out.println("didn't find " + i);
}
}
}
}
class EnqueueTask implements Runnable {
private static AtomicInteger count = new AtomicInteger();
Queue queue;
public EnqueueTask(Queue q) {
queue = q;
}
public void run() {
if (!queue.offer(count.incrementAndGet())) {
System.out.println("did not insert " + count.get());
}
}
}
Back Home