Example usage for java.util.concurrent ConcurrentLinkedQueue add

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

Introduction

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

Prototype

public boolean add(E e) 

Source Link

Document

Inserts the specified element at the tail of this queue.

Usage

From source file:io.covert.dns.collection.ResolverThread.java

public static void main(String[] args) throws Exception {

    ConcurrentLinkedQueue<DnsRequest> inQueue = new ConcurrentLinkedQueue<DnsRequest>();
    AtomicLong inQueueSize = new AtomicLong(0);
    ConcurrentLinkedQueue<Pair<Record, Message>> outQueue = new ConcurrentLinkedQueue<Pair<Record, Message>>();
    String[] nameservers = new String[] { "8.8.8.8" };

    inQueue.add(new DnsRequest("www6.google.com.", Type.AAAA, DClass.IN));
    inQueue.add(new DnsRequest("ipv6.google.com.", Type.AAAA, DClass.IN));
    inQueue.add(new DnsRequest("gmail.com.", Type.AAAA, DClass.IN));
    inQueueSize.incrementAndGet();/*w w w.  ja va 2 s  . c o  m*/
    inQueueSize.incrementAndGet();
    inQueueSize.incrementAndGet();

    ResolverThread res = new ResolverThread(inQueue, inQueueSize, outQueue, nameservers, 5);
    res.start();
    res.stopRunning();
    res.join();

    Pair<Record, Message> result = outQueue.remove();
    System.out.println(result);

    result = outQueue.remove();
    System.out.println(result);

    result = outQueue.remove();
    System.out.println(result);
}

From source file:playground.johannes.socialnets.SpatialNetworkGenerator.java

/**
 * @param args/*from w ww.j  a v  a 2s. co m*/
 * @throws InterruptedException 
 * @throws IOException 
 * @throws FileNotFoundException 
 */
public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException {
    Config config = Gbl.createConfig(args);

    alpha1 = Double.parseDouble(config.getParam("socialnets", "alpha1"));
    alpha2 = Double.parseDouble(config.getParam("socialnets", "alpha2"));
    gamma = Double.parseDouble(config.getParam("socialnets", "gamma"));
    logger.info(String.format("Parameters are: alpha1=%1$s, alpha2=%2$s, gamma=%3$s", alpha1, alpha2, gamma));

    logger.info("Loading network and plans...");
    ScenarioData data = new ScenarioData(config);
    final NetworkLayer network = data.getNetwork();
    final Population population = data.getPopulation();

    logger.info("Creating egos...");
    SocialNetwork socialNet = new SocialNetwork();
    ConcurrentLinkedQueue<Ego> egos = new ConcurrentLinkedQueue<Ego>();
    for (Person person : population) {
        egos.add(socialNet.addEgo(person));
    }

    logger.info("Initializing threads step 1...");
    double scale = 1;//Double.parseDouble(args[1]);
    InternalThread.totalEgos = egos.size();
    int count = 1;//Runtime.getRuntime().availableProcessors();
    InternalThread[] threads = new InternalThread[count];
    for (int i = 0; i < count; i++) {
        threads[i] = new InternalThread(network, socialNet, egos, scale, i);
    }
    for (Thread thread : threads) {
        thread.start();
    }
    for (Thread thread : threads) {
        thread.join();
    }

    dumpStats(socialNet, args[1], 0);

    for (int k = 0; k < 0; k++) {
        logger.info("Initializing threads setp " + (k + 2) + "...");

        Step2Thread.totalEgos = socialNet.getVertices().size();
        Step2Thread[] threads2 = new Step2Thread[count];
        for (int i = 0; i < count; i++) {
            threads2[i] = new Step2Thread(socialNet, new Random(i * (k + 1)));
        }
        for (Thread thread : threads2) {
            thread.start();
        }
        for (Thread thread : threads2) {
            thread.join();
        }

        dumpStats(socialNet, args[1], k + 1);
    }
}

From source file:com.ibm.crail.storage.StorageServer.java

public static void main(String[] args) throws Exception {
    Logger LOG = CrailUtils.getLogger();
    CrailConfiguration conf = new CrailConfiguration();
    CrailConstants.updateConstants(conf);
    CrailConstants.printConf();/* w  w w . ja va 2s  .c om*/
    CrailConstants.verify();

    int splitIndex = 0;
    for (String param : args) {
        if (param.equalsIgnoreCase("--")) {
            break;
        }
        splitIndex++;
    }

    //default values
    StringTokenizer tokenizer = new StringTokenizer(CrailConstants.STORAGE_TYPES, ",");
    if (!tokenizer.hasMoreTokens()) {
        throw new Exception("No storage types defined!");
    }
    String storageName = tokenizer.nextToken();
    int storageType = 0;
    HashMap<String, Integer> storageTypes = new HashMap<String, Integer>();
    storageTypes.put(storageName, storageType);
    for (int type = 1; tokenizer.hasMoreElements(); type++) {
        String name = tokenizer.nextToken();
        storageTypes.put(name, type);
    }
    int storageClass = -1;

    //custom values
    if (args != null) {
        Option typeOption = Option.builder("t").desc("storage type to start").hasArg().build();
        Option classOption = Option.builder("c").desc("storage class the server will attach to").hasArg()
                .build();
        Options options = new Options();
        options.addOption(typeOption);
        options.addOption(classOption);
        CommandLineParser parser = new DefaultParser();

        try {
            CommandLine line = parser.parse(options, Arrays.copyOfRange(args, 0, splitIndex));
            if (line.hasOption(typeOption.getOpt())) {
                storageName = line.getOptionValue(typeOption.getOpt());
                storageType = storageTypes.get(storageName).intValue();
            }
            if (line.hasOption(classOption.getOpt())) {
                storageClass = Integer.parseInt(line.getOptionValue(classOption.getOpt()));
            }
        } catch (ParseException e) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Storage tier", options);
            System.exit(-1);
        }
    }
    if (storageClass < 0) {
        storageClass = storageType;
    }

    StorageTier storageTier = StorageTier.createInstance(storageName);
    if (storageTier == null) {
        throw new Exception("Cannot instantiate datanode of type " + storageName);
    }

    String extraParams[] = null;
    splitIndex++;
    if (args.length > splitIndex) {
        extraParams = new String[args.length - splitIndex];
        for (int i = splitIndex; i < args.length; i++) {
            extraParams[i - splitIndex] = args[i];
        }
    }
    storageTier.init(conf, extraParams);
    storageTier.printConf(LOG);

    RpcClient rpcClient = RpcClient.createInstance(CrailConstants.NAMENODE_RPC_TYPE);
    rpcClient.init(conf, args);
    rpcClient.printConf(LOG);

    ConcurrentLinkedQueue<InetSocketAddress> namenodeList = CrailUtils.getNameNodeList();
    ConcurrentLinkedQueue<RpcConnection> connectionList = new ConcurrentLinkedQueue<RpcConnection>();
    while (!namenodeList.isEmpty()) {
        InetSocketAddress address = namenodeList.poll();
        RpcConnection connection = rpcClient.connect(address);
        connectionList.add(connection);
    }
    RpcConnection rpcConnection = connectionList.peek();
    if (connectionList.size() > 1) {
        rpcConnection = new RpcDispatcher(connectionList);
    }
    LOG.info("connected to namenode(s) " + rpcConnection.toString());

    StorageServer server = storageTier.launchServer();
    StorageRpcClient storageRpc = new StorageRpcClient(storageType, CrailStorageClass.get(storageClass),
            server.getAddress(), rpcConnection);

    HashMap<Long, Long> blockCount = new HashMap<Long, Long>();
    long sumCount = 0;
    while (server.isAlive()) {
        StorageResource resource = server.allocateResource();
        if (resource == null) {
            break;
        } else {
            storageRpc.setBlock(resource.getAddress(), resource.getLength(), resource.getKey());
            DataNodeStatistics stats = storageRpc.getDataNode();
            long newCount = stats.getFreeBlockCount();
            long serviceId = stats.getServiceId();

            long oldCount = 0;
            if (blockCount.containsKey(serviceId)) {
                oldCount = blockCount.get(serviceId);
            }
            long diffCount = newCount - oldCount;
            blockCount.put(serviceId, newCount);
            sumCount += diffCount;
            LOG.info("datanode statistics, freeBlocks " + sumCount);
        }
    }

    while (server.isAlive()) {
        DataNodeStatistics stats = storageRpc.getDataNode();
        long newCount = stats.getFreeBlockCount();
        long serviceId = stats.getServiceId();

        long oldCount = 0;
        if (blockCount.containsKey(serviceId)) {
            oldCount = blockCount.get(serviceId);
        }
        long diffCount = newCount - oldCount;
        blockCount.put(serviceId, newCount);
        sumCount += diffCount;

        LOG.info("datanode statistics, freeBlocks " + sumCount);
        Thread.sleep(2000);
    }
}

From source file:mcnutty.music.get.MusicGet.java

public static void main(String[] args) throws Exception {

    //print out music-get
    System.out.println("                     _                      _   ");
    System.out.println(" _ __ ___  _   _ ___(_) ___       __ _  ___| |_ ");
    System.out.println("| '_ ` _ \\| | | / __| |/ __|____ / _` |/ _ \\ __|");
    System.out.println("| | | | | | |_| \\__ \\ | (_|_____| (_| |  __/ |_ ");
    System.out.println("|_| |_| |_|\\__,_|___/_|\\___|     \\__, |\\___|\\__|");
    System.out.println("                                 |___/          \n");

    //these will always be initialised later (but the compiler doesn't know that)
    String directory = "";
    Properties prop = new Properties();

    try (InputStream input = new FileInputStream("config.properties")) {
        prop.load(input);// ww  w . j ava  2  s .c  om
        if (prop.getProperty("directory") != null) {
            directory = prop.getProperty("directory");
        } else {
            System.out.println(
                    "Error reading config property 'directory' - using default value of /tmp/musicserver/\n");
            directory = "/tmp/musicserver/";
        }
        if (prop.getProperty("password") == null) {
            System.out.println("Error reading config property 'password' - no default value, exiting\n");
            System.exit(1);
        }
    } catch (IOException e) {
        System.out.println("Error reading config file");
        System.exit(1);
    }

    //create a queue object
    ProcessQueue process_queue = new ProcessQueue();

    try {
        if (args.length > 0 && args[0].equals("clean")) {
            Files.delete(Paths.get("queue.json"));
        }
        //load an existing queue if possible
        String raw_queue = Files.readAllLines(Paths.get("queue.json")).toString();
        JSONArray queue_state = new JSONArray(raw_queue);
        ConcurrentLinkedQueue<QueueItem> loaded_queue = new ConcurrentLinkedQueue<>();
        JSONArray queue = queue_state.getJSONArray(0);
        for (int i = 0; i < queue.length(); i++) {
            JSONObject item = ((JSONObject) queue.get(i));
            QueueItem loaded_item = new QueueItem();
            loaded_item.ip = item.getString("ip");
            loaded_item.real_name = item.getString("name");
            loaded_item.disk_name = item.getString("guid");
            loaded_queue.add(loaded_item);
        }
        process_queue.bucket_queue = loaded_queue;
        System.out.println("Loaded queue from disk\n");
    } catch (Exception ex) {
        //otherwise clean out the music directory and start a new queue
        try {
            Files.walkFileTree(Paths.get(directory), new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }
            });
            Files.delete(Paths.get(directory));
        } catch (Exception e) {
            e.printStackTrace();
        }
        Files.createDirectory(Paths.get(directory));
        System.out.println("Created a new queue\n");
    }

    //start the web server
    StartServer start_server = new StartServer(process_queue, directory);
    new Thread(start_server).start();

    //wit for the web server to spool up
    Thread.sleep(1000);

    //read items from the queue and play them
    while (true) {
        QueueItem next_item = process_queue.next_item();
        if (!next_item.equals(new QueueItem())) {
            //Check the timeout
            int timeout = 547;
            try (FileInputStream input = new FileInputStream("config.properties")) {
                prop.load(input);
                timeout = Integer.parseInt(prop.getProperty("timeout", "547"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Playing " + next_item.real_name);
            process_queue.set_played(next_item);
            process_queue.save_queue();
            Process p = Runtime.getRuntime().exec("timeout " + timeout
                    + "s mplayer -fs -quiet -af volnorm=2:0.25 " + directory + next_item.disk_name);

            try {
                p.waitFor(timeout, TimeUnit.SECONDS);
                Files.delete(Paths.get(directory + next_item.disk_name));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            process_queue.bucket_played.clear();
        }
        Thread.sleep(1000);
    }
}

From source file:org.dlw.ai.blackboard.knowledge.KnowledgeSourceUtil.java

/**
 * Private method to store an assertion/*from   ww  w .  j a v a2s. c o  m*/
 * 
 * @param ks
 *            the {@link KnowledgeSource} object
 * @param cipher
 *            the String cipher letter
 * @param plainText
 *            the String plain text letter
 */
private static void makeAssertion(KnowledgeSource ks, String cipher, String plainText) {

    /**
     * Create and load an Assertion
     */
    Assertion assertion = new Assertion();
    assertion.setCipherLetter(cipher);
    assertion.setPlainLetter(plainText);
    assertion.setReason(MessageConstants.SUBSTITUTION_ASSERT);

    /**
     * Get data-structure to hold new Assertion
     */
    ConcurrentLinkedQueue<Assumption> queue = ks.getPastAssumptions();

    /**
     * Load our Assertion
     */
    queue.add(assertion);

    /**
     * Add Assumption/Assertion queue to this specific knowledge source
     */
    ks.setPastAssumptions(queue);

}

From source file:com.jivesoftware.os.jive.utils.shell.utils.Invoke.java

public static int invoke(File home, String[] command, final InputStream writeToProcess,
        final ConcurrentLinkedQueue<String> response) throws Exception {
    Executor executor = new DefaultExecutor();
    executor.setExitValue(0);/*from  w ww  .  java  2 s  . com*/
    if (home != null) {
        executor.setWorkingDirectory(home);
    }

    //give all the processes 120s to return that they started successfully
    ExecuteWatchdog watchdog = new ExecuteWatchdog(120000);
    executor.setWatchdog(watchdog);

    LogOutputStream outputStream = new LogOutputStream(20000) {
        @Override
        protected void processLine(final String line, final int level) {
            response.add(line);
        }
    };

    LogOutputStream errorStream = new LogOutputStream(40000) {
        @Override
        protected void processLine(final String line, final int level) {
            response.add(line);
        }
    };

    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream, errorStream, writeToProcess);
    executor.setStreamHandler(pumpStreamHandler);
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());

    CommandLine commandLine = new CommandLine(command[0]);
    for (int i = 1; i < command.length; i++) {
        commandLine.addArgument(command[i]);
    }
    try {
        //executor.execute(commandLine, handler);
        return executor.execute(commandLine);
        //handler.waitFor(20000);
    } catch (Exception x) {
        x.printStackTrace();
        return 1;
    }
}

From source file:org.dlw.ai.blackboard.knowledge.cryptogram.DirectSubstitutionKnowledgeSource.java

private void makeAssertion(KnowledgeSource ks, String cipher, String plainText) {

    /**/* w w w.j  a  va 2  s  .c  o  m*/
     * Create and load an Assertion
     */
    Assertion assertion = new Assertion();
    assertion.setCipherLetter(cipher);
    assertion.setPlainLetter(plainText);
    assertion.setReason(MessageConstants.SUBSTITUTION_ASSERT);

    /**
     * Get data-structure to hold new Assertion
     */
    ConcurrentLinkedQueue<Assumption> queue = ks.getPastAssumptions();

    /**
     * Load our Assertion
     */
    queue.add(assertion);

    /**
     * Add Assumption/Assertion queue to this specific knowledge source
     */
    ks.setPastAssumptions(queue);

}

From source file:org.languagetool.server.PipelinePool.java

void returnPipeline(PipelineSettings settings, Pipeline pipeline) throws ExecutionException {
    if (pool == null)
        return;//from w ww .  j av a  2  s  .  c om
    ConcurrentLinkedQueue<Pipeline> pipelines = pool.get(settings);
    pipeline.refreshExpireTimer();
    pipelines.add(pipeline);
}

From source file:mcnutty.music.get.ProcessQueue.java

void save_queue() {
    try (PrintWriter file = new PrintWriter("queue.json")) {
        ConcurrentLinkedQueue<QueueItem> queue_dump = new ConcurrentLinkedQueue<>();
        QueueItem last_item = new QueueItem();
        for (QueueItem item : bucket_played)
            last_item = item;/*from   w  w w  . j  av  a 2s  . c om*/
        queue_dump.add(last_item);
        queue_dump.addAll(bucket_queue);
        file.println(json_array_list(queue_dump).toString());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:io.pravega.controller.eventProcessor.impl.SerializedRequestHandler.java

@Override
public final CompletableFuture<Void> process(final T streamEvent) {
    CompletableFuture<Void> result = new CompletableFuture<>();
    Work work = new Work(streamEvent, System.currentTimeMillis(), result);
    String key = streamEvent.getKey();

    final ConcurrentLinkedQueue<Work> queue;

    synchronized (lock) {
        if (workers.containsKey(key)) {
            workers.get(key).add(work);/*from  w  w  w  . j  ava 2  s .  co m*/
            queue = null;
        } else {
            queue = new ConcurrentLinkedQueue<>();
            queue.add(work);
            workers.put(key, queue);
        }
    }

    if (queue != null) {
        executor.execute(() -> run(key, queue));
    }

    return result;
}