Example usage for java.util Queue add

List of usage examples for java.util Queue add

Introduction

In this page you can find the example usage for java.util Queue 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:poisondog.demo.StringDemo.java

public static void main(String[] args) {
    //      String temp=" command  para1 para2  ";
    //      System.out.println(temp.replaceAll("^\\s*\\S*\\s*", "").replaceAll("\\s*$", "") + "]]");

    Queue<Double> queue = new CircularFifoQueue<Double>(1000);
    List<Double> all = new LinkedList<Double>();
    List<Double> list = new ArrayList<Double>();
    double result = 0;
    double sum = 0;
    Random r = new Random();
    for (int i = 0; i < 10000; i++) {
        double g = r.nextGaussian() * 100 - 5;
        sum += g;//from w w w .j  a  va2 s .  c  o  m
        if (g > 0)
            result++;
        if (i > 5000 && getRate(queue) < getRate(all) * .94)
            list.add(g);
        all.add(g);
        queue.add(g);
        //         if (queue.size() > 1000)
        //            queue.remove();

    }
    //      System.out.println(list.size());
    int count = 0;
    for (Double d : list) {
        if (d > 0)
            count++;
    }
    System.out.println("Origin Rate: " + (double) result / all.size());
    System.out.println("Origin Sum: " + sum);
    System.out.println("Upgrade Rate: " + (double) count / list.size());
    System.out.println("Upgrade Count: " + list.size());
    System.out.println("Upgrade Sum: " + getSum(list));
    System.out.println("Queue Count: " + queue.size());
}

From source file:io.aos.protocol.http.httpcommon.FluentAsync.java

public static void main(String... args) throws Exception {
    // Use pool of two threads
    ExecutorService threadpool = Executors.newFixedThreadPool(2);
    Async async = Async.newInstance().use(threadpool);

    Request[] requests = new Request[] { Request.Get("http://www.google.com/"),
            Request.Get("http://www.yahoo.com/"), Request.Get("http://www.apache.com/"),
            Request.Get("http://www.apple.com/") };

    Queue<Future<Content>> queue = new LinkedList<Future<Content>>();
    // Execute requests asynchronously
    for (final Request request : requests) {
        Future<Content> future = async.execute(request, new FutureCallback<Content>() {

            public void failed(final Exception ex) {
                System.out.println(ex.getMessage() + ": " + request);
            }//from  w  w w .java 2 s.  c  o m

            public void completed(final Content content) {
                System.out.println("Request completed: " + request);
            }

            public void cancelled() {
            }

        });
        queue.add(future);
    }

    while (!queue.isEmpty()) {
        Future<Content> future = queue.remove();
        try {
            future.get();
        } catch (ExecutionException ex) {
        }
    }
    System.out.println("Done");
    threadpool.shutdown();
}

From source file:org.apache.flink.benchmark.Runner.java

public static void main(String[] args) throws Exception {
    final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
    env.getConfig().enableObjectReuse();
    env.getConfig().disableSysoutLogging();

    ParameterTool parameters = ParameterTool.fromArgs(args);

    if (!(parameters.has("p") && parameters.has("types") && parameters.has("algorithms"))) {
        printUsage();/*from w w  w. j a v a 2 s  .  com*/
        System.exit(-1);
    }

    int parallelism = parameters.getInt("p");
    env.setParallelism(parallelism);

    Set<IdType> types = new HashSet<>();

    if (parameters.get("types").equals("all")) {
        types.add(IdType.INT);
        types.add(IdType.LONG);
        types.add(IdType.STRING);
    } else {
        for (String type : parameters.get("types").split(",")) {
            if (type.toLowerCase().equals("int")) {
                types.add(IdType.INT);
            } else if (type.toLowerCase().equals("long")) {
                types.add(IdType.LONG);
            } else if (type.toLowerCase().equals("string")) {
                types.add(IdType.STRING);
            } else {
                printUsage();
                throw new RuntimeException("Unknown type: " + type);
            }
        }
    }

    Queue<RunnerWithScore> queue = new PriorityQueue<>();

    if (parameters.get("algorithms").equals("all")) {
        for (Map.Entry<String, Class> entry : AVAILABLE_ALGORITHMS.entrySet()) {
            for (IdType type : types) {
                AlgorithmRunner runner = (AlgorithmRunner) entry.getValue().newInstance();
                runner.initialize(type, SAMPLES, parallelism);
                runner.warmup(env);
                queue.add(new RunnerWithScore(runner, 1.0));
            }
        }
    } else {
        for (String algorithm : parameters.get("algorithms").split(",")) {
            double ratio = 1.0;
            if (algorithm.contains("=")) {
                String[] split = algorithm.split("=");
                algorithm = split[0];
                ratio = Double.parseDouble(split[1]);
            }

            if (AVAILABLE_ALGORITHMS.containsKey(algorithm.toLowerCase())) {
                Class clazz = AVAILABLE_ALGORITHMS.get(algorithm.toLowerCase());

                for (IdType type : types) {
                    AlgorithmRunner runner = (AlgorithmRunner) clazz.newInstance();
                    runner.initialize(type, SAMPLES, parallelism);
                    runner.warmup(env);
                    queue.add(new RunnerWithScore(runner, ratio));
                }
            } else {
                printUsage();
                throw new RuntimeException("Unknown algorithm: " + algorithm);
            }
        }
    }

    JsonFactory factory = new JsonFactory();

    while (queue.size() > 0) {
        RunnerWithScore current = queue.poll();
        AlgorithmRunner runner = current.getRunner();

        StringWriter writer = new StringWriter();
        JsonGenerator gen = factory.createGenerator(writer);
        gen.writeStartObject();
        gen.writeStringField("algorithm", runner.getClass().getSimpleName());

        boolean running = true;

        while (running) {
            try {
                runner.run(env, gen);
                running = false;
            } catch (ProgramInvocationException e) {
                // only suppress job cancellations
                if (!(e.getCause() instanceof JobCancellationException)) {
                    throw e;
                }
            }
        }

        JobExecutionResult result = env.getLastJobExecutionResult();

        long runtime_ms = result.getNetRuntime();
        gen.writeNumberField("runtime_ms", runtime_ms);
        current.credit(runtime_ms);

        if (!runner.finished()) {
            queue.add(current);
        }

        gen.writeObjectFieldStart("accumulators");
        for (Map.Entry<String, Object> accumulatorResult : result.getAllAccumulatorResults().entrySet()) {
            gen.writeStringField(accumulatorResult.getKey(), accumulatorResult.getValue().toString());
        }
        gen.writeEndObject();

        gen.writeEndObject();
        gen.close();
        System.out.println(writer.toString());
    }
}

From source file:interoperabilite.webservice.fluent.FluentAsync.java

public static void main(String[] args) throws Exception {
    // Use pool of two threads
    ExecutorService threadpool = Executors.newFixedThreadPool(2);
    Async async = Async.newInstance().use(threadpool);

    Request[] requests = new Request[] { Request.Get("http://www.google.com/"),
            Request.Get("http://www.yahoo.com/"), Request.Get("http://www.apache.com/"),
            Request.Get("http://www.apple.com/") };

    Queue<Future<Content>> queue = new LinkedList<Future<Content>>();
    // Execute requests asynchronously
    for (final Request request : requests) {
        Future<Content> future = async.execute(request, new FutureCallback<Content>() {

            @Override/*from   w  w w  .ja v a2s .co  m*/
            public void failed(final Exception ex) {
                System.out.println(ex.getMessage() + ": " + request);
            }

            @Override
            public void completed(final Content content) {
                System.out.println("Request completed: " + request);
            }

            @Override
            public void cancelled() {
            }

        });
        queue.add(future);
    }

    while (!queue.isEmpty()) {
        Future<Content> future = queue.remove();
        try {
            future.get();
        } catch (ExecutionException ex) {
        }
    }
    System.out.println("Done");
    threadpool.shutdown();
}

From source file:gobblin.restli.throttling.LocalStressTest.java

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

    CommandLine cli = StressTestUtils.parseCommandLine(OPTIONS, args);

    int stressorThreads = Integer.parseInt(
            cli.getOptionValue(STRESSOR_THREADS.getOpt(), Integer.toString(DEFAULT_STRESSOR_THREADS)));
    int processorThreads = Integer.parseInt(
            cli.getOptionValue(PROCESSOR_THREADS.getOpt(), Integer.toString(DEFAULT_PROCESSOR_THREADS)));
    int artificialLatency = Integer.parseInt(
            cli.getOptionValue(ARTIFICIAL_LATENCY.getOpt(), Integer.toString(DEFAULT_ARTIFICIAL_LATENCY)));
    long targetQps = Integer.parseInt(cli.getOptionValue(QPS.getOpt(), Integer.toString(DEFAULT_TARGET_QPS)));

    Configuration configuration = new Configuration();
    StressTestUtils.populateConfigFromCli(configuration, cli);

    String resourceLimited = LocalStressTest.class.getSimpleName();

    Map<String, String> configMap = Maps.newHashMap();

    ThrottlingPolicyFactory factory = new ThrottlingPolicyFactory();
    SharedLimiterKey res1key = new SharedLimiterKey(resourceLimited);
    configMap.put(BrokerConfigurationKeyGenerator.generateKey(factory, res1key, null,
            ThrottlingPolicyFactory.POLICY_KEY), QPSPolicy.FACTORY_ALIAS);
    configMap.put(BrokerConfigurationKeyGenerator.generateKey(factory, res1key, null, QPSPolicy.QPS),
            Long.toString(targetQps));

    ThrottlingGuiceServletConfig guiceServletConfig = new ThrottlingGuiceServletConfig();
    guiceServletConfig.initialize(ConfigFactory.parseMap(configMap));
    LimiterServerResource limiterServer = guiceServletConfig.getInjector()
            .getInstance(LimiterServerResource.class);

    RateComputingLimiterContainer limiterContainer = new RateComputingLimiterContainer();

    Class<? extends Stressor> stressorClass = configuration.getClass(StressTestUtils.STRESSOR_CLASS,
            StressTestUtils.DEFAULT_STRESSOR_CLASS, Stressor.class);

    ExecutorService executorService = Executors.newFixedThreadPool(stressorThreads);

    SharedResourcesBroker broker = guiceServletConfig.getInjector().getInstance(
            Key.get(SharedResourcesBroker.class, Names.named(LimiterServerResource.BROKER_INJECT_NAME)));
    ThrottlingPolicy policy = (ThrottlingPolicy) broker.getSharedResource(new ThrottlingPolicyFactory(),
            new SharedLimiterKey(resourceLimited));
    ScheduledExecutorService reportingThread = Executors.newSingleThreadScheduledExecutor();
    reportingThread.scheduleAtFixedRate(new Reporter(limiterContainer, policy), 0, 15, TimeUnit.SECONDS);

    Queue<Future<?>> futures = new LinkedList<>();
    MockRequester requester = new MockRequester(limiterServer, artificialLatency, processorThreads);

    requester.start();// w w  w  . j  a v  a2s .  c  om
    for (int i = 0; i < stressorThreads; i++) {
        RestliServiceBasedLimiter restliLimiter = RestliServiceBasedLimiter.builder()
                .resourceLimited(resourceLimited).requestSender(requester).serviceIdentifier("stressor" + i)
                .build();

        Stressor stressor = stressorClass.newInstance();
        stressor.configure(configuration);
        futures.add(executorService
                .submit(new StressorRunner(limiterContainer.decorateLimiter(restliLimiter), stressor)));
    }
    int stressorFailures = 0;
    for (Future<?> future : futures) {
        try {
            future.get();
        } catch (ExecutionException ee) {
            stressorFailures++;
        }
    }
    requester.stop();

    executorService.shutdownNow();

    if (stressorFailures > 0) {
        log.error("There were " + stressorFailures + " failed stressor threads.");
    }
    System.exit(stressorFailures);
}

From source file:amie.keys.CSAKey.java

public static void main(String[] args) throws IOException, InterruptedException {
    final Triple<MiningAssistant, Float, String> parsedArgs = parseArguments(args);
    final Set<Rule> output = new LinkedHashSet<>();

    // Helper object that contains the implementation for the calculation
    // of confidence and support
    // The file with the non-keys, one per line
    long timea = System.currentTimeMillis();
    List<List<String>> inputNonKeys = Utilities.parseNonKeysFile(parsedArgs.third);
    System.out.println(inputNonKeys.size() + " input non-keys");
    final List<List<String>> nonKeys = pruneBySupport(inputNonKeys, parsedArgs.second,
            parsedArgs.first.getKb());/*from  w  ww. j  a v a 2s  .  co m*/
    Collections.sort(nonKeys, new Comparator<List<String>>() {

        @Override
        public int compare(List<String> o1, List<String> o2) {
            int r = Integer.compare(o2.size(), o1.size());
            if (r == 0) {
                return Integer.compare(o2.hashCode(), o1.hashCode());
            }

            return r;
        }

    });
    System.out.println(nonKeys.size() + " non-keys after pruning");
    int totalLoad = computeLoad(nonKeys);
    System.out.println(totalLoad + " is the total load");
    int nThreads = Runtime.getRuntime().availableProcessors();
    //int batchSize = Math.max(Math.min(maxBatchSize, totalLoad / nThreads), minBatchSize);
    int batchSize = Math.max(Math.min(maxLoad, totalLoad / nThreads), minLoad);

    final Queue<int[]> chunks = new PriorityQueue(50, new Comparator<int[]>() {
        @Override
        public int compare(int[] o1, int[] o2) {
            return Integer.compare(o2[2], o1[2]);
        }

    });

    final HashSet<HashSet<Integer>> nonKeysInt = new HashSet<>();
    final HashMap<String, Integer> property2Id = new HashMap<>();
    final HashMap<Integer, String> id2Property = new HashMap<>();
    final List<Integer> propertiesList = new ArrayList<>();
    int support = (int) parsedArgs.second.floatValue();
    KB kb = parsedArgs.first.getKb();
    buildDictionaries(nonKeys, nonKeysInt, property2Id, id2Property, propertiesList, support, kb);
    final List<HashSet<Integer>> nonKeysIntList = new ArrayList<>(nonKeysInt);
    int start = 0;
    int[] nextIdx = nextIndex(nonKeysIntList, 0, batchSize);
    int end = nextIdx[0];
    int load = nextIdx[1];
    while (start < nonKeysIntList.size()) {
        int[] chunk = new int[] { start, end, load };
        chunks.add(chunk);
        start = end;
        nextIdx = nextIndex(nonKeysIntList, end, batchSize);
        end = nextIdx[0];
        load = nextIdx[1];
    }

    Thread[] threads = new Thread[Math.min(Runtime.getRuntime().availableProcessors(), chunks.size())];
    for (int i = 0; i < threads.length; ++i) {
        threads[i] = new Thread(new Runnable() {

            @Override
            public void run() {
                while (true) {
                    int[] chunk = null;
                    synchronized (chunks) {
                        if (!chunks.isEmpty()) {
                            chunk = chunks.poll();
                        } else {
                            break;
                        }
                    }
                    System.out.println("Processing chunk " + Arrays.toString(chunk));
                    mine(parsedArgs, nonKeysIntList, property2Id, id2Property, propertiesList, chunk[0],
                            chunk[1], output);
                }

            }
        });
        threads[i].start();
    }

    for (int i = 0; i < threads.length; ++i) {
        threads[i].join();
    }
    long timeb = System.currentTimeMillis();
    System.out.println("==== Unique C-keys =====");
    for (Rule r : output) {
        System.out.println(Utilities.formatKey(r));
    }
    System.out.println(
            "VICKEY found " + output.size() + " unique conditional keys in " + (timeb - timea) + " ms");
}

From source file:Main.java

public static <T extends Annotation> T getAnnotation(Class<?> clazz, Class<T> aClazz) {
    //Check class hierarchy
    for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
        T anno = c.getAnnotation(aClazz);
        if (anno != null) {
            return anno;
        }/*from w  w w . j  a  v a2  s . c  om*/
    }

    //Check interfaces (breadth first)
    Queue<Class<?>> q = new LinkedList<Class<?>>();
    q.add(clazz);
    while (!q.isEmpty()) {
        Class<?> c = q.remove();
        if (c != null) {
            if (c.isInterface()) {
                T anno = c.getAnnotation(aClazz);
                if (anno != null) {
                    return anno;
                }
            } else {
                q.add(c.getSuperclass());
            }
            q.addAll(Arrays.asList(c.getInterfaces()));
        }
    }

    return null;
}

From source file:com.rapleaf.hank.cli.AddRing.java

private static void addRing(ClientConfigurator configurator, String ringGroupName, int ringNumber,
        String hostsString) throws Exception {
    // create the ring
    Coordinator coord = configurator.getCoordinator();
    RingGroup ringGroup = coord.getRingGroupConfig(ringGroupName);
    Ring newRing = ringGroup.addRing(ringNumber);

    // add all the hosts to the ring
    String[] hosts = hostsString.split(",");
    List<Host> hostConfigs = new LinkedList<Host>();
    for (String host : hosts) {
        PartDaemonAddress address = PartDaemonAddress.parse(host);
        hostConfigs.add(newRing.addHost(address));
    }/* w  w  w  .  j  a v  a  2  s .  c  o  m*/

    // assign all the domains to the hosts
    DomainGroup domainGroup = ringGroup.getDomainGroup();
    DomainGroupVersion latestVersion = domainGroup.getLatestVersion();
    int verNum = latestVersion.getVersionNumber();
    for (DomainGroupVersionDomainVersion domainVersion : latestVersion.getDomainVersions()) {
        Domain domain = domainVersion.getDomain();

        Queue<HostDomain> q = new LinkedList<HostDomain>();
        for (Host hostConfig : hostConfigs) {
            q.add(hostConfig.addDomain(domainGroup.getDomainId(domain.getName())));
        }

        for (int i = 0; i < domain.getNumParts(); i++) {
            HostDomain hdc = q.poll();
            hdc.addPartition(i, verNum);
            q.add(hdc);
        }
    }
}

From source file:graphs.Graphs.java

public static <V, E> String BreadthSearch(Graph<V, E> g) {
    StringBuilder b = new StringBuilder();

    Queue<V> Qu = new LinkedList<V>();
    Set<V> visited = new HashSet();
    Set<V> found = new HashSet();

    V start = (V) g.getVertices().toArray()[0];
    Qu.add(start);
    found.add(start);//from   www.ja v  a  2  s .  co m

    while (!Qu.isEmpty()) {
        V vertex = Qu.remove();
        for (V neighbor : g.getNeighbors(vertex)) {
            if (!found.contains(neighbor) && !visited.contains(neighbor)) {
                found.add(neighbor);
                Qu.add(neighbor);
            }
        }
        b.append(vertex.toString() + " ");
        visited.add(vertex);
    }

    return b.toString();
}

From source file:fr.inria.atlanmod.emf.graphs.Connectedness.java

/**
 * Returns the {@link Set} of {@link EObject}s that can be reached by
 * navigating {@link EReference}s, starting from <code>initialEObject</code>
 * //  ww w  . j av  a 2 s  .  com
 * @param initialEObject
 *            The initial {@link EObject}
 * @return The {@link Set} of reachable {@link EObject}s
 */
private static Set<EObject> getReachableEObjects(EObject initialEObject) {
    Set<EObject> visited = new HashSet<>();
    Queue<EObject> next = new LinkedList<EObject>();
    next.add(initialEObject);

    while (!next.isEmpty()) {
        EObject activeEObject = next.poll();
        if (visited.add(activeEObject)) {
            next.addAll(activeEObject.eContents());
            next.addAll(activeEObject.eCrossReferences());
        }
    }

    return visited;
}