Example usage for java.util.concurrent BlockingQueue add

List of usage examples for java.util.concurrent BlockingQueue add

Introduction

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

Prototype

boolean add(E e);

Source Link

Document

Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    int capacity = 10;
    BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(capacity);

    for (int i = 0; i < 10; i++) {
        queue.add(i);
    }/*w ww  . j a v  a  2 s.c o  m*/

    System.out.println(queue.element());
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    int capacity = 10;
    BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(capacity);

    for (int i = 0; i < 10; i++) {
        queue.add(i);
    }/*  w  w w  .  ja  va 2s. c  o  m*/

    System.out.println(queue.remove(new Integer(0)));
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    int capacity = 10;
    BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(capacity);

    for (int i = 0; i < 10; i++) {
        queue.add(i);
    }//from w w w .ja  v a2 s.c  o m

    // System.out.println(queue.removeFirstOccurrence(new Integer(0)));
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    int capacity = 10;
    BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(capacity);

    for (int i = 0; i < 10; i++) {
        queue.add(i);
    }/*w  w w  .j av  a  2  s.co m*/

    System.out.println(queue.contains(0));
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    int capacity = 10;
    BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(capacity);

    for (int i = 0; i < 10; i++) {
        queue.add(i);
    }/*from w  w  w  . j a  va  2  s .  c  om*/

    //System.out.println(queue.removeLastOccurrence(new Integer(0)));
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    int capacity = 10;
    BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(capacity);

    for (int i = 0; i < 10; i++) {
        queue.add(i);
    }//from   ww w .  j av a2s . co  m
    Iterator<Integer> it = queue.iterator();
    while (it.hasNext()) {
        System.out.println(it.next());
    }
}

From source file:Test.java

public static void main(String[] args) throws InterruptedException {
    BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
    for (int i = 0; i < 10; i++) {
        final int localI = i;
        queue.add(new Runnable() {
            public void run() {
                doExpensiveOperation(localI);
            }/*from  ww  w . j av  a  2s  .  c  o  m*/
        });
    }
    ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 1000, TimeUnit.MILLISECONDS, queue);
    executor.prestartAllCoreThreads();
    executor.shutdown();
    executor.awaitTermination(100000, TimeUnit.SECONDS);
}

From source file:org.sourcepit.consul.forwarder.Main.java

public static void main(String[] args) {

    final String dockerUri = "http://192.168.56.101:2375";
    final String consulUri = "http://192.168.56.101:8500";

    final int fetchConsulStateInterval = 30;
    final int fetchDockerStateInterval = 30;
    final int dispatchItemsInterval = 2;
    final int requestDockerStateDelay = 5;

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setDefaultMaxPerRoute(10);
    final HttpClient httpClient = HttpClients.createMinimal(connManager);

    final BlockingQueue<JsonObject> queue = new LinkedBlockingQueue<>();

    final FetchConsulStateCmd fetchConsulStateCmd = new FetchConsulStateCmd(httpClient, consulUri) {
        @Override//  w ww  . j  a  va  2 s .c  om
        protected void doHandle(JsonObject consulState) {
            final JsonObject item = createItem("ConsulState", consulState);
            LOG.debug(item.toString());
            queue.add(item);
        }

    };

    final FetchDockerStateCmd fetchDockerStateCmd = new FetchDockerStateCmd(httpClient, dockerUri) {
        @Override
        protected void doHandle(JsonArray dockerState) {
            final JsonObject item = createItem("DockerState", dockerState);
            LOG.debug(item.toString());
            queue.add(item);
        }
    };

    final ConsulForwarderState forwarderState = new ConsulForwarderState();

    final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    scheduler.scheduleAtFixedRate(fetchConsulStateCmd, 0, fetchConsulStateInterval, TimeUnit.SECONDS);
    scheduler.scheduleAtFixedRate(fetchDockerStateCmd, 0, fetchDockerStateInterval, TimeUnit.SECONDS);
    scheduler.scheduleAtFixedRate(new DispatchItemsCmd(queue) {
        @Override
        protected void handleDockerState(JsonArray dockerState) {
            forwarderState.applyDockerState(dockerState);
        }

        @Override
        protected void handleDockerEvents(JsonArray dockerEvents) {
            // trigger docker state update
            scheduler.schedule(fetchDockerStateCmd, requestDockerStateDelay, TimeUnit.SECONDS);
        }

        @Override
        protected void handleConsulState(JsonObject consulState) {
            forwarderState.applyConsulState(consulState);
        }
    }, 0, dispatchItemsInterval, TimeUnit.SECONDS);

    final DockerEventObserver eventObserver = new DockerEventObserver(httpClient, dockerUri) {
        @Override
        protected void handle(JsonObject event) {
            queue.add(createItem("DockerEvent", event));
        }
    };

    final Thread eventObserverThread = new Thread(eventObserver, "Docker Event Observer") {
        @Override
        public void interrupt() {
            eventObserver.die();
            super.interrupt();
        }
    };
    eventObserverThread.start();
}

From source file:com.openteach.diamond.network.waverider.session.DefaultSession.java

public static void main(String[] args) {

    BlockingQueue<ByteBuffer> inputBuffer = new LinkedBlockingQueue<ByteBuffer>();
    /*for (int i = 0; i < 10; i++)
    {*//*from  ww  w .j  a  v a 2s  .c o  m*/
    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
    byteBuffer.put(makePacket().marshall());
    byteBuffer.put(makePacket().marshall());
    byteBuffer.flip();
    byte[] b = new byte[8];
    ByteBuffer halfBuf0 = ByteBuffer.allocate(8);
    byteBuffer.get(b);
    halfBuf0.put(b);
    halfBuf0.flip();
    inputBuffer.add(halfBuf0);
    inputBuffer.add(byteBuffer);
    /*}*/

    int size = 0;
    int oldSize = size;
    long length = Packet.getHeaderSize();
    ByteBuffer buffer = ByteBuffer.allocate(NetWorkConstants.DEFAULT_NETWORK_BUFFER_SIZE);
    ByteBuffer currentBuffer = null;

    while (size < length) {
        currentBuffer = inputBuffer.peek();
        oldSize = size;
        int position = currentBuffer.position();
        size += currentBuffer.remaining();
        buffer.put(currentBuffer);
        if (size >= Packet.getHeaderSize()) {
            length = buffer.getLong(Packet.getLengthPosition());
        }

        if (size <= length) {
            inputBuffer.remove();
        } else {
            currentBuffer.position(position);
            buffer.position(buffer.position() - currentBuffer.remaining());
            byte[] buf = new byte[(int) (length - oldSize)];
            currentBuffer.get(buf);
            buffer.put(buf);
        }
    }

    // buffer.position(0);
    buffer.flip();
    Packet packet = Packet.unmarshall(buffer);

    Command command = CommandFactory.createCommand(packet.getType(), packet.getPayLoad());

    String str = new String(command.getPayLoad().array());

    System.out.println(str);

}

From source file:com.curecomp.primefaces.migrator.PrimefacesMigration.java

public static void main(String[] args) throws Exception {
    // Let's use some colors :)
    //        AnsiConsole.systemInstall();
    CommandLineParser cliParser = new BasicParser();
    CommandLine cli = null;//ww w . j  ava2  s . c  o  m
    try {
        cli = cliParser.parse(OPTIONS, args);
    } catch (ParseException e) {
        printHelp();
    }
    if (!cli.hasOption("s")) {
        printHelp();
    }

    String sourcePattern;
    if (cli.hasOption("p")) {
        sourcePattern = cli.getOptionValue("p");
    } else {
        sourcePattern = DEFAULT_SOURCE_PATTERN;
    }

    String defaultAnswer;
    if (cli.hasOption("default-answer")) {
        defaultAnswer = cli.getOptionValue("default-answer");
    } else {
        defaultAnswer = DEFAULT_DEFAULT_PROMPT_ANSWER;
    }

    boolean defaultAnswerYes = defaultAnswer.equalsIgnoreCase("y");
    boolean quiet = cli.hasOption("q");
    boolean testWrite = cli.hasOption("t");
    Path sourceDirectory = Paths.get(cli.getOptionValue("s")).toAbsolutePath();
    // Since we use IO we will have some blocking threads hanging around
    int threadCount = Runtime.getRuntime().availableProcessors() * 2;
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(threadCount, threadCount, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>());
    BlockingQueue<WidgetVarLocation> foundUsages = new LinkedBlockingQueue<>();
    BlockingQueue<WidgetVarLocation> unusedOrAmbiguous = new LinkedBlockingQueue<>();
    BlockingQueue<WidgetVarLocation> skippedUsages = new LinkedBlockingQueue<>();
    List<Future<?>> futures = new ArrayList<>();

    findWidgetVars(sourceDirectory, sourcePattern, threadPool).forEach(widgetVarLocation -> {
        // We can't really find usages of widget vars that use EL expressions :(
        if (widgetVarLocation.widgetVar.contains("#")) {
            unusedOrAmbiguous.add(widgetVarLocation);
            return;
        }

        try {
            FileActionVisitor visitor = new FileActionVisitor(sourceDirectory, sourcePattern,
                    sourceFile -> futures.add(threadPool.submit((Callable<?>) () -> {
                        findWidgetVarUsages(sourceFile, widgetVarLocation, foundUsages, skippedUsages,
                                unusedOrAmbiguous);
                        return null;
                    })));

            Files.walkFileTree(sourceDirectory, visitor);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    });

    awaitAll(futures);

    new TreeSet<>(skippedUsages).forEach(widgetUsage -> {
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String previous = replace(widgetUsage.line, startIndex, endIndex,
                Ansi.ansi().bold().fg(Ansi.Color.RED).a(widgetUsage.widgetVar).reset().toString());
        System.out.println("Skipped " + relativePath + " at line " + widgetUsage.lineNr + " and col "
                + widgetUsage.columnNr + " for widgetVar '" + widgetUsage.widgetVar + "'");
        System.out.println("\t" + previous);
    });

    Map<WidgetVarLocation, List<WidgetVarLocation>> written = new HashMap<>();

    new TreeSet<>(foundUsages).forEach(widgetUsage -> {
        WidgetVarLocation key = new WidgetVarLocation(null, widgetUsage.location, widgetUsage.lineNr, -1, null);
        List<WidgetVarLocation> writtenList = written.get(key);
        int existing = writtenList == null ? 0 : writtenList.size();
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String next = replace(widgetUsage.line, startIndex, endIndex, Ansi.ansi().bold().fg(Ansi.Color.RED)
                .a("PF('" + widgetUsage.widgetVar + "')").reset().toString());
        System.out
                .println(relativePath + " at line " + widgetUsage.lineNr + " and col " + widgetUsage.columnNr);
        System.out.println("\t" + next);
        System.out.print("Replace (Y/N)? [" + (defaultAnswerYes ? "Y" : "N") + "]: ");

        String input;

        if (quiet) {
            input = "";
            System.out.println();
        } else {
            try {
                do {
                    input = in.readLine();
                } while (input != null && !input.isEmpty() && !"y".equalsIgnoreCase(input)
                        && !"n".equalsIgnoreCase(input));
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }

        if (input == null) {
            System.out.println("Aborted!");
        } else if (input.isEmpty() && defaultAnswerYes || !input.isEmpty() && !"n".equalsIgnoreCase(input)) {
            System.out.println("Replaced!");
            System.out.print("\t");
            if (writtenList == null) {
                writtenList = new ArrayList<>();
                written.put(key, writtenList);
            }

            writtenList.add(widgetUsage);
            List<String> lines;
            try {
                lines = Files.readAllLines(widgetUsage.location);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }

            try (OutputStream os = testWrite ? new ByteArrayOutputStream()
                    : Files.newOutputStream(widgetUsage.location);
                    PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8))) {
                String line;

                for (int i = 0; i < lines.size(); i++) {
                    int lineNr = i + 1;
                    line = lines.get(i);

                    if (lineNr == widgetUsage.lineNr) {
                        int begin = widgetUsage.columnNr + (testWrite ? 0 : existing * 6);
                        int end = begin + widgetUsage.widgetVar.length();
                        String newLine = replace(line, begin, end, "PF('" + widgetUsage.widgetVar + "')",
                                false);

                        if (testWrite) {
                            System.out.println(newLine);
                        } else {
                            pw.println(newLine);
                        }
                    } else {
                        if (!testWrite) {
                            pw.println(line);
                        }
                    }
                }
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        } else {
            System.out.println("Skipped!");
        }
    });

    new TreeSet<>(unusedOrAmbiguous).forEach(widgetUsage -> {
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String previous = replace(widgetUsage.line, startIndex, endIndex,
                Ansi.ansi().bold().fg(Ansi.Color.RED).a(widgetUsage.widgetVar).reset().toString());
        System.out.println("Skipped unused or ambiguous " + relativePath + " at line " + widgetUsage.lineNr
                + " and col " + widgetUsage.columnNr);
        System.out.println("\t" + previous);
    });

    threadPool.shutdown();
}