Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- abstract class BaseLinkedBlockingQueue<E> {
- /**
- * Linked list node class
- */
- static class Node<E> {
- E item;
- /**
- * One of: - the real successor Node - this Node, meaning the successor
- * is head.next - null, meaning there is no successor (this is the last
- * node)
- */
- Node<E> next;
- Node(E x) {
- item = x;
- }
- }
- /** Head of linked list */
- protected transient Node<E> head;
- /** Tail of linked list */
- protected transient Node<E> last;
- public BaseLinkedBlockingQueue() {
- last = head = new Node<E>(null);
- }
- /**
- * Creates a node and links it at end of queue.
- *
- * @param x
- * the item
- */
- public void enqueue(E x) {
- // assert putLock.isHeldByCurrentThread();
- last = last.next = new Node<E>(x);
- }
- /**
- * Removes a node from head of queue.
- *
- * @return the node
- */
- public abstract E dequeue();
- @Override
- public String toString() {
- if (head.next == null) {
- return "[]";
- }
- StringBuilder sb = new StringBuilder();
- sb.append('[');
- for(Node<E> node = head.next; node != null; node = node.next) {
- E e = node.item;
- sb.append(e);
- sb.append(", ");
- }
- return sb.replace(sb.length()-2, sb.length(), "]").toString();
- }
- }
- class LinkedBlockingQueueWithoutHelp<E> extends BaseLinkedBlockingQueue<E> {
- @Override
- public E dequeue() {
- // assert takeLock.isHeldByCurrentThread();
- Node<E> first = head.next;
- head.next = head; // no help for GC
- head = first;
- E x = first.item;
- first.item = null;
- return x;
- }
- }
- class OriginalLinkedBlockingQueue<E> extends BaseLinkedBlockingQueue<E> {
- @Override
- public E dequeue() {
- // assert takeLock.isHeldByCurrentThread();
- Node<E> h = head;
- Node<E> first = h.next;
- h.next = h; // help GC
- head = first;
- E x = first.item;
- first.item = null;
- return x;
- }
- }
- public class Demo {
- static class Item {
- Double x;
- Double y;
- public Item(Double x, Double y) {
- super();
- this.x = x;
- this.y = y;
- }
- @Override
- public String toString() {
- return "Item (" + x + ", " + y + ")";
- }
- }
- /**
- * @param args
- * @throws Exception
- */
- public static void main(String[] args) throws Exception {
- // BaseLinkedBlockingQueue<Item> queue = new OriginalLinkedBlockingQueue<Item>();
- BaseLinkedBlockingQueue<Item> queue = new LinkedBlockingQueueWithoutHelp<Item>();
- runWith(queue);
- // System.gc();
- System.out.println(queue);
- }
- private static void runWith(BaseLinkedBlockingQueue<Item> queue) {
- queue.enqueue(new Item(1.2, 2.2));
- queue.enqueue(new Item(0.0, 0.0));
- Item head = queue.dequeue();
- System.out.println(head);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement