Example usage for java.util.concurrent Executors newSingleThreadExecutor

List of usage examples for java.util.concurrent Executors newSingleThreadExecutor

Introduction

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

Prototype

public static ExecutorService newSingleThreadExecutor() 

Source Link

Document

Creates an Executor that uses a single worker thread operating off an unbounded queue.

Usage

From source file:gov.nih.nci.grididloader.BigIdCreator.java

/**
 * Reads properties from a file called "loader.properties" in the classpath
 * and configures a new BigIdCreator.//from w  w  w.  j av a  2  s  .c  om
 * @throws Exception If loader.properties cannot be found, or a property 
 *         is missing.
 */
public BigIdCreator() throws Exception {

    // Load the configuration files
    final Properties props = new Properties();
    final Properties dbprops = new Properties();
    final InputStream is = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("loader.properties");
    final InputStream dis = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");
    try {
        props.load(is);
        dbprops.load(dis);
    } catch (Exception e) {
        throw new Exception("Can't read the properties file. "
                + "Make sure loader.properties and db.properties " + "are in the CLASSPATH");
    } finally {

    }

    // Setup database connection pool
    final OracleConnectionPoolDataSource pool = new OracleConnectionPoolDataSource();
    pool.setURL(dbprops.getProperty("oracleloader.url"));
    pool.setUser(dbprops.getProperty("oracleloader.user"));
    pool.setPassword(dbprops.getProperty("oracleloader.password"));
    this.dataSource = pool;

    // load entities and mappings
    config.loadXMLMapping(props.getProperty("mapping.file"));

    // setup the handle interface factory
    this.hiFactory = new HandleInterfaceFactory(props, dataSource);

    // init the job executor
    this.numThreads = Integer.parseInt(props.getProperty("loader.threads"));
    this.parallelExecutor = Executors.newFixedThreadPool(numThreads);
    this.serialExecutor = Executors.newSingleThreadExecutor();
}

From source file:com.sonymobile.jenkins.plugins.lenientshutdown.PluginImpl.java

/**
 * Actually sets the node offline or prepares it to be leniently and then later offline.
 *
 * @param computer the computer./*from   w w w  .  j  av a 2 s.co m*/
 */
public void setNodeOffline(final Computer computer) {
    if (computer == null) {
        return;
    }
    final Node node = computer.getNode();
    if (node == null) {
        return;
    }
    if (QueueUtils.isBuilding(computer) || QueueUtils.hasNodeExclusiveItemInQueue(computer)) {
        //Doing some work; we want to take offline leniently
        final String nodeName = node.getNodeName();
        toggleNodeShuttingDown(nodeName);
        setOfflineByUser(nodeName, User.current());

        ExecutorService service = new SecurityContextExecutorService(Executors.newSingleThreadExecutor());
        service.submit(new Runnable() {
            @Override
            public void run() {
                Set<Long> permittedQueuedItemIds = getPermittedQueuedItemIds(nodeName);
                permittedQueuedItemIds.clear();
                permittedQueuedItemIds.addAll(QueueUtils.getPermittedQueueItemIds(nodeName));
                permittedQueuedItemIds.addAll(QueueUtils.getRunninProjectsQueueIDs(nodeName));
            }
        });

    } else { //No builds; we can take offline directly
        User currentUser = User.current();
        if (currentUser == null) {
            currentUser = User.getUnknown();
        }
        computer.setTemporarilyOffline(true, new LenientOfflineCause(currentUser));
    }
}

From source file:com.echopf.ECHOTreeMap.java

/**
 * Does Fetch data from the remote server in a background thread.
 *
 * @param sync if set TRUE, then the main (UI) thread is waited for complete the fetching in a background thread. 
 *         (a synchronous communication)
 * @param callback invoked after the fetching is completed
 * @throws ECHOException //from w w w  .j a  v a2  s. c om
 */
protected void doFetch(final boolean sync, final FetchCallback<S> callback) throws ECHOException {
    final Handler handler = new Handler();

    // Get ready a background thread
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<Object> communictor = new Callable<Object>() {

        @Override
        public Object call() throws ECHOException {

            ECHOException exception = null;
            JSONObject data = null;

            try {

                synchronized (lock) {
                    data = ECHOQuery.getRequest(getRequestURLPath());
                    copyData(data);
                }

            } catch (ECHOException e) {
                exception = e;
            } catch (Exception e) {
                exception = new ECHOException(e);
            }

            if (sync == false) {

                // Execute a callback method in the main (UI) thread.
                if (callback != null) {
                    final ECHOException fException = exception;
                    handler.post(new Runnable() {
                        @Override
                        @SuppressWarnings("unchecked")
                        public void run() {
                            callback.done((S) ECHOTreeMap.this, fException);
                        }
                    });
                }

            } else {

                if (exception != null)
                    throw exception;
            }

            return null;
        }
    };

    Future<Object> future = executor.submit(communictor);

    if (sync) {
        try {
            future.get();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // ignore/reset
        } catch (ExecutionException e) {
            Throwable e2 = e.getCause();

            if (e2 instanceof ECHOException) {
                throw (ECHOException) e2;
            }

            throw new RuntimeException(e2);
        }
    }
}

From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessReadWriteLock.java

@Test
public void testThatDowngradingRespectsThreads() throws Exception {
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try {/*from www.j  a va 2s .  c  o m*/
        client.start();

        final InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock");
        ExecutorService t1 = Executors.newSingleThreadExecutor();
        ExecutorService t2 = Executors.newSingleThreadExecutor();

        final CountDownLatch latch = new CountDownLatch(1);

        Future<Object> f1 = t1.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                lock.writeLock().acquire();
                latch.countDown();
                return null;
            }
        });

        Future<Object> f2 = t2.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
                Assert.assertFalse(lock.readLock().acquire(5, TimeUnit.SECONDS));
                return null;
            }
        });

        f1.get();
        f2.get();
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:es.molabs.io.utils.test.FileWatcherRunnableTest.java

@Before
public void setUp() {
    executor = Executors.newSingleThreadExecutor();
}

From source file:com.olacabs.fabric.compute.pipelined.ComuptationPipelineTest.java

@Test
public void testCheck() throws Exception {
    Properties properties = new Properties();
    properties.put("processor.counter_1.triggering_frequency", "1000");
    properties.put("processor.summer_1.triggering_frequency", "1000");
    properties.put("computation.shutdown.wait_time_in_seconds", "1");
    properties.put("computation.channel.channel_type", " disruptor");
    properties.put("computation.disruptor.buffer_size", "64");
    properties.put("computation.disruptor.wait_strategy", "Yield ");

    final String sourceId = "source_1";
    final String pid1 = "summer_1";
    final String pid2 = "counter_1";
    final String pid3 = "printer_1";

    RegisteringLoader loader = RegisteringLoader.builder()
            .source("memory", new MemoryBasedPipelineStreamPipelineSource())
            .stage("printer", new PrinterStreamingProcessor()).stage("summer", new SummingProcessor())
            .stage("counter", new CountingProcessor()).build();

    ComputationSpec spec = ComputationSpec.builder().name("test-pipeline")
            .source(ComponentInstance.builder().id(sourceId)
                    .meta(ComponentMetadata.builder().type(ComponentType.SOURCE).id(sourceId).name("memory")
                            .build())//from   ww  w. j av a  2  s .  c om
                    .build())
            .processor(ComponentInstance.builder().id(pid1)
                    .meta(ComponentMetadata.builder().type(ComponentType.PROCESSOR).id(pid1).name("summer")
                            .build())
                    .build())
            .processor(ComponentInstance.builder().id(pid2)
                    .meta(ComponentMetadata.builder().type(ComponentType.PROCESSOR).id(pid2).name("counter")
                            .build())
                    .build())
            .processor(ComponentInstance.builder().id(pid3)
                    .meta(ComponentMetadata.builder().type(ComponentType.PROCESSOR).id(pid3).name("printer")
                            .build())
                    .build())
            .connection(Connection.builder().fromType(ComponentType.SOURCE).from(sourceId).to(pid1).build())
            .connection(Connection.builder().fromType(ComponentType.SOURCE).from(sourceId).to(pid2).build())
            .connection(Connection.builder().fromType(ComponentType.SOURCE).from(sourceId).to(pid3).build())
            .connection(Connection.builder().fromType(ComponentType.PROCESSOR).from(pid1).to(pid3).build())
            .connection(Connection.builder().fromType(ComponentType.PROCESSOR).from(pid2).to(pid3).build())
            .properties(properties).build();
    System.out.println(new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(spec));

    Linker linker = new Linker(loader);
    ComputationPipeline pipeline = linker.build(spec);
    pipeline.initialize(properties);

    ExecutorService executor = Executors.newSingleThreadExecutor();

    ConsoleReporter reporter = ConsoleReporter
            .forRegistry(SharedMetricRegistries.getOrCreate("metrics-registry"))
            .convertRatesTo(TimeUnit.SECONDS).convertDurationsTo(TimeUnit.MILLISECONDS).build();
    reporter.start(1, TimeUnit.SECONDS);
    executor.submit(pipeline::start);
    Thread.sleep(2000);
    pipeline.stop();
    reporter.stop();

    executor.shutdownNow();

}

From source file:acromusashi.kafka.log.producer.LinuxApacheLogProducer.java

/**
 * ????Log?Tail?/*  w  ww.j a  va  2s  . c  o  m*/
 * 
 * @param configMap ?Map
 */
protected void startTailLog(Map<String, Object> configMap) {
    String tailCommand = configMap.get("tail.command").toString();
    String tailPath = configMap.get("tail.path").toString();
    String tailCommandStr = tailCommand + " " + tailPath;
    String kafkaTopic = configMap.get("kafka.topic").toString();
    String apacheLogFormat = configMap.get("apachelog.format").toString();
    String jsonDateFormat = configMap.get("jsondate.format").toString();

    String hostname = "defaultHost";

    try {
        hostname = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException ex) {
        logger.warn("HostName resolve failed. Use default. : default=" + hostname, ex);
    }

    ProducerConfig producerConfig = ProducerConfigConverter.convertToProducerConfig(configMap);

    logger.info("Producer starting. Command=" + tailCommandStr);

    ExecutorService executorService = Executors.newSingleThreadExecutor();
    LinuxLogTailExecutor executor = new LinuxLogTailExecutor(tailCommandStr, kafkaTopic, apacheLogFormat,
            jsonDateFormat, hostname);
    executor.initialize(producerConfig);

    executorService.execute(executor);

    logger.info("Producer started");
}

From source file:com.nts.alphamale.handler.ExecutorHandler.java

public void executeSingle(Runnable rt) {
    singleExecutor = Executors.newSingleThreadExecutor();
    singleExecutor.submit(rt);
}

From source file:de.dfki.iui.mmds.scxml.engine.SCXMLEngineActivator.java

public static void sendActiveStates(final String id, final List<String> activeStates,
        final List<String> allActiveStates) {
    if (getEventAdmin() == null)
        return;/*w  ww.ja  v  a 2  s .c o m*/
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        @Override
        public void run() {
            getEventAdmin().sendEvent(new SCXMLActiveStatesEvent(id, activeStates, allActiveStates));
        }
    });
}

From source file:com.adaptris.core.DefaultFailedMessageRetrier.java

@Override
public void init() throws CoreException {
    super.init();
    failedMessageExecutor = Executors.newSingleThreadExecutor();
}