Example usage for java.util.concurrent ConcurrentLinkedQueue ConcurrentLinkedQueue

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

Introduction

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

Prototype

public ConcurrentLinkedQueue() 

Source Link

Document

Creates a ConcurrentLinkedQueue that is initially empty.

Usage

From source file:com.ok2c.lightmtp.examples.LocalMailClientTransportExample.java

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

    String text1 = "From: root\r\n" + "To: testuser1\r\n" + "Subject: test message 1\r\n" + "\r\n"
            + "This is a short test message 1\r\n";
    String text2 = "From: root\r\n" + "To: testuser1, testuser2\r\n" + "Subject: test message 2\r\n" + "\r\n"
            + "This is a short test message 2\r\n";
    String text3 = "From: root\r\n" + "To: testuser1, testuser2, testuser3\r\n" + "Subject: test message 3\r\n"
            + "\r\n" + "This is a short test message 3\r\n";

    DeliveryRequest request1 = new BasicDeliveryRequest("root", Arrays.asList("testuser1"),
            new ByteArraySource(text1.getBytes("US-ASCII")));

    DeliveryRequest request2 = new BasicDeliveryRequest("root", Arrays.asList("testuser1", "testuser2"),
            new ByteArraySource(text2.getBytes("US-ASCII")));

    DeliveryRequest request3 = new BasicDeliveryRequest("root",
            Arrays.asList("testuser1", "testuser2", "testuser3"),
            new ByteArraySource(text3.getBytes("US-ASCII")));

    Queue<DeliveryRequest> queue = new ConcurrentLinkedQueue<DeliveryRequest>();
    queue.add(request1);/*from ww  w. j a  v  a  2  s.  c o  m*/
    queue.add(request2);
    queue.add(request3);

    CountDownLatch messageCount = new CountDownLatch(queue.size());

    IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(1).build();

    MailClientTransport mua = new LocalMailClientTransport(config);
    mua.start(new MyDeliveryRequestHandler(messageCount));

    SessionEndpoint endpoint = new SessionEndpoint(new InetSocketAddress("localhost", 2525));

    SessionRequest sessionRequest = mua.connect(endpoint, queue, null);
    sessionRequest.waitFor();

    IOSession iosession = sessionRequest.getSession();
    if (iosession != null) {
        messageCount.await();
    } else {
        IOException ex = sessionRequest.getException();
        if (ex != null) {
            System.out.println("Connection failed: " + ex.getMessage());
        }
    }

    System.out.println("Shutting down I/O reactor");
    try {
        mua.shutdown();
    } catch (IOException ex) {
        mua.forceShutdown();
    }
    System.out.println("Done");
}

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);//from w  w w .  j a  va2  s .  com
        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:playground.johannes.socialnets.SpatialNetworkGenerator.java

/**
 * @param args/*  w  w w .  ja  v a  2 s.com*/
 * @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 ww  .j a va  2s .co  m*/
    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: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. j  a va2s .  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:Main.java

public static <T> Collection<T> createSyncronizedCollection() {
    return new ConcurrentLinkedQueue<T>();
}

From source file:Main.java

public static <E> Queue<E> getConcurrentLinkedQueue() {
    return new ConcurrentLinkedQueue<E>();
}

From source file:Main.java

public static <E> ConcurrentLinkedQueue<E> newConcurrentLinkedQueue() {
    return new ConcurrentLinkedQueue<E>();
}

From source file:com.insightml.utils.Collections.java

public static <I> ConcurrentLinkedQueue<I> newConcurrentList() {
    return new ConcurrentLinkedQueue<>();
}

From source file:edu.eci.arsw.msgbroker.ManejadorPuntos.java

public void reset() {
    puntos = new ConcurrentLinkedQueue<Point>();
}