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:it.unimi.di.big.mg4j.document.WikipediaDocumentSequence.java

@Override
public DocumentIterator iterator() throws IOException {
    final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    saxParserFactory.setNamespaceAware(true);
    final MutableString nameSpaceAccumulator = new MutableString();
    final ObjectOpenHashSet<MutableString> nameSpacesAccumulator = new ObjectOpenHashSet<MutableString>();
    final ArrayBlockingQueue<DocumentFactory> freeFactories = new ArrayBlockingQueue<DocumentFactory>(16);
    for (int i = freeFactories.remainingCapacity(); i-- != 0;)
        freeFactories.add(this.factory.copy());
    final ArrayBlockingQueue<DocumentAndFactory> readyDocumentsAndFactories = new ArrayBlockingQueue<DocumentAndFactory>(
            freeFactories.size());/*from  ww  w  . jav a2s .c o  m*/

    final SAXParser parser;
    try {
        parser = saxParserFactory.newSAXParser();
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    final DefaultHandler handler = new DefaultHandler() {
        private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        private boolean inText;
        private boolean inTitle;
        private boolean inId;
        private boolean inTimestamp;
        private boolean inNamespaceDef;
        private boolean redirect;
        private MutableString text = new MutableString();
        private MutableString title = new MutableString();
        private MutableString id = new MutableString();
        private MutableString timestamp = new MutableString();
        private final Reference2ObjectMap<Enum<?>, Object> metadata = new Reference2ObjectOpenHashMap<Enum<?>, Object>();
        {
            metadata.put(PropertyBasedDocumentFactory.MetadataKeys.ENCODING, "UTF-8");
            metadata.put(MetadataKeys.REDIRECT, redirectAnchors);
        }

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
            if ("page".equals(localName)) {
                redirect = inText = inTitle = inId = inTimestamp = false;
                text.length(0);
                title.length(0);
                id.length(0);
                timestamp.length(0);
            } else if ("text".equals(localName))
                inText = true;
            else if ("title".equals(localName) && title.length() == 0)
                inTitle = true; // We catch only the first id/title elements.
            else if ("id".equals(localName) && id.length() == 0)
                inId = true;
            else if ("timestamp".equals(localName) && timestamp.length() == 0)
                inTimestamp = true;
            else if ("redirect".equals(localName)) {
                redirect = true;
                if (attributes.getValue("title") != null)
                    // Accumulate the title of the page as virtual text of the redirect page.
                    synchronized (redirectAnchors) {
                        final String link = Encoder.encodeTitleToUrl(attributes.getValue("title"), true);
                        redirectAnchors.add(
                                new AnchorExtractor.Anchor(new MutableString(baseURL.length() + link.length())
                                        .append(baseURL).append(link), title.copy()));
                    }
            } else if ("namespace".equals(localName)) {
                // Found a new namespace
                inNamespaceDef = true;
                nameSpaceAccumulator.length(0);
            }
        }

        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            if ("namespace".equals(localName)) { // Collecting a namespace
                if (nameSpaceAccumulator.length() != 0)
                    nameSpacesAccumulator.add(nameSpaceAccumulator.copy().toLowerCase());
                return;
            }

            if ("namespaces".equals(localName)) { // All namespaces collected
                nameSpaces = ImmutableSet.copyOf(nameSpacesAccumulator);
                return;
            }

            if (!redirect) {
                if ("title".equals(localName)) {
                    // Set basic metadata for the page
                    metadata.put(PropertyBasedDocumentFactory.MetadataKeys.TITLE, title.copy());
                    String link = Encoder.encodeTitleToUrl(title.toString(), true);
                    metadata.put(PropertyBasedDocumentFactory.MetadataKeys.URI,
                            new MutableString(baseURL.length() + link.length()).append(baseURL).append(link));
                    inTitle = false;
                } else if ("id".equals(localName)) {
                    metadata.put(MetadataKeys.ID, Long.valueOf(id.toString()));
                    inId = false;
                } else if ("timestamp".equals(localName)) {
                    try {
                        metadata.put(MetadataKeys.LASTEDIT, dateFormat.parse(timestamp.toString()));
                    } catch (ParseException e) {
                        throw new RuntimeException(e.getMessage(), e);
                    }
                    inTimestamp = false;
                } else if ("text".equals(localName)) {
                    inText = false;
                    if (!keepNamespaced) {
                        // Namespaces are case-insensitive and language-dependent
                        final int pos = title.indexOf(':');
                        if (pos != -1 && nameSpaces.contains(title.substring(0, pos).toLowerCase()))
                            return;
                    }
                    try {
                        final MutableString html = new MutableString();
                        DocumentFactory freeFactory;
                        try {
                            freeFactory = freeFactories.take();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e.getMessage(), e);
                        }
                        if (parseText) {
                            if (DISAMBIGUATION.search(text) != -1) { // It's a disambiguation page.
                                /* Roi's hack: duplicate links using the page title, so the generic name will end up as anchor text. */
                                final MutableString newLinks = new MutableString();
                                for (int start = 0, end; (start = BRACKETS_OPEN.search(text,
                                        start)) != -1; start = end) {
                                    end = start;
                                    final int endOfLink = text.indexOfAnyOf(END_OF_DISAMBIGUATION_LINK, start);
                                    // Note that we don't escape title because we are working at the Wikipedia raw text level.
                                    if (endOfLink != -1) {
                                        newLinks.append(text.array(), start, endOfLink - start).append('|')
                                                .append(title).append("]]\n");
                                        end = endOfLink;
                                    }
                                    end++;
                                }

                                text.append(newLinks);
                            }
                            // We separate categories by OXOXO, so we don't get overflowing phrases.
                            final MutableString category = new MutableString();
                            for (int start = 0, end; (start = CATEGORY_START.search(text,
                                    start)) != -1; start = end) {
                                end = BRACKETS_CLOSED.search(text, start += CATEGORY_START.length());
                                if (end != -1)
                                    category.append(text.subSequence(start, end)).append(" OXOXO ");
                                else
                                    break;
                            }
                            metadata.put(MetadataKeys.CATEGORY, category);

                            // Heuristics to get the first paragraph
                            metadata.put(MetadataKeys.FIRSTPAR, new MutableString());
                            String plainText = wikiModel.render(new PlainTextConverter(true), text.toString());
                            for (int start = 0; start < plainText.length(); start++) {
                                //System.err.println("Examining " + plainText.charAt( start )  );
                                if (Character.isWhitespace(plainText.charAt(start)))
                                    continue;
                                if (plainText.charAt(start) == '{') {
                                    //System.err.print( "Braces " + start + " text: \"" + plainText.subSequence( start, start + 10 )  + "\" -> " );
                                    start = BRACES_CLOSED.search(plainText, start);
                                    //System.err.println( start + " text: \"" + plainText.subSequence( start, start + 10 ) + "\"" );
                                    if (start == -1)
                                        break;
                                    start++;
                                } else if (plainText.charAt(start) == '[') {
                                    start = BRACKETS_CLOSED.search(plainText, start);
                                    if (start == -1)
                                        break;
                                    start++;
                                } else {
                                    final int end = plainText.indexOf('\n', start);
                                    if (end != -1)
                                        metadata.put(MetadataKeys.FIRSTPAR,
                                                new MutableString(plainText.substring(start, end)));
                                    break;
                                }
                            }

                            try {
                                wikiModel.render(new HTMLConverter(), text.toString(), html, false, true);
                                final Map<String, String> categories = wikiModel.getCategories();
                                // Put back category links in the page (they have been parsed by bliki and to not appear anymore in the HTML rendering)
                                for (Entry<String, String> entry : categories.entrySet()) {
                                    final String key = entry.getKey();
                                    final String value = entry.getValue().trim();
                                    if (value.length() != 0) // There are empty such things
                                        html.append("\n<a href=\"").append(baseURL).append("Category:")
                                                .append(Encoder.encodeTitleToUrl(key, true)).append("\">")
                                                .append(HtmlEscapers.htmlEscaper().escape(key))
                                                .append("</a>\n");
                                }
                            } catch (Exception e) {
                                LOGGER.error("Unexpected exception while parsing " + title, e);
                            }
                        }
                        readyDocumentsAndFactories.put(new DocumentAndFactory(
                                freeFactory.getDocument(IOUtils.toInputStream(html, Charsets.UTF_8),
                                        new Reference2ObjectOpenHashMap<Enum<?>, Object>(metadata)),
                                freeFactory));
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e.getMessage(), e);
                    } catch (IOException e) {
                        throw new RuntimeException(e.getMessage(), e);
                    }
                }
            }
        }

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            if (inText && parseText)
                text.append(ch, start, length);
            if (inTitle)
                title.append(ch, start, length);
            if (inId)
                id.append(ch, start, length);
            if (inTimestamp)
                timestamp.append(ch, start, length);
            if (inNamespaceDef) {
                nameSpaceAccumulator.append(ch, start, length);
                inNamespaceDef = false; // Dirty, but it works
            }
        }

        @Override
        public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
            if (inText && parseText)
                text.append(ch, start, length);
            if (inTitle)
                title.append(ch, start, length);
        }
    };

    final Thread parsingThread = new Thread() {
        public void run() {
            try {
                InputStream in = new FileInputStream(wikipediaXmlDump);
                if (bzipped)
                    in = new BZip2CompressorInputStream(in);
                parser.parse(
                        new InputSource(new InputStreamReader(new FastBufferedInputStream(in), Charsets.UTF_8)),
                        handler);
                readyDocumentsAndFactories.put(END);
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    };

    parsingThread.start();

    return new AbstractDocumentIterator() {
        private DocumentFactory lastFactory;

        @Override
        public Document nextDocument() throws IOException {
            try {
                final DocumentAndFactory documentAndFactory = readyDocumentsAndFactories.take();
                if (lastFactory != null)
                    freeFactories.put(lastFactory);
                if (documentAndFactory == END)
                    return null;
                lastFactory = documentAndFactory.factory;
                return documentAndFactory.document;
            } catch (InterruptedException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    };
}

From source file:org.bimserver.GeometryGenerator.java

@SuppressWarnings("unchecked")
public GenerateGeometryResult generateGeometry(long uoid, final PluginManager pluginManager,
        final DatabaseSession databaseSession, final IfcModelInterface model, final int pid, final int rid,
        final boolean store, GeometryCache geometryCache)
        throws BimserverDatabaseException, GeometryGeneratingException {
    GenerateGeometryResult generateGeometryResult = new GenerateGeometryResult();
    packageMetaData = model.getPackageMetaData();
    productClass = packageMetaData.getEClass("IfcProduct");
    productRepresentationClass = packageMetaData.getEClass("IfcProductRepresentation");
    geometryFeature = productClass.getEStructuralFeature("geometry");
    representationFeature = productClass.getEStructuralFeature("Representation");
    representationsFeature = productRepresentationClass.getEStructuralFeature("Representations");

    if (geometryCache != null && !geometryCache.isEmpty()) {
        returnCachedData(model, geometryCache, databaseSession, pid, rid);
        return null;
    }//from   ww  w  . ja va2s  .  c  om
    long start = System.nanoTime();
    String pluginName = "";
    if (model.getPackageMetaData().getSchema() == Schema.IFC4) {
        pluginName = "org.bimserver.ifc.step.serializer.Ifc4StepSerializerPlugin";
    } else if (model.getPackageMetaData().getSchema() == Schema.IFC2X3TC1) {
        pluginName = "org.bimserver.ifc.step.serializer.Ifc2x3tc1StepSerializerPlugin";
    }

    try {
        final SerializerPlugin ifcSerializerPlugin = (SerializerPlugin) pluginManager.getPlugin(pluginName,
                true);
        if (ifcSerializerPlugin == null) {
            throw new UserException("No IFC serializer found");
        }

        User user = (User) databaseSession.get(uoid, OldQuery.getDefault());
        UserSettings userSettings = user.getUserSettings();
        RenderEnginePluginConfiguration defaultRenderEngine = userSettings.getDefaultRenderEngine();
        if (defaultRenderEngine == null) {
            throw new UserException("No default render engine has been selected for this user");
        }
        final RenderEnginePlugin renderEnginePlugin = pluginManager
                .getRenderEngine(defaultRenderEngine.getPluginDescriptor().getPluginClassName(), true);
        if (renderEnginePlugin == null) {
            throw new UserException("No (enabled) render engine found of type "
                    + defaultRenderEngine.getPluginDescriptor().getPluginClassName());
        }

        int maxSimultanousThreads = Math.min(
                bimServer.getServerSettingsCache().getServerSettings().getRenderEngineProcesses(),
                Runtime.getRuntime().availableProcessors());
        if (maxSimultanousThreads < 1) {
            maxSimultanousThreads = 1;
        }

        final RenderEngineSettings settings = new RenderEngineSettings();
        settings.setPrecision(Precision.SINGLE);
        settings.setIndexFormat(IndexFormat.AUTO_DETECT);
        settings.setGenerateNormals(true);
        settings.setGenerateTriangles(true);
        settings.setGenerateWireFrame(false);

        final RenderEngineFilter renderEngineFilter = new RenderEngineFilter();

        if (maxSimultanousThreads == 1) {
            Runner runner = new Runner(null, renderEnginePlugin, databaseSession, settings, store, model,
                    ifcSerializerPlugin, model, pid, rid, null, renderEngineFilter, generateGeometryResult);
            runner.run();
        } else {
            Set<EClass> classes = new HashSet<>();
            for (IdEObject object : model.getAllWithSubTypes(packageMetaData.getEClass("IfcProduct"))) {
                IdEObject representation = (IdEObject) object.eGet(representationFeature);
                if (representation != null
                        && ((List<?>) representation.eGet(representationsFeature)).size() > 0) {
                    classes.add(object.eClass());
                }
            }

            if (classes.size() == 0) {
                return null;
            }

            classes.remove(packageMetaData.getEClass("IfcAnnotation"));
            classes.remove(packageMetaData.getEClass("IfcOpeningElement"));

            LOGGER.debug("Using " + maxSimultanousThreads + " processes for geometry generation");
            ThreadPoolExecutor executor = new ThreadPoolExecutor(maxSimultanousThreads, maxSimultanousThreads,
                    24, TimeUnit.HOURS, new ArrayBlockingQueue<Runnable>(classes.size()));

            final Map<IdEObject, IdEObject> bigMap = new HashMap<IdEObject, IdEObject>();

            HideAllInversesObjectIDM idm = new HideAllInversesObjectIDM(
                    CollectionUtils.singleSet(packageMetaData.getEPackage()),
                    pluginManager.getMetaDataManager().getPackageMetaData("ifc2x3tc1").getSchemaDefinition());
            OidProvider oidProvider = new OidProvider() {
                @Override
                public long newOid(EClass eClass) {
                    return databaseSession.newOid(eClass);
                }
            };
            for (final EClass eClass : classes) {
                final BasicIfcModel targetModel = new BasicIfcModel(
                        pluginManager.getMetaDataManager().getPackageMetaData("ifc2x3tc1"), null);
                ModelHelper modelHelper = new ModelHelper(bimServer.getMetaDataManager(), targetModel);
                modelHelper.setOidProvider(oidProvider);
                modelHelper.setObjectIDM(idm);

                IdEObject newOwnerHistory = modelHelper.copyBasicObjects(model, bigMap);

                for (IdEObject idEObject : model.getAll(eClass)) {
                    IdEObject newObject = modelHelper.copy(idEObject, false,
                            ModelHelper.createObjectIdm(idEObject.eClass()));
                    modelHelper.copyDecomposes(idEObject, newOwnerHistory);
                    bigMap.put(newObject, idEObject);
                    if (eClass.getName().equals("IfcWallStandardCase")) {
                        EStructuralFeature hasOpeningsFeature = idEObject.eClass()
                                .getEStructuralFeature("HasOpenings");
                        for (IdEObject ifcRelVoidsElement : ((List<IdEObject>) idEObject
                                .eGet(hasOpeningsFeature))) {
                            bigMap.put(modelHelper.copy(ifcRelVoidsElement, false), ifcRelVoidsElement);
                            EStructuralFeature relatedOpeningElementFeature = ifcRelVoidsElement.eClass()
                                    .getEStructuralFeature("RelatedOpeningElement");
                            IdEObject relatedOpeningElement = (IdEObject) ifcRelVoidsElement
                                    .eGet(relatedOpeningElementFeature);
                            if (relatedOpeningElement != null) {
                                bigMap.put(modelHelper.copy(relatedOpeningElement, false),
                                        relatedOpeningElement);
                            }
                        }
                    }
                }

                executor.submit(new Runner(eClass, renderEnginePlugin, databaseSession, settings, store,
                        targetModel, ifcSerializerPlugin, model, pid, rid, bigMap, renderEngineFilter,
                        generateGeometryResult));
            }
            executor.shutdown();
            executor.awaitTermination(24, TimeUnit.HOURS);
        }

        long end = System.nanoTime();
        LOGGER.info("Rendertime: " + ((end - start) / 1000000) + "ms, " + "Reused: "
                + Formatters.bytesToString(bytesSaved.get()) + ", Total: "
                + Formatters.bytesToString(totalBytes.get()) + ", Final: "
                + Formatters.bytesToString(totalBytes.get() - bytesSaved.get()));
    } catch (Exception e) {
        LOGGER.error("", e);
        throw new GeometryGeneratingException(e);
    }
    return generateGeometryResult;
}

From source file:org.alfresco.repo.transaction.RetryingTransactionHelperTest.java

@SuppressWarnings("unchecked")
private void runThreads(final RetryingTransactionHelper txnHelper, final List<Throwable> caughtExceptions,
        final Pair<Integer, Integer>... startDurationPairs) {
    ExecutorService executorService = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<Runnable>(10));

    class Work implements Runnable {
        private final CountDownLatch startLatch;
        private final long endTime;

        public Work(CountDownLatch startLatch, long endTime) {
            this.startLatch = startLatch;
            this.endTime = endTime;
        }/*from   w w  w  .j  a v  a  2s.c o m*/

        public void run() {
            try {
                txnHelper.doInTransaction(new RetryingTransactionCallback<Void>() {

                    public Void execute() throws Throwable {
                        // Signal that we've started
                        startLatch.countDown();

                        long duration = endTime - System.currentTimeMillis();
                        if (duration > 0) {
                            Thread.sleep(duration);
                        }
                        return null;
                    }
                });
            } catch (Throwable e) {
                caughtExceptions.add(e);
                // We never got a chance to signal we had started so do it now
                if (startLatch.getCount() > 0) {
                    startLatch.countDown();
                }
            }
        }
    }
    ;

    // Schedule the transactions at their required start times
    long startTime = System.currentTimeMillis();
    long currentStart = 0;
    for (Pair<Integer, Integer> pair : startDurationPairs) {
        int start = pair.getFirst();
        long now = System.currentTimeMillis();
        long then = startTime + start;
        if (then > now) {
            try {
                Thread.sleep(then - now);
            } catch (InterruptedException e) {
            }
            currentStart = start;
        }
        CountDownLatch startLatch = new CountDownLatch(1);
        Runnable work = new Work(startLatch, startTime + currentStart + pair.getSecond());
        executorService.execute(work);
        try {
            // Wait for the thread to get up and running. We need them starting in sequence
            startLatch.await(60, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
        }
    }
    // Wait for the threads to have finished
    executorService.shutdown();
    try {
        executorService.awaitTermination(60, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
    }

}

From source file:com.koda.integ.hbase.storage.FileExtStorage.java

/**
 * Initializes the queues./*from  w  w  w. j  a v a 2 s  . c  om*/
 */
private void initQueues() {
    writeQueue = new ArrayBlockingQueue<ByteBuffer>(numBuffers);
    emptyBuffersQueue = new ArrayBlockingQueue<ByteBuffer>(numBuffers);
    for (int i = 0; i < numBuffers; i++) {
        ByteBuffer buf = NativeMemory.allocateDirectBuffer(16, bufferSize);
        emptyBuffersQueue.add(buf);
    }
    try {
        activeBuffer.set(emptyBuffersQueue.take());
    } catch (InterruptedException e) {
        LOG.warn(e);
    }
}

From source file:org.lilyproject.tools.import_.cli.JsonImport.java

private void startExecutor() {
    executor = new ThreadPoolExecutor(threadCount, threadCount, 10, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(250));
    executor.setRejectedExecutionHandler(new WaitPolicy());
}

From source file:net.pms.dlna.DLNAResource.java

/**
 * First thing it does it searches for an item matching the given objectID.
 * If children is false, then it returns the found object as the only object in the list.
 * TODO: (botijo) This function does a lot more than this!
 * @param objectId ID to search for./*ww  w. j a  v a  2  s.c o m*/
 * @param returnChildren State if you want all the children in the returned list.
 * @param start
 * @param count
 * @param renderer Renderer for which to do the actions.
 * @return List of DLNAResource items.
 * @throws IOException
 */
public synchronized List<DLNAResource> getDLNAResources(String objectId, boolean returnChildren, int start,
        int count, RendererConfiguration renderer) throws IOException {
    ArrayList<DLNAResource> resources = new ArrayList<DLNAResource>();
    DLNAResource dlna = search(objectId, count, renderer);

    if (dlna != null) {
        String systemName = dlna.getSystemName();
        dlna.setDefaultRenderer(renderer);

        if (!returnChildren) {
            resources.add(dlna);
            dlna.refreshChildrenIfNeeded();
        } else {
            dlna.discoverWithRenderer(renderer, count, true);

            if (count == 0) {
                count = dlna.getChildren().size();
            }

            if (count > 0) {
                ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(count);

                int nParallelThreads = 3;
                if (dlna instanceof DVDISOFile) {
                    nParallelThreads = 1; // Some DVD drives die wih 3 parallel threads
                }

                ThreadPoolExecutor tpe = new ThreadPoolExecutor(Math.min(count, nParallelThreads), count, 20,
                        TimeUnit.SECONDS, queue);

                for (int i = start; i < start + count; i++) {
                    if (i < dlna.getChildren().size()) {
                        final DLNAResource child = dlna.getChildren().get(i);

                        if (child != null) {
                            tpe.execute(child);
                            resources.add(child);
                        } else {
                            logger.warn("null child at index {} in {}", i, systemName);
                        }
                    }
                }

                try {
                    tpe.shutdown();
                    tpe.awaitTermination(20, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    logger.error("error while shutting down thread pool executor for " + systemName, e);
                }

                logger.trace("End of analysis for {}", systemName);
            }
        }
    }

    return resources;
}

From source file:org.kurento.rabbitmq.RabbitTemplate.java

protected Message doSendAndReceiveWithTemporary(final String exchange, final String routingKey,
        final Message message) {
    return this.execute(new ChannelCallback<Message>() {

        @Override// ww  w .ja v a  2s  .c  o  m
        public Message doInRabbit(Channel channel) throws Exception {
            final ArrayBlockingQueue<Message> replyHandoff = new ArrayBlockingQueue<Message>(1);

            Assert.isNull(message.getMessageProperties().getReplyTo(),
                    "Send-and-receive methods can only be used if the Message does not already have a replyTo property.");
            DeclareOk queueDeclaration = channel.queueDeclare();
            String replyTo = queueDeclaration.getQueue();
            message.getMessageProperties().setReplyTo(replyTo);

            String consumerTag = UUID.randomUUID().toString();
            DefaultConsumer consumer = new DefaultConsumer(channel) {

                @Override
                public void handleDelivery(String consumerTag, Envelope envelope,
                        AMQP.BasicProperties properties, byte[] body) throws IOException {
                    MessageProperties messageProperties = messagePropertiesConverter
                            .toMessageProperties(properties, envelope, encoding);
                    Message reply = new Message(body, messageProperties);
                    if (logger.isTraceEnabled()) {
                        logger.trace("Message received " + reply);
                    }
                    try {
                        replyHandoff.put(reply);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
            };
            channel.basicConsume(replyTo, true, consumerTag, true, true, null, consumer);
            doSend(channel, exchange, routingKey, message, null);
            Message reply = (replyTimeout < 0) ? replyHandoff.take()
                    : replyHandoff.poll(replyTimeout, TimeUnit.MILLISECONDS);
            channel.basicCancel(consumerTag);
            return reply;
        }
    });
}

From source file:org.apache.juneau.rest.client.RestClient.java

ExecutorService getExecutorService(boolean create) {
    if (executorService != null || !create)
        return executorService;
    synchronized (this) {
        if (executorService == null)
            executorService = new ThreadPoolExecutor(1, 1, 30, TimeUnit.SECONDS,
                    new ArrayBlockingQueue<Runnable>(10));
        return executorService;
    }//w ww .j a v  a  2 s  .  com
}

From source file:la2launcher.MainFrame.java

private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
    final long initTime = new Date().getTime();
    ReentrantLock lock = new ReentrantLock();
    final String patcherUrl = "http://" + updateHost + "/hf//updater.lst.la2";//new ArrayBlockingQueue<Runnable>(10000)
    final ThreadPoolExecutor tpe = new ThreadPoolExecutor(5, 5, 1, TimeUnit.HOURS,
            new ArrayBlockingQueue<Runnable>(10000));
    filesProcessed = 0;/*w  ww.jav  a2s .  c om*/
    tpe.execute(new Runnable() {
        @Override
        public void run() {
            jTextArea2.setText("");
            DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
            jProgressBar1.setMinimum(0);
            jProgressBar1.setMaximum(model.getRowCount());
            jProgressBar1.setValue(0);
            jLabel4.setText("0/" + model.getRowCount());
            for (int i = 0; i < model.getRowCount(); i++) {
                boolean checked = (Boolean) model.getValueAt(i, 1);
                String fileName = (String) model.getValueAt(i, 0);
                if (checked) {
                    tpe.execute(new Runnable() {
                        @Override
                        public void run() {

                            final String fileUrl = "http://" + updateHost + "/hf/" + fileName.replace("\\", "/")
                                    + ".la2";
                            try {
                                printMsg("  " + fileUrl);
                                File file = new File(gamePath + fileName + ".rar");
                                File fileExt = new File(gamePath + fileName);

                                file.getParentFile().mkdirs();
                                FileOutputStream fos = new FileOutputStream(file);
                                CloseableHttpClient httpclient = HttpClients.createDefault();
                                HttpGet httpGet = new HttpGet(fileUrl);
                                CloseableHttpResponse response1 = httpclient.execute(httpGet);

                                HttpEntity entity1 = response1.getEntity();
                                copyStream(entity1.getContent(), fos, new CopyListener() {
                                    @Override
                                    public void transfered(int n) {
                                        bytesRecieved += n;
                                        bytesRecievedTotal += n;
                                    }
                                });
                                response1.close();
                                fos.close();

                                printMsg("?? : " + fileName);

                                lock.lock();
                                //fixBzip2File(file);
                                //printMsg(" ?");

                                extractArchive(file.getAbsolutePath());

                                //BZip2CompressorInputStream bz = new BZip2CompressorInputStream(new FileInputStream(file));
                                //OutputStream pout = new FileOutputStream(fileExt);
                                //copyStream(archStream, pout, null);
                                //pout.close();
                                //archStream.close();
                                //jTextArea2.setText(jTextArea2.getText() + "\r\n? : " + fileName);
                                printMsg("? : " + fileName);
                                //file.delete();

                                //                                    File tgt = new File(gamePath + fileName);
                                //                                    if (tgt.exists()) {
                                //                                        tgt.delete();
                                //                                    }
                                //tgt.getParentFile().mkdirs();
                                //Files.move(fileExt.toPath(), new File(gamePath + fileName).toPath());
                                //jTextArea2.setText(jTextArea2.getText() + "\r\n ??: " + fileName);
                                printMsg(" ??: " + fileName);
                                jProgressBar1.setIndeterminate(false);
                                jLabel4.setText((++filesProcessed) + "/" + model.getRowCount());
                                jProgressBar1.setValue((int) filesProcessed);
                                lock.unlock();
                            } catch (IOException ex) {
                                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (Exception ex) {
                                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    });
                }
            }
        }
    });

    jButton5.setEnabled(false);
    jButton6.setEnabled(false);
    jButton7.setEnabled(false);
    jButton8.setEnabled(false);
    jButton9.setEnabled(false);
    jButton10.setEnabled(false);
    jProgressBar1.setIndeterminate(true);
    new Thread() {
        @Override
        public void run() {
            do {
                long millis = new Date().getTime();
                try {
                    sleep(300);
                } catch (InterruptedException ex) {
                    Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                millis = new Date().getTime() - millis;
                BigDecimal totBig = new BigDecimal(bytesRecievedTotal / (1024 * 1024.0));
                totBig = totBig.setScale(2, BigDecimal.ROUND_CEILING);
                jLabel5.setText("?: " + (bytesRecieved / millis) + "KB/s. : "
                        + totBig + " MB");
                bytesRecieved = 0;
            } while (tpe.getActiveCount() > 0);
            tpe.shutdown();
            jButton5.setEnabled(true);
            jButton6.setEnabled(true);
            jButton7.setEnabled(true);
            jButton8.setEnabled(true);
            jButton9.setEnabled(true);
            jButton10.setEnabled(true);
            jProgressBar1.setIndeterminate(false);
            printMsg("  " + (new Date().getTime() - initTime)
                    + " ?.");
        }
    }.start();
}

From source file:jp.terasoluna.fw.file.dao.standard.AbstractFileLineIterator.java

/**
 * ???<br>//from  w  w  w .  j  a  va 2 s  .c  om
 * ?????????? ?????????<br>
 * ????????????????<br>
 * ??????????<br>
 * ??????????<br>
 * @throws FileException ???????
 */
private void buildTrailerQueue() {
    if (0 < trailerLineCount) {
        // ??
        trailerQueue = new ArrayBlockingQueue<String>(trailerLineCount);

        // ???
        for (int i = 0; i < trailerLineCount; i++) {
            if (!hasNext()) {
                throw new FileException("The data which can be acquired doesn't exist.",
                        new NoSuchElementException(), fileName);
            }
            try {
                trailerQueue.add(lineReader.readLine());
            } catch (FileException e) {
                throw new FileException("Error occurred by reading processing of a File.", e, fileName);
            }
        }
    }
}