Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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.apache.marmotta.platform.core.util;
 
A blocking queue implementation backed by a linked hash set for predictable iteration order and constant time addition, removal and contains operations.

Author: Sebastian Schaffert

 
 public class LinkedHashSetBlockingQueue<E> extends AbstractQueue<E> implements BlockingQueue<E> {
 
     private int capacity = .;

    
Current number of elements
 
     private final AtomicInteger count = new AtomicInteger(0);

    
Lock held by take, poll, etc
 
     private final ReentrantLock takeLock = new ReentrantLock();

    
Wait queue for waiting takes
 
     private final Condition notEmpty = .newCondition();

    
Lock held by put, offer, etc
 
     private final ReentrantLock putLock = new ReentrantLock();

    
Wait queue for waiting puts
 
     private final Condition notFull = .newCondition();
 
     private final LinkedHashSet<E> delegate;
 
     public LinkedHashSetBlockingQueue() {
          = new LinkedHashSet<E>();
     }
 
     public LinkedHashSetBlockingQueue(int capacity) {
         this. = new LinkedHashSet<E>(capacity);
         this. = capacity;
     }
 
 
     @Override
     public boolean offer(E e) {
         if (e == nullthrow new NullPointerException();
         final AtomicInteger count = this.;
         if (count.get() == )
             return false;
         int c = -1;
         final ReentrantLock putLock = this.;
         putLock.lock();
         try {
             if (count.get() < ) {
                 final boolean wasAdded = enqueue(e);
                 c = wasAdded?count.getAndIncrement():count.get();
                 if (c + 1 < )
                     .signal();
             }
         } finally {
             putLock.unlock();
         }
         if (c == 0)
             signalNotEmpty();
         return c >= 0;
     }
 
     @Override
     public void put(E ethrows InterruptedException {
         if (e == nullthrow new NullPointerException();
 
         int c = -1;
         final ReentrantLock putLock = this.;
         final AtomicInteger count = this.;
         putLock.lockInterruptibly();
         try {
            while (count.get() == ) {
                .await();
            }
            final boolean wasAdded = enqueue(e);
            c = wasAdded?count.getAndIncrement():count.get();
            if (c + 1 < )
                .signal();
        } finally {
            putLock.unlock();
        }
        if (c == 0)
            signalNotEmpty();
    }
    @Override
    public boolean offer(E elong timeoutTimeUnit unitthrows InterruptedException {
        if (e == nullthrow new NullPointerException();
        long nanos = unit.toNanos(timeout);
        int c = -1;
        final ReentrantLock putLock = this.;
        final AtomicInteger count = this.;
        putLock.lockInterruptibly();
        try {
            while (count.get() == ) {
                if (nanos <= 0)
                    return false;
                nanos = .awaitNanos(nanos);
            }
            final boolean wasAdded = enqueue(e);
            c = wasAdded?count.getAndIncrement():count.get();
            if (c + 1 < )
                .signal();
        } finally {
            putLock.unlock();
        }
        if (c == 0)
            signalNotEmpty();
        return true;
    }
    @Override
    public E take() throws InterruptedException {
        E x;
        int c = -1;
        final AtomicInteger count = this.;
        final ReentrantLock takeLock = this.;
        takeLock.lockInterruptibly();
        try {
            while (count.get() == 0) {
                .await();
            }
            x = dequeue();
            c = count.getAndDecrement();
            if (c > 1)
                .signal();
        } finally {
            takeLock.unlock();
        }
        if (c == )
            signalNotFull();
        return x;
    }
    @Override
    public E poll(long timeoutTimeUnit unitthrows InterruptedException {
        E x = null;
        int c = -1;
        long nanos = unit.toNanos(timeout);
        final AtomicInteger count = this.;
        final ReentrantLock takeLock = this.;
        takeLock.lockInterruptibly();
        try {
            while (count.get() == 0) {
                if (nanos <= 0)
                    return null;
                nanos = .awaitNanos(nanos);
            }
            x = dequeue();
            c = count.getAndDecrement();
            if (c > 1)
                .signal();
        } finally {
            takeLock.unlock();
        }
        if (c == )
            signalNotFull();
        return x;
    }
    @Override
    public int remainingCapacity() {
        return . - size();
    }
    @Override
    public int drainTo(Collection<? super E> c) {
        return drainTo(c,.);
    }
    @Override
    public int drainTo(Collection<? super E> cint maxElements) {
        if (c == null)
            throw new NullPointerException();
        if (c == this)
            throw new IllegalArgumentException();
        boolean signalNotFull = false;
        final ReentrantLock takeLock = this.;
        takeLock.lock();
        try {
            int n = Math.min(maxElements.get());
            Iterator<E> it = .iterator();
            for(int i=0; i<n && it.hasNext(); i++) {
                E x = it.next();
                c.add(x);
            }
            .getAndAdd(-n);
            return n;
        } finally {
            takeLock.unlock();
            if (signalNotFull)
                signalNotFull();
        }
    }
    @Override
    public E poll() {
        final AtomicInteger count = this.;
        if (count.get() == 0)
            return null;
        E x = null;
        int c = -1;
        final ReentrantLock takeLock = this.;
        takeLock.lock();
        try {
            if (count.get() > 0) {
                x = dequeue();
                c = count.getAndDecrement();
                if (c > 1)
                    .signal();
            }
        } finally {
            takeLock.unlock();
        }
        if (c == )
            signalNotFull();
        return x;
    }
    @Override
    public E peek() {
        if (.get() == 0)
            return null;
        final ReentrantLock takeLock = this.;
        takeLock.lock();
        try {
            Iterator<E> it = .iterator();
            if(it.hasNext()) {
                return it.next();
            } else {
                return null;
            }
        } finally {
            takeLock.unlock();
        }
    }


    
Creates a node and links it at end of queue.

Parameters:
x the item
Returns:
true if this set did not already contain x
    private boolean enqueue(E x) {
        synchronized () {
            return .add(x);
        }
    }

    
Removes a node from head of queue.

Returns:
the node
    private E dequeue() {
        synchronized () {
            Iterator<E> it = .iterator();
            E x = it.next();
            it.remove();
            return x;
        }
    }



    
Lock to prevent both puts and takes.
    void fullyLock() {
        .lock();
        .lock();
    }

    
Unlock to allow both puts and takes.
    void fullyUnlock() {
        .unlock();
        .unlock();
    }

    
Signals a waiting take. Called only from put/offer (which do not otherwise ordinarily lock takeLock.)
    private void signalNotEmpty() {
        final ReentrantLock takeLock = this.;
        takeLock.lock();
        try {
            .signal();
        } finally {
            takeLock.unlock();
        }
    }

    
Signals a waiting put. Called only from take/poll.
    private void signalNotFull() {
        final ReentrantLock putLock = this.;
        putLock.lock();
        try {
            .signal();
        } finally {
            putLock.unlock();
        }
    }

    
Tells whether both locks are held by current thread.
    boolean isFullyLocked() {
        return (.isHeldByCurrentThread() &&
                .isHeldByCurrentThread());
    }
    @Override
    public Iterator<E> iterator() {
        final Iterator<E> it = .iterator();
        return new Iterator<E>() {
            @Override
            public boolean hasNext() {
                fullyLock();
                try {
                    return it.hasNext();
                } finally {
                    fullyUnlock();
                }
            }
            @Override
            public E next() {
                fullyLock();
                try {
                    return it.next();
                } finally {
                    fullyUnlock();
                }
            }
            @Override
            public void remove() {
                fullyLock();
                try {
                    it.remove();
                    // remove counter
                    .getAndDecrement();
                } finally {
                    fullyUnlock();
                }
            }
        };
    }
    @Override
    public int size() {
        return .get();
    }
    @Override
    public boolean remove(Object o) {
        if (o == nullreturn false;
        fullyLock();
        try {
            if(.remove(o)) {
                if(.getAndDecrement() == ) {
                    .signal();
                }
                return true;
            }
        } finally {
            fullyUnlock();
        }
        return false;
    }
    @Override
    public void clear() {
        fullyLock();
        try {
            .clear();
            .set(0);
        } finally {
            fullyUnlock();
        }
    }
New to GrepCode? Check out our FAQ X