{@inheritDoc}

@throws QueueException.EphemeralIsFull
if the ephemeral storage is full
177887
@Override
    public IQueueMessage<ID, DATA> take() throws QueueException.EphemeralIsFull {
        try {
            GetResponse msg = getConsumerChannel().basicGet(queueName, true);
            return msg != null ? deserialize(msg.getBody()) : null;
        } catch (Exception e) {
            throw e instanceof QueueException ? (QueueException) e : new QueueException(e);
        }
    }
730119
protected function queueAllForDeletion()
    {
		if (!$this->originalFilename()) {
			return;
		}

		if (!$this->preserve_files)
		{
			$filePaths = array_map(array($this, 'path_name'), $this->styles);

			$this->queuedForDeletion = array_merge($this->queuedForDeletion, $filePaths);
		}

		$this->instanceWrite('file_name', NULL);
		$this->instanceWrite('file_size', NULL);
		$this->instanceWrite('content_type', NULL);
		$this->instanceWrite('updated_at', NULL);
    }
768608
@Override
    public java.util.concurrent.Future<GetQueueUrlResult> getQueueUrlAsync(String queueName) {

        return getQueueUrlAsync(new GetQueueUrlRequest().withQueueName(queueName));
    }
935296
private void synchronizeBucketsWithHDD() {
        int synchronizedBuckets = 0;
        // run over all buckets
        for (int i = 0; i < numberOfBuckets; i++) {
            Bucket<Data> oldBucket = bucketContainer.getBucket(i);

            // if the bucket is empty, then do nothing
            if (oldBucket.elementsInBucket == 0) {
                synchronizedBuckets++;
                continue;
            }

            /* ***** TESTING PURPOSE ****** */
            if (DynamicMemoryAllocater.INSTANCES[gp.instanceID].getFreeMemory() == 0) {
                log.info("No memory free, theoretically I must force synchronization");
            }
            /* **************************** */

            long elapsedTime = System.currentTimeMillis() - oldBucket.getCreationTime();
            // if the bucket is full, or the bucket is longer then max bucket storage time within the BucketContainer,
            // or the shutdown was initiated, then try to synchronize the buckets
            // At this point we prevent starvation of one bucket if it not filled for a long period of time.
            if (oldBucket.elementsInBucket >= gp.MIN_ELEMENT_IN_BUCKET_BEFORE_SYNC ||
                    // TODO What do we do if more than one DynamicMemoryAllocator exist???
                    DynamicMemoryAllocater.INSTANCES[gp.instanceID].getFreeMemory() == 0 ||
                    // DynamicMemoryAllocater.INSTANCE.getFreeMemory() == 0 ||
                    elapsedTime > maxBucketStorageTime ||
                    shutDownInitiated ||
                    forceInitiated) {
                if (!startNewThread(i)) {
                    sleep();
                }
            }
        }

        if (shutDownInitiated) {
            log.info("{} of {} buckets were synchronized.", synchronizedBuckets, bucketContainer.getNumberOfBuckets());
        }

        // if the queue is not full try to fill it
        if (bufferThreads.getQueue().size() < bufferThreads.getMaximumPoolSize()) {
            int bucketId = getLargestBucketId();
            if (bucketId != -1) {
                Bucket<Data> pointer = bucketContainer.getBucket(bucketId);
                boolean threadStarted = false;
                if (DynamicMemoryAllocater.INSTANCES[gp.instanceID].getFreeMemory() == 0 ||
                        pointer.elementsInBucket >= gp.MIN_ELEMENT_IN_BUCKET_BEFORE_SYNC ||
                        forceInitiated) {
                    threadStarted = startNewThread(bucketId);
                }

                if (!threadStarted) {
                    sleep();
                }
            }
        }
    }
871634
protected synchronized void flush() throws RepositoryException, MalformedQueryException, UpdateExecutionException, IOException {
        if (cache.isEmpty()) { return; }
        StringBuffer entireQuery = new StringBuffer();
        SPARQLQueryBindingSet bindingSet = new SPARQLQueryBindingSet();

        for (Namespace ns :cache.getNamespaces()){
            entireQuery.append("PREFIX "+ns.getPrefix()+": <"+ns.getName()+">. ");
        }
        entireQuery.append("DELETE DATA { ");

        Set<Resource> distinctCtx = new HashSet<Resource>();
        for (Resource context :cache.contexts()) {
            distinctCtx.add(context);
        }

        for (Resource ctx : distinctCtx) {
               if (ctx != null) {
                   entireQuery.append(" GRAPH <" + ctx + "> { ");
               }
                for (Statement stmt : cache.filter(null, null, null, ctx)) {
                    entireQuery.append("<" + stmt.getSubject().stringValue() + "> ");
                    entireQuery.append("<" + stmt.getPredicate().stringValue() + "> ");
                    Value object=stmt.getObject();
                    if (object instanceof Literal) {
                        Literal lit = (Literal) object;
                        entireQuery.append("\"");
                        entireQuery.append(SPARQLUtil.encodeString(lit.getLabel()));
                        entireQuery.append("\"");
                        if(null == lit.getLanguage()) {
                            entireQuery.append("^^<" + lit.getDatatype().stringValue() + ">");
                        }else{
                            entireQuery.append("@" + lit.getLanguage().toString());
                        }
                    } else {
                        entireQuery.append("<" + object.stringValue() + "> ");
                    }
                    entireQuery.append(".");
                }
                if (ctx != null) {
                    entireQuery.append(" }");
                }
        }

        entireQuery.append("} ");
        log.info(entireQuery.toString());
        client.sendUpdateQuery(entireQuery.toString(),bindingSet,false,null);
        lastCacheAccess = new Date();
        //log.info("success writing cache: {}",String.valueOf(cache.size()));
        cache.clear();

    }
416303
private function flushMemorySpool()
    {
        $mailerTransport = $this->mailer->getTransport();
        if (!$mailerTransport instanceof \Swift_Transport_SpoolTransport) {
            return;
        }

        $spool = $mailerTransport->getSpool();
        if (!$spool instanceof \Swift_MemorySpool) {
            return;
        }

        if (null === $this->transport) {
            throw new \Exception('No transport available to flush mail queue');
        }

        $spool->flushQueue($this->transport);
    }
819818
private boolean add(T e, boolean failWhenFull) {
        final Queue<T> queue = this.getOrCreateQueue(e);

        this.writeLock.lock();
        try {
            if (this.size == this.capacity) {
                if (failWhenFull) {
                    throw new IllegalStateException("Queue is at capacity: " + this.capacity);
                }

                return false;
            }

            final boolean added = queue.add(e);
            if (added) {
                this.size++;
                this.notEmpty.signal();
            }
            return added;
        } finally {
            this.writeLock.unlock();
        }
    }
147634
protected function getQueue()
        {
            if (null === $this->queue) {
                $this->queue = new $this->queueClass();

                if (!$this->queue instanceof SplPriorityQueue) {
                    throw new Exception(sprintf(
                        'Queue expects an internal queue of type SplPriorityQueue; received "%s"',
                        get_class($this->queue)
                    ));
                }
            }

            return $this->queue;
        }
330543
@Override
	public void put(E e) throws InterruptedException {
		if (sizeLimit > 0){
	        final ReentrantLock lock = this.sizeLimitLock;
	        lock.lockInterruptibly();
	        try {
	            try {
	                while (size() >= sizeLimit)
	                    withinSizeLimit.await();
	            } catch (InterruptedException ie) {
	            	withinSizeLimit.signal(); // propagate to non-interrupted thread
	                throw ie;
	            }
	            queue.put(e);
	        } finally {
	            lock.unlock();
	        }
		}else{
			queue.put(e);
		}
	}
558559
@Override
    public IQueueMessage<ID, DATA> take() throws QueueException.EphemeralIsFull {
        if (!isEphemeralDisabled()) {
            int ephemeralMaxSize = getEphemeralMaxSize();
            if (ephemeralMaxSize > 0 && ephemeralSize() >= ephemeralMaxSize) {
                throw new QueueException.EphemeralIsFull(ephemeralMaxSize);
            }
        }
        lockTake.lock();
        try {
            if (lastFetchedId == null) {
                itQueue.seekToFirst();
            } else {
                itQueue.seek(lastFetchedId);
            }
            if (!itQueue.isValid()) {
                return null;
            }
            lastFetchedId = itQueue.key();
            byte[] value = itQueue.value();
            IQueueMessage<ID, DATA> msg = deserialize(value);
            try {
                batchTake.delete(cfQueue, lastFetchedId);
                // batchTake.put(cfMetadata, keyLastFetchedId, lastFetchedId);
                batchTake.put(cfMetadata, keyLastFetchedIdBytes, lastFetchedId);
                if (!isEphemeralDisabled() && msg != null) {
                    byte[] _key = msg.getId().toString().getBytes(QueueUtils.UTF8);
                    batchTake.put(cfEphemeral, _key, value);
                }
                rocksDbWrapper.write(writeOptions, batchTake);
            } catch (RocksDBException e) {
                throw new QueueException(e);
            } finally {
                batchTake.clear();
            }
            itQueue.next();
            return msg;
        } finally {
            lockTake.unlock();
        }
    }
1041183
private synchronized boolean isQueueEmptyForSessionId (final short sessionId) {
     if (tc.isEntryEnabled()) SibTr.entry(this, tc, "isQueueEmptyForSessionId", "sessionId="+sessionId);

     boolean empty = true;
     final Iterator it = queue.iterator();
     while(it.hasNext()) {
       final QueueData data = (QueueData)it.next();
       final ProxyQueue pq = data.getProxyQueue();
       if (pq.getId() == sessionId) {
         if (tc.isDebugEnabled()) SibTr.debug(this, tc, "Found match: ", pq);
         empty = false;
         break;
       }
     }

     if (tc.isEntryEnabled()) SibTr.exit(this, tc, "isQueueEmptyForSessionId", Boolean.valueOf(empty));
     return empty;
   }
838399
protected function queueAllForDeletion()
    {
        if (empty($this->getAttribute('filename'))) {
            return;
        }

        // Remove old files
        if ($this->config('preserve_files', false) === false) {
            foreach ($this->styles as $name => $style) {
                $this->setQueue('deletion', $this->path($name));
            }
        }

        // Set model attributes
        $this->instanceWrite('file_name', null);
        $this->instanceWrite('file_size', null);
        $this->instanceWrite('content_type', null);
        $this->instanceWrite('updated_at', null);
        $this->instanceWrite('queue_state', self::QUEUE_DONE);
        $this->instanceWrite('queued_file', null);
    }
650982
private String recoverQueue(String queueName, QueueDeclaration queueDeclaration,
    List<Binding> queueBindings) throws Exception {
    String newQueueName = queueName;

    if (config.isQueueRecoveryEnabled()) {
      if (queueDeclaration != null) {
        newQueueName = recoverQueue(queueName, queueDeclaration);

        // Update dependencies for new queue names
        if (!queueName.equals(newQueueName)) {
          connectionHandler.queueDeclarations.remove(queueName);
          connectionHandler.queueDeclarations.put(newQueueName, queueDeclaration);
          connectionHandler.updateQueueBindingReferences(queueName, newQueueName);
        }
      }

      recoverQueueBindings(queueBindings);
    }

    return newQueueName;
  }
588939
@Override
  public void writeExternal(ObjectOutput out) throws IOException {
    super.writeExternal(out);
    // TODO: do we need to write/read the capacity?
    out.writeInt(entries.length);
    for(Entry entry : entries) {
      if(entry == null) {
        break;
      }
      entry.writeExternal(out);
    }
  }
951755
@Override
    public AbstractLessLockingUniversalSingleStorageJdbcQueue init() throws Exception {
        super.init();

        if (getMessageFactory() == null) {
            setMessageFactory(UniversalIdIntQueueMessageFactory.INSTANCE);
        }

        SQL_COUNT = MessageFormat.format(SQL_COUNT, getTableName());
        SQL_COUNT_EPHEMERAL = MessageFormat.format(SQL_COUNT_EPHEMERAL, getTableNameEphemeral());

        return this;
    }
794057
@Override
  public Page allocate(int size, boolean thief, boolean victim, OffHeapStorageArea owner) {
      while (true) {
          processQueue();
          long now = max.get();
          if (now < size) {
            return null;
          } else if (max.compareAndSet(now, now - size)) {
            ByteBuffer buffer;
            try {
              buffer = ByteBuffer.allocateDirect(size);
            } catch (OutOfMemoryError e) {
              return null;
            }
            bufferSizes.put(new PhantomReference<>(buffer, allocatedBuffers), size);
            return new Page(buffer, owner);
          }
      }
  }
934260
@Override
  public void waitForBucketEmpty(String bucketName)
      throws IOException {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(bucketName),
        "bucketName must not be null or empty");

    for (int i = 0; i < BUCKET_EMPTY_MAX_RETRIES; i++) {
      // We only need one item to see the bucket is not yet empty.
      List<String> objectNames = listObjectNames(bucketName, null, PATH_DELIMITER, 1);
      if (objectNames.isEmpty()) {
        return;
      }
      try {
        sleeper.sleep(BUCKET_EMPTY_WAIT_TIME_MS);
      } catch (InterruptedException ignored) {
        // Ignore the exception and loop.
      }
    }
    throw new IOException("Internal error: bucket not empty: " + bucketName);
  }