Example usage for java.util.concurrent LinkedBlockingDeque LinkedBlockingDeque

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

Introduction

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

Prototype

public LinkedBlockingDeque(Collection<? extends E> c) 

Source Link

Document

Creates a LinkedBlockingDeque with a capacity of Integer#MAX_VALUE , initially containing the elements of the given collection, added in traversal order of the collection's iterator.

Usage

From source file:Producer.java

public static void main(String[] args) {
    BlockingDeque<Integer> deque = new LinkedBlockingDeque<Integer>(5);
    Runnable producer = new Producer("Producer", deque);
    Runnable consumer = new Consumer("Consumer", deque);
    new Thread(producer).start();
    try {//from   w  ww  .j a va  2 s.  c  o  m
        Thread.sleep(500);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    new Thread(consumer).start();
}

From source file:com.utdallas.s3lab.smvhunter.monkey.MonkeyMe.java

/**
 * @param args// w  w w  .  ja  v  a 2 s  .c  om
 */
public static void main(String[] args) throws Exception {

    logger.info("start time ==== " + System.currentTimeMillis());

    try {
        //load the adb location from the props file
        Properties props = new Properties();
        props.load(new FileInputStream(new File("adb.props")));

        //set the adb location
        WindowUpdate.adbLocation = props.getProperty("adb_location");
        adbLocation = props.getProperty("adb_location");
        //set root dir
        ROOT_DIRECTORY = props.getProperty("root_dir");
        //completed txt
        completedFile = new File(ROOT_DIRECTORY + "tested.txt");
        //db location for static analysis
        dbLocation = props.getProperty("db_location");
        //location for smart input generation output
        smartInputLocation = props.getProperty("smart_input_location");

        //udp dump location
        udpDumpLocation = props.getProperty("udp_dump_location");
        //logcat dump location
        logCatLocation = props.getProperty("log_cat_location");
        //strace output location
        straceOutputLocation = props.getProperty("strace_output_location");
        //strace dump location
        straceDumpLocation = props.getProperty("strace_output_location");

        //set x and y coords
        UIEnumerator.screenX = props.getProperty("x");
        UIEnumerator.screenY = props.getProperty("y");

        DeviceOfflineMonitor.START_EMULATOR = props.getProperty("restart");

        //read output of static analysis
        readFromStaticAnalysisText();
        logger.info("Read static analysis output");

        readFromSmartInputText();
        logger.info("Read smart input generation output");

        //populate the queue with apps which are only present in the static analysis
        @SuppressWarnings("unchecked")
        final Set<? extends String> sslApps = new HashSet<String>(
                CollectionUtils.collect(FileUtils.readLines(new File(dbLocation)), new Transformer() {
                    @Override
                    public Object transform(Object input) {
                        //get app file name
                        String temp = StringUtils.substringBefore(input.toString(), " ");
                        return StringUtils.substringAfterLast(temp, "/");
                    }
                }));
        Collection<File> fileList = FileUtils.listFiles(new File(ROOT_DIRECTORY), new String[] { "apk" },
                false);
        CollectionUtils.filter(fileList, new Predicate() {
            @Override
            public boolean evaluate(Object object) {
                return sslApps.contains(StringUtils.substringAfterLast(object.toString(), "/"));
            }
        });
        apkQueue = new LinkedBlockingDeque<File>(fileList);

        logger.info("finished listing files from the root directory");

        try {
            //populate the tested apk list
            completedApps.addAll(FileUtils.readLines(completedFile));
        } catch (Exception e) {
            //pass except
            logger.info("No tested.txt file found");

            //create new file
            if (completedFile.createNewFile()) {
                logger.info("tested.txt created in root directory");
            } else {
                logger.info("tested.txt file could not be created");
            }

        }

        //get the executors for managing the emulators
        executors = Executors.newCachedThreadPool();

        //set the devicemonitor exec
        DeviceOfflineMonitor.exec = executors;

        final List<Future<?>> futureList = new ArrayList<Future<?>>();

        //start the offline device monitor (emulator management thread)
        logger.info("Starting Device Offline Monitor Thread");
        executors.submit(new DeviceOfflineMonitor());

        //get ADB backend object for device change listener
        AdbBackend adb = new AdbBackend();

        //register for device change and wait for events
        //once event is received, start the MonkeyMe thread
        MonkeyDeviceChangeListener deviceChangeListener = new MonkeyDeviceChangeListener(executors, futureList);
        AndroidDebugBridge.addDeviceChangeListener(deviceChangeListener);
        logger.info("Listening to changes in devices (emulators)");

        //wait for the latch to come down
        //this means that all the apks have been processed
        cdl.await();

        logger.info("Finished testing all apps waiting for threads to join");

        //now wait for every thread to finish
        for (Future<?> future : futureList) {
            future.get();
        }

        logger.info("All threads terminated");

        //stop listening for device update
        AndroidDebugBridge.removeDeviceChangeListener(deviceChangeListener);

        //stop the debug bridge
        AndroidDebugBridge.terminate();

        //stop offline device monitor
        DeviceOfflineMonitor.stop = true;

        logger.info("adb and listeners terminated");

    } finally {
        logger.info("Executing this finally");
        executors.shutdownNow();
    }

    logger.info("THE END!!");
}

From source file:Main.java

public static ExecutorService getThreadPoolExecutor() {
    if (executor == null) {
        executor = new ThreadPoolExecutor(2, 5, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(3));
    }/*from  ww w  .ja va  2 s .com*/
    return executor;
}

From source file:Main.java

public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque(final Collection<? extends E> c) {
    return new LinkedBlockingDeque<E>(c);
}

From source file:Main.java

public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque(final int initialCapacity) {
    return new LinkedBlockingDeque<E>(initialCapacity);
}

From source file:org.mule.config.pool.DefaultThreadPoolFactory.java

public ThreadPoolExecutor createPool(String name, ThreadingProfile tp) {
    BlockingQueue buffer;/*from ww  w  . j  av a  2 s  .co m*/

    if (tp.getMaxBufferSize() > 0 && tp.getMaxThreadsActive() > 1) {
        buffer = new LinkedBlockingDeque(tp.getMaxBufferSize());
    } else {
        buffer = new SynchronousQueue();
    }

    ThreadPoolExecutor pool = internalCreatePool(name, tp, buffer);
    configureThreadPoolExecutor(name, tp, pool);
    return pool;

}

From source file:org.phoenicis.multithreading.ControlledThreadPoolExecutorService.java

public ControlledThreadPoolExecutorService(String name, int numberOfThread, int queueSize) {
    super(numberOfThread, numberOfThread, 0, TimeUnit.SECONDS, new LinkedBlockingDeque<>(queueSize));
    this.semaphore = new Semaphore(queueSize);
    this.name = name;
    this.numberOfThreads = numberOfThread;
}

From source file:org.apache.distributedlog.common.rate.SampledMovingAverageRate.java

SampledMovingAverageRate(int intervalSecs, double scaleFactor, Ticker ticker) {
    this.value = 0;
    this.total = new LongAdder();
    this.scaleFactor = scaleFactor;
    this.ticker = ticker;
    this.samples = new LinkedBlockingDeque<>(intervalSecs);
}

From source file:org.muehleisen.hannes.taxiapp.TaxiRoute.java

@Override
public void run() {
    log.info(this.getClass().getSimpleName() + " starting...");

    BlockingQueue<Runnable> taskQueue = new LinkedBlockingDeque<Runnable>(100);
    ExecutorService ex = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(),
            Runtime.getRuntime().availableProcessors(), Integer.MAX_VALUE, TimeUnit.DAYS, taskQueue,
            new ThreadPoolExecutor.DiscardPolicy());
    // create rainbow table for driver lookup
    log.info("Creating driver license rainbow table.");
    RouteLogEntry.initLrt();//w w  w . ja  v  a 2  s.  c  o m

    // bring up routing service
    log.info("Bringing up OTP Graph Service from '" + graph + "'.");
    GraphServiceImpl graphService = new GraphServiceImpl();
    graphService.setPath(graph);
    graphService.startup();
    ps = new RetryingPathServiceImpl(graphService, new EarliestArrivalSPTService());

    // read taxi files
    log.info("Reading taxi files from '" + taxilog + "'.");
    Collection<File> files = FileUtils.listFiles(new File(taxilog), new SuffixFileFilter(".csv.zip"),
            TrueFileFilter.INSTANCE);
    for (File f : files) {
        log.info("Reading '" + f + "'.");
        try {
            ZipInputStream z = new ZipInputStream(new FileInputStream(f));
            z.getNextEntry(); // ZIP files have many entries. In this case,
                              // only one
            BufferedReader r = new BufferedReader(new InputStreamReader(z));
            r.readLine(); // header
            String line = null;
            while ((line = r.readLine()) != null) {
                RouteLogEntry rle = new RouteLogEntry(line);
                if (!rle.hasGeo()) {
                    continue;
                }
                while (taskQueue.remainingCapacity() < 1) {
                    Thread.sleep(100);
                }
                ex.submit(new RouteTask(rle));
            }
            r.close();
            z.close();
        } catch (Exception e) {
            log.error("Failed to read taxi file from '" + taxilog + "'.", e);
        }
    }
    ex.shutdown();
    try {
        ex.awaitTermination(Integer.MAX_VALUE, TimeUnit.DAYS);
    } catch (InterruptedException e) {
        // ...
    }
    log.info(deliveries);
}

From source file:com.pinterest.terrapin.storage.ReaderFactory.java

public ReaderFactory(PropertiesConfiguration configuration, FileSystem hadoopFs) {
    this.configuration = configuration;
    this.hadoopFs = hadoopFs;
    int numReaderThreads = this.configuration.getInt(Constants.READER_THREAD_POOL_SIZE, 200);
    ExecutorService threadPool = new ThreadPoolExecutor(numReaderThreads, numReaderThreads, 0, TimeUnit.SECONDS,
            new LinkedBlockingDeque<Runnable>(10000),
            new ThreadFactoryBuilder().setDaemon(false).setNameFormat("reader-pool-%d").build());
    this.readerFuturePool = new ExecutorServiceFuturePool(threadPool);
}