Example usage for java.util.concurrent LinkedBlockingQueue LinkedBlockingQueue

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

Introduction

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

Prototype

public LinkedBlockingQueue() 

Source Link

Document

Creates a LinkedBlockingQueue with a capacity of Integer#MAX_VALUE .

Usage

From source file:com.all.dht.database.StorageDaemon.java

public void start(MojitoDHT dht) {
    this.dht = dht;
    this.storableExecutor = Executors.newFixedThreadPool(dhtSettings.getMaxConcurrentStores(),
            new IncrementalNamedThreadFactory("DhtStorablePool"));
    this.storableQueue = new LinkedBlockingQueue<AllStorable>();
    this.failedStores = new HashMap<KUID, AtomicInteger>();
    this.process = Executors.newSingleThreadExecutor(new IncrementalNamedThreadFactory("StorageDaemonThread"));
    this.process.execute(this);
}

From source file:eu.stratosphere.nephele.services.iomanager.IOManager.java

/**
 * Creates a block channel writer that writes to the given channel. The writer writes asynchronously (write-behind),
 * accepting write request, carrying them out at some time and returning the written segment its return queue afterwards.
 * <p>/*from w w  w  . ja va 2s. c o  m*/
 * The writer will collect a specified number of write requests and carry them out
 * in one, effectively writing one block in the size of multiple memory pages.
 * Note that this means that no memory segment will reach the return queue before
 * the given number of requests are collected, so the number of buffers used with
 * the writer should be greater than the number of requests to combine. Ideally,
 * the number of memory segments used is a multiple of the number of requests to
 * combine.
 * 
 * @param channelID The descriptor for the channel to write to.
 * @param numRequestsToCombine The number of write requests to combine to one I/O request.
 * @return A block channel writer that writes to the given channel.
 * @throws IOException Thrown, if the channel for the writer could not be opened.
 */
public BlockChannelWriter createBlockChannelWriter(Channel.ID channelID, int numRequestsToCombine)
        throws IOException {
    if (this.isClosed) {
        throw new IllegalStateException("I/O-Manger is closed.");
    }

    return new BlockChannelWriter(channelID, this.writers[channelID.getThreadNum()].requestQueue,
            new LinkedBlockingQueue<MemorySegment>(), numRequestsToCombine);
}

From source file:com.all.backend.web.services.LocalPushService.java

@SuppressWarnings("unchecked")
@Override/*from  ww  w  . jav a 2  s . c o m*/
public AllMessage<?> pullMessage(ContactInfo contact) {
    long id = contact.getId();
    BlockingQueue<AllMessage<?>> queue;
    synchronized (messages) {
        queue = messages.get(id);
        if (queue == null) {
            queue = new LinkedBlockingQueue<AllMessage<?>>();
            messages.put(id, queue);
        }
    }
    AllMessage<?> poll = null;
    try {
        poll = queue.poll(1, TimeUnit.MINUTES);
    } catch (Exception e) {
        log.error(e, e);
    }
    if (poll == null) {
        synchronized (messages) {
            if (queue.isEmpty()) {
                messages.remove(id);
            }
        }
    }
    return poll;
}

From source file:com.bluepowermod.part.tube.TubeLogic.java

/**
 * This method gets the end target and heading for a TubeStack. When the tubestack's target variable is null, this is an exporting item, meaning
 * the returned target will be the TileEntity the item is going to transport to. When the tubestack's target variable is not not, the item is
 * being retrieved to this inventory. The returned target is the inventory the item came/should come from.
 *
 * @param simulate/*from  www.  j a  v a 2 s . c o m*/
 *            The only difference between simulate and not simulate is the fact that the round robin handling will be updated in non-simulate.
 * @param from
 *            The direction this item came from, this direction will never be a valid heading. Is null in normal item routing, as the from
 *            direction IS a valid output.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
private Pair<ForgeDirection, TileEntity> getHeadingForItem(TubeStack stack, boolean simulate) {

    Map<TubeNode, Integer> distances = new HashMap<TubeNode, Integer>();
    Queue<TubeNode> traversingNodes = new LinkedBlockingQueue<TubeNode>();
    Queue<ForgeDirection> trackingExportDirection = new LinkedBlockingQueue<ForgeDirection>();
    Map<TubeEdge, ForgeDirection> validDestinations = new LinkedHashMap<TubeEdge, ForgeDirection>();// using a LinkedHashMap so the order doesn't
    // change, used for round robin.

    if (getNode() != null) {
        distances.put(getNode(), 0);// make this the origin.
        traversingNodes.add(getNode());
    }

    boolean firstRun = true;
    int closestDest = 0;
    while (!traversingNodes.isEmpty()) {
        TubeNode node = traversingNodes.poll();
        if (node.edges == null)
            node.init();
        ForgeDirection heading = firstRun ? null : trackingExportDirection.poll();
        for (int i = 0; i < 6; i++) {
            if (firstRun)
                heading = ForgeDirection.getOrientation(i);
            if (node.edges != null) {
                TubeEdge edge = node.edges[i];
                if (edge != null && canPassThroughMask(stack.color, edge.colorMask)) {// if this item can travel through this color mask proceed.
                    Integer distance = distances.get(edge.target);
                    if (distance == null || distances.get(node) + edge.distance < distance) {
                        distances.put(edge.target, distances.get(node) + edge.distance);
                        if (edge.target.target instanceof PneumaticTube) {
                            traversingNodes.add(edge.target);
                            trackingExportDirection.add(heading);
                        } else if (stack.getTarget(tube.getWorld()) == null
                                && edge.isValidForExportItem(stack.stack)
                                || stack.heading == null && edge.isValidForImportItem(stack)
                                || stack.heading != null
                                        && stack.getTarget(tube.getWorld()) == edge.target.target
                                        && edge.targetConnectionSide.getOpposite() == stack
                                                .getTargetEntryDir()) {
                            validDestinations.put(edge,
                                    stack.heading == null ? edge.targetConnectionSide : heading);
                        }
                    }
                }
            }
        }

        // Check the distances of the current breadth first search layer. if no points are closer than the currently valid destination(s), we're
        // done searching.
        boolean isDoneSearching = true;
        closestDest = getClosestDestination(validDestinations.keySet(), distances);
        for (TubeNode checkingNode : traversingNodes) {
            if (distances.get(checkingNode) <= closestDest) {
                isDoneSearching = false;
                break;
            }
        }
        if (isDoneSearching)
            break;
        firstRun = false;
    }

    if (validDestinations.size() == 0) {
        if (stack.getTarget(tube.getWorld()) != null && stack.heading != null && !simulate) {
            stack.setTarget(null, ForgeDirection.UNKNOWN);// if we can't reach the retrieving target anymore, reroute as normal.
            return getHeadingForItem(stack, simulate);
        } else {
            return null;
        }
    }

    List<Pair<ForgeDirection, TileEntity>> validDirections = new ArrayList<Pair<ForgeDirection, TileEntity>>();
    for (Map.Entry<TubeEdge, ForgeDirection> entry : validDestinations.entrySet()) {
        if (distances.get(entry.getKey().target) == closestDest) {
            validDirections.add(new ImmutablePair(entry.getValue(), entry.getKey().target.target));
        }
    }

    // handle round robin
    if (!simulate)
        roundRobinCounter++;
    if (roundRobinCounter >= validDirections.size())
        roundRobinCounter = 0;
    return validDirections.get(roundRobinCounter);
}

From source file:com.amazonaws.services.kinesis.leases.impl.LeaseCoordinator.java

/**
 * Returns executor service that should be used for lease renewal.
 * @param maximumPoolSize Maximum allowed thread pool size
 * @return Executor service that should be used for lease renewal.
 *///from  w w w  .ja v  a  2  s . c  om
private static ExecutorService getLeaseRenewalExecutorService(int maximumPoolSize) {
    ThreadPoolExecutor exec = new ThreadPoolExecutor(maximumPoolSize, maximumPoolSize, 60L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(), LEASE_RENEWAL_THREAD_FACTORY);
    exec.allowCoreThreadTimeOut(true);
    return exec;
}

From source file:com.offbynull.voip.audio.gateways.io.AudioRunnable.java

private Object openDevices(Address fromAddress, Address toAddress, OpenDevicesRequest request) {
    if (outputDevices == null || inputDevices == null) {
        return new ErrorResponse("Devices not loaded");
    }//from  ww  w. j  ava2s  .  c  o  m

    if (openOutputDevice != null || openInputDevice != null) {
        return new ErrorResponse("Devices already open");
    }

    int outputId = request.getOutputId();
    int inputId = request.getInputId();

    LineEntry outputLineEntry = outputDevices.get(outputId);
    if (outputLineEntry == null) {
        LOG.error("Output device not available: {}", outputId);
        return new ErrorResponse("Output device " + outputId + " not available");
    }

    LineEntry inputLineEntry = inputDevices.get(inputId);
    if (inputLineEntry == null) {
        LOG.error("Input device not available: {}", inputId);
        return new ErrorResponse("Input device " + inputId + " not available");
    }

    // open input device
    try {
        openInputDevice = (TargetDataLine) AudioSystem.getLine(inputLineEntry.getLineInfo());
        openInputDevice.open(EXPECTED_FORMAT);
        openInputDevice.start();
    } catch (Exception e) {
        openInputDevice = null;
        LOG.error("Unable to open input device", e);
        return new ErrorResponse("Unable to open input device");
    }

    // open output device
    try {
        openOutputDevice = (SourceDataLine) AudioSystem.getLine(outputLineEntry.getLineInfo());
        openOutputDevice.open(EXPECTED_FORMAT);
        openOutputDevice.start();
    } catch (Exception e) {
        try {
            openInputDevice.close();
        } catch (Exception innerE) {
            LOG.error("Unable to close input device", innerE);
        }

        openInputDevice = null;
        openOutputDevice = null;
        LOG.error("Unable to open output device", e);
        return new ErrorResponse("Unable to open output device");
    }

    // start input read thread
    InputReadRunnable inputReadRunnable = new InputReadRunnable(openInputDevice, bus, INPUT_BUFFER_SIZE);
    inputReadThread = new Thread(inputReadRunnable);
    inputReadThread.setDaemon(true);
    inputReadThread.setName(getClass().getSimpleName() + "-" + inputReadRunnable.getClass().getSimpleName());
    inputReadThread.start();

    // start input read thread
    outputQueue = new LinkedBlockingQueue<>();
    OutputWriteRunnable outputWriteRunnable = new OutputWriteRunnable(openOutputDevice, outputQueue,
            OUTPUT_BUFFER_SIZE);
    outputWriteThread = new Thread(outputWriteRunnable);
    outputWriteThread.setDaemon(true);
    outputWriteThread
            .setName(getClass().getSimpleName() + "-" + outputWriteRunnable.getClass().getSimpleName());
    outputWriteThread.start();

    // set address to shuttle input PCM blocks to
    openedFromAddress = fromAddress;
    openedToAddress = toAddress;

    return new SuccessResponse();
}

From source file:com.microsoft.live.unittest.ApiTest.java

License:asdf

@Override
protected void setUp() throws Exception {
    super.setUp();

    // Set up the MockClient
    this.mockEntity = new MockHttpEntity();

    StatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    this.mockResponse = new MockHttpResponse(this.mockEntity, statusLine);
    this.mockClient = new MockHttpClient(this.mockResponse);
    this.loadLiveLibraryHeaderChecker();
    this.exceptionQueue = new LinkedBlockingQueue<LiveOperationException>();
    this.liveConnectClient = TestUtils.newLiveConnectClient(this.mockClient);
}

From source file:com.microsoft.live.unittest.UploadTest.java

@Override
protected void setUp() throws Exception {
    super.setUp();

    // some upload requests perform two http requests, so clear any responses that may have
    // been entered already. each test here is responsible for loading 1 or two responses.
    this.mockClient.clearHttpResponseQueue();
    this.responseQueue = new LinkedBlockingQueue<LiveOperation>();
    this.queueingListener = new UploadOperationQueueingListener(this.exceptionQueue, this.responseQueue);
}

From source file:com.ibm.iotf.devicemgmt.device.ManagedDevice.java

/**
 * <p>Send a device manage request to Watson IoT Platform</p>
 *
 * <p>A Device uses this request to become a managed device.
 * It should be the first device management request sent by the
 * Device after connecting to the IBM Watson IoT Platform.
 * It would be usual for a device management agent to send this
 * whenever is starts or restarts.</p>
 *
 * <p>This method connects the device to Watson IoT Platform connect if its not connected already</p>
 *
 * @param lifetime The length of time in seconds within
 *        which the device must send another Manage device request.
 *        if set to 0, the managed device will not become dormant.
 *        When set, the minimum supported setting is 3600 (1 hour).
 *
 * @param supportFirmwareActions Tells whether the device supports firmware actions or not.
 *        The device must add a firmware handler to handle the firmware requests.
 *
 * @param supportDeviceActions Tells whether the device supports Device actions or not.
 *        The device must add a Device action handler to handle the reboot and factory reset requests.
 *        /*  w  w w.ja  v a2  s . c  om*/
 * @param bundleIds List of Device Management Extension bundleIds
 *
 * @return boolean response containing the status of the manage request
 * @throws MqttException When there is a failure
 */
public boolean sendManageRequest(long lifetime, boolean supportFirmwareActions, boolean supportDeviceActions,
        List<String> bundleIds) throws MqttException {

    final String METHOD = "manage";

    LoggerUtility.log(Level.FINE, CLASS_NAME, METHOD, "lifetime(" + lifetime + "), " + "supportFirmwareActions("
            + supportFirmwareActions + "), " + "supportDeviceActions(" + supportDeviceActions + ")");

    boolean success = false;
    String topic = client.getDMAgentTopic().getManageTopic();

    if (!this.isConnected()) {
        this.connect();
    }

    this.supportDeviceActions = supportDeviceActions;
    this.supportFirmwareActions = supportFirmwareActions;
    this.bundleIds = bundleIds;
    JsonObject jsonPayload = new JsonObject();
    JsonObject supports = new JsonObject();
    supports.add("deviceActions", new JsonPrimitive(supportDeviceActions));
    supports.add("firmwareActions", new JsonPrimitive(supportFirmwareActions));
    if (bundleIds != null && bundleIds.size() > 0) {
        for (int i = 0; i < bundleIds.size(); i++) {
            supports.add(bundleIds.get(i), new JsonPrimitive(true));
        }
    }

    JsonObject data = new JsonObject();
    data.add("supports", supports);
    if (deviceData.getDeviceInfo() != null) {
        data.add("deviceInfo", deviceData.getDeviceInfo().toJsonObject());
    }
    if (deviceData.getMetadata() != null) {
        data.add("metadata", deviceData.getMetadata().getMetadata());
    }
    if (lifetime > 0) {
        data.add("lifetime", new JsonPrimitive(lifetime));
    }
    jsonPayload.add("d", data);

    JsonObject jsonResponse = sendAndWait(topic, jsonPayload, REGISTER_TIMEOUT_VALUE);
    if (jsonResponse != null && jsonResponse.get("rc").getAsInt() == ResponseCode.DM_SUCCESS.getCode()) {
        DMRequestHandler.setRequestHandlers(this.client);
        if (!running) {
            publishQueue = new LinkedBlockingQueue<JsonObject>();
            Thread t = new Thread(this);
            t.start();
            running = true;
        }
        /*
         * set the dormant time to a local variable, in case if the connection is
         * lost due to n/w interruption, we need to send another manage request
         * with the dormant time as the lifetime
         */
        if (lifetime > 0) {
            Date currentTime = new Date();
            dormantTime = new Date(currentTime.getTime() + (lifetime * 1000));
        }
        success = true;
    }
    LoggerUtility.log(Level.FINE, CLASS_NAME, METHOD, "Success (" + success + ")");

    bManaged = success;
    return success;
}

From source file:com.android.camera.one.v2.OneCameraZslImpl.java

/**
 * Instantiates a new camera based on Camera 2 API.
 *
 * @param device The underlying Camera 2 device.
 * @param characteristics The device's characteristics.
 * @param pictureSize the size of the final image to be taken.
 *///from w  w w .j ava2  s .c  o  m
OneCameraZslImpl(CameraDevice device, CameraCharacteristics characteristics, Size pictureSize) {
    Log.v(TAG, "Creating new OneCameraZslImpl");

    mDevice = device;
    mCharacteristics = characteristics;
    mLensRange = LensRangeCalculator.getDiopterToRatioCalculator(characteristics);
    mDirection = new CameraDirectionProvider(mCharacteristics);
    mFullSizeAspectRatio = calculateFullSizeAspectRatio(characteristics);

    mCameraThread = new HandlerThread("OneCamera2");
    // If this thread stalls, it will delay viewfinder frames.
    mCameraThread.setPriority(Thread.MAX_PRIORITY);
    mCameraThread.start();
    mCameraHandler = new Handler(mCameraThread.getLooper());

    mCameraListenerThread = new HandlerThread("OneCamera2-Listener");
    mCameraListenerThread.start();
    mCameraListenerHandler = new Handler(mCameraListenerThread.getLooper());

    // TODO: Encoding on multiple cores results in preview jank due to
    // excessive GC.
    int numEncodingCores = CameraUtil.getNumCpuCores();
    mImageSaverThreadPool = new ThreadPoolExecutor(numEncodingCores, numEncodingCores, 10, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>());

    mCaptureManager = new ImageCaptureManager(MAX_CAPTURE_IMAGES, mCameraListenerHandler,
            mImageSaverThreadPool);
    mCaptureManager.setCaptureReadyListener(new ImageCaptureManager.CaptureReadyListener() {
        @Override
        public void onReadyStateChange(boolean capturePossible) {
            mReadyStateManager.setInput(ReadyStateRequirement.CAPTURE_MANAGER_READY, capturePossible);
        }
    });

    // Listen for changes to auto focus state and dispatch to
    // mFocusStateListener.
    mCaptureManager.addMetadataChangeListener(CaptureResult.CONTROL_AF_STATE,
            new ImageCaptureManager.MetadataChangeListener() {
                @Override
                public void onImageMetadataChange(Key<?> key, Object oldValue, Object newValue,
                        CaptureResult result) {
                    FocusStateListener listener = mFocusStateListener;
                    if (listener != null) {
                        listener.onFocusStatusUpdate(AutoFocusHelper.stateFromCamera2State(
                                result.get(CaptureResult.CONTROL_AF_STATE)), result.getFrameNumber());
                    }
                }
            });

    // Allocate the image reader to store all images received from the
    // camera.
    if (pictureSize == null) {
        // TODO The default should be selected by the caller, and
        // pictureSize should never be null.
        pictureSize = getDefaultPictureSize();
    }
    mCaptureImageReader = ImageReader.newInstance(pictureSize.getWidth(), pictureSize.getHeight(),
            sCaptureImageFormat, MAX_CAPTURE_IMAGES);

    mCaptureImageReader.setOnImageAvailableListener(mCaptureManager, mCameraHandler);
    mMediaActionSound.load(MediaActionSound.SHUTTER_CLICK);
}