Example usage for java.util.concurrent ArrayBlockingQueue ArrayBlockingQueue

List of usage examples for java.util.concurrent ArrayBlockingQueue ArrayBlockingQueue

Introduction

In this page you can find the example usage for java.util.concurrent ArrayBlockingQueue ArrayBlockingQueue.

Prototype

public ArrayBlockingQueue(int capacity) 

Source Link

Document

Creates an ArrayBlockingQueue with the given (fixed) capacity and default access policy.

Usage

From source file:de.vandermeer.skb.interfaces.strategies.collections.queue.ArrayBlockingQueueStrategy.java

/**
 * Returns a new collection for the given collection.
 * @param capacity the queue's capacity/*from   ww  w.ja va 2  s .c  o  m*/
 * @param collection input collection
 * @return new collection
 */
default ArrayBlockingQueue<T> get(int capacity, Collection<T> collection) {
    ArrayBlockingQueue<T> ret = new ArrayBlockingQueue<T>(capacity);
    if (collection != null) {
        ret.addAll(collection);
    }
    return ret;
}

From source file:nl.salp.warcraft4j.dev.casc.dbc.DbcFilenameGenerator.java

public DbcFilenameGenerator(int maxLength, Supplier<Consumer<String>> consumer) {
    this.maxLength = maxLength;
    this.queue = new ArrayBlockingQueue<>(1_000_000);
    this.consumer = consumer;
}

From source file:org.seedstack.mqtt.internal.MqttPoolDefinition.java

public MqttPoolDefinition(Configuration configuration) {
    this.available = configuration.getBoolean(POOL_ENABLED, Boolean.TRUE);
    if (this.available) {
        int coreSize = configuration.getInt(POOL_CORE_SIZE, DEFAULT_CORE_SIZE);
        int maxSize = configuration.getInt(POOL_MAX_SIZE, DEFAULT_MAX_SIZE);
        int queueSize = configuration.getInt(POOL_QUEUE_SIZE, DEFAULT_QUEUE_SIZE);
        int keepAlive = configuration.getInt(POOL_KEEP_ALIVE, DEFAULT_KEEP_ALIVE);
        this.threadPoolExecutor = new ThreadPoolExecutor(coreSize, maxSize, keepAlive, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(queueSize));
    }//  ww w  .j  av a2 s .c o  m
}

From source file:org.programmatori.domotica.own.emulator.SCSBaseComponent.java

public SCSBaseComponent(SCSMsg msg, Bus bus) {
    super();//from   ww  w .jav a2 s . c  o m
    setDaemon(true);

    who = msg.getWho();
    what = msg.getWhat();
    where = msg.getWhere();
    property = msg.getProperty();
    value = msg.getValue();

    if (what == null)
        what = new What("0");

    setName(Config.getInstance().getWhoDescription(getWho().getMain()) + " Where: " + getWhere());
    Config.getInstance().addThread(this);

    msgOut = new ArrayBlockingQueue<SCSMsg>(1);
    this.bus = bus;
    group = -1;
}

From source file:com.aliyun.oss.common.comm.TimeoutServiceClient.java

public TimeoutServiceClient(ClientConfiguration config) {
    super(config);

    int processors = Runtime.getRuntime().availableProcessors();
    executor = new ThreadPoolExecutor(processors * 5, processors * 10, 60L, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(processors * 100), Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.CallerRunsPolicy());
    executor.allowCoreThreadTimeOut(true);
}

From source file:com.taobao.common.tfs.comm.TfsClient.java

public Object invoke(final BasePacket packet, final long timeout) throws TfsException {
    if (isDebugEnabled) {
        log.debug("send request [" + packet.getChid() + "],time is:" + System.currentTimeMillis());
    }/*from  w w  w.  jav a2s  .com*/
    ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<Object>(1);
    responses.put(packet.getChid(), queue);
    ByteBuffer bb = packet.getByteBuffer();
    bb.flip();
    byte[] data = new byte[bb.remaining()];
    bb.get(data);
    WriteFuture writeFuture = session.write(data);
    writeFuture.addListener(new IoFutureListener() {

        public void operationComplete(IoFuture future) {

            WriteFuture wfuture = (WriteFuture) future;
            if (wfuture.isWritten()) {
                return;
            }
            String error = "send message to tfs server error [" + packet.getChid() + "], tfs server: "
                    + session.getRemoteAddress() + ", maybe because this connection closed: "
                    + !session.isConnected();

            try {
                putResponse(packet.getChid(), new TfsException(error));
            } catch (TfsException e) {
                // should never happen
                log.error("put response fail", e);
            }

            // close this session
            if (session.isConnected()) {
                session.close();
            } else {
                TfsClientFactory.getInstance().removeClient(key);
            }
        }

    });

    Object response = null;
    try {
        response = queue.poll(timeout, TimeUnit.MILLISECONDS);
        if (response == null) { // timeout
            return null;
        } else if (response instanceof TfsException) {
            throw (TfsException) response;
        }
    } catch (InterruptedException e) {
        throw new TfsException("tfs client invoke error", e);
    } finally {
        responses.remove(packet.getChid());
        // For GC
        queue = null;
    }
    if (isDebugEnabled) {
        log.debug("return response [" + packet.getChid() + "],time is:" + System.currentTimeMillis());
    }

    // do decode here
    if (response instanceof BasePacket) {
        ((BasePacket) response).decode();
    }
    return response;
}

From source file:org.apache.flink.runtime.io.network.bufferprovider.GlobalBufferPool.java

public GlobalBufferPool(int numBuffers, int bufferSize) {
    this.numBuffers = numBuffers;
    this.bufferSize = bufferSize;

    buffers = new ArrayBlockingQueue<MemorySegment>(numBuffers);

    final int mb = 1 << 20;
    final int memRequiredMb = (numBuffers * bufferSize) / mb;

    for (int i = 0; i < numBuffers; i++) {
        try {//from  w w  w.  jav  a2  s  .  c  o  m
            byte[] buf = new byte[bufferSize];
            buffers.add(new MemorySegment(buf));
        } catch (OutOfMemoryError err) {
            int memAllocatedMb = ((i + 1) * bufferSize) / mb;

            String msg = String.format(
                    "Tried to allocate %d buffers of size %d bytes each (total: %d MB) "
                            + "and ran out of memory after %d buffers (%d MB).",
                    numBuffers, bufferSize, memRequiredMb, i + 1, memAllocatedMb);
            throw new OutOfMemoryError(msg);
        }
    }

    LOG.info(String.format("Allocated %d buffers of size %d bytes each (total: %d MB).", numBuffers, bufferSize,
            memRequiredMb));
}

From source file:io.fabric8.che.starter.openshift.CheDeploymentConfig.java

private void waitUntilDeploymentConfigIsAvailable(final OpenShiftClient client, String namespace) {
    final BlockingQueue<Object> queue = new ArrayBlockingQueue<Object>(1);

    final Runnable readinessPoller = new Runnable() {
        public void run() {
            try {
                if (isDeploymentAvailable(client, namespace)) {
                    queue.put(true);//w  ww  .  ja v a 2  s  .  co  m
                    return;
                } else {
                    queue.put(false);
                    return;
                }
            } catch (Throwable t) {
                try {
                    if (queue.isEmpty()) {
                        queue.put(false);
                    }
                    return;
                } catch (InterruptedException e) {
                }
            }
        }
    };

    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    ScheduledFuture<?> poller = executor.scheduleWithFixedDelay(readinessPoller, 0, 500, TimeUnit.MILLISECONDS);
    executor.schedule(new Runnable() {

        @Override
        public void run() {
            poller.cancel(true);
        }
    }, Integer.valueOf(startTimeout), TimeUnit.SECONDS);
    try {
        while (!waitUntilReady(queue)) {
        }
    } finally {
        if (!poller.isDone()) {
            poller.cancel(true);
        }
        executor.shutdown();
    }
}

From source file:eu.stratosphere.runtime.io.network.bufferprovider.GlobalBufferPool.java

public GlobalBufferPool(int numBuffers, int bufferSize) {
    this.numBuffers = numBuffers;
    this.bufferSize = bufferSize;

    this.buffers = new ArrayBlockingQueue<MemorySegment>(this.numBuffers);
    for (int i = 0; i < this.numBuffers; i++) {
        this.buffers.add(new MemorySegment(new byte[this.bufferSize]));
    }//from  w w w . ja  v a 2 s  .c o  m

    LOG.info(String.format("Initialized global buffer pool with %d buffers (%d bytes each).", this.numBuffers,
            this.bufferSize));
}

From source file:cn.clxy.upload.UploadFileService.java

private void doUpload() {

    listener.onStart(indexes != null ? indexes.size() : getPartCount());
    parts = new ArrayBlockingQueue<Part>(Config.maxRead);
    CompletionService<String> cs = new ExecutorCompletionService<String>(executor);

    cs.submit(readTask);/*from w w w  .j  a  va2s.  c om*/

    for (int i = 0; i < Config.maxUpload; i++) {
        cs.submit(new UploadTask("upload." + i));
    }

    // Wait all done. total count = maxUpload + 1.
    for (int i = 0; i <= Config.maxUpload; i++) {
        Future<String> future = null;
        try {
            future = cs.take();
            checkFuture(future);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    // Notify sever all done.
    Future<String> result = executor.submit(notifyTask);
    checkFuture(result);
    listener.onSuccess();
}