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:org.couch4j.http.DatabaseChangeNotificationService.java

private void receiveChangeNotifications() {
    if (receivingChangeNotifications) {
        return;/*from  w  w  w  . j  av a  2 s . c o m*/
    }
    logger.info("[" + Thread.currentThread().getName() + "] Start receiveChangeNotifications()...");

    receivingChangeNotifications = true;
    executor = Executors.newSingleThreadExecutor();
    Runnable r = new Runnable() {
        private void streamChanges(int updateSeq) {
            if (!receivingChangeNotifications) {
                return;
            }
            // Do we need the "heartbeat" param?
            HttpGet method = new HttpGet(urlResolver.urlForPath("_changes", map("feed", "continuous", "style",
                    "all_docs", "since", String.valueOf(updateSeq), "heartbeat", "5000")));

            HttpResponse response = null;
            HttpEntity entity = null;
            try {
                // int statusCode = client.executeMethod(method);
                response = client.execute(method);
                entity = response.getEntity();
                // Read the response body.
                Reader in = new InputStreamReader(entity.getContent(), EntityUtils.getContentCharSet(entity));

                Scanner s = new Scanner(in).useDelimiter("\n");
                String line;
                while (s.hasNext() && null != (line = s.next())) {
                    // dispatch change event
                    if (line.length() > 1 && JSONUtils.mayBeJSON(line)) {
                        JSONObject json = JSONObject.fromObject(line);
                        if (json.has("seq")) {
                            if (logger.isLoggable(Level.FINE)) {
                                logger.fine("Dispatch new change event: " + line);
                            }
                            dispatchEvent(new DatabaseChangeEvent(json));
                        } else if (json.has("last_seq")) {
                            if (logger.isLoggable(Level.FINE)) {
                                logger.fine("CouchDB server closed _changes connection. Reconnecting...");
                            }
                            streamChanges(json.getInt("last_seq"));
                        }
                    }
                }
                if (logger.isLoggable(Level.FINE)) {
                    logger.fine("[" + Thread.currentThread().getName() + "] Stop receiving changes...");
                }
            } catch (IOException e) {
                throw new Couch4JException(e);
            } finally {
                if (null != entity) {
                    try {
                        entity.consumeContent();
                    } catch (IOException e) {
                        // swallow
                    }
                }
            }
        }

        public void run() {
            if (logger.isLoggable(Level.FINE)) {
                logger.fine("[" + Thread.currentThread().getName() + "] Start receiving changes... ");
            }
            // Start with current udpate seq
            int updateSeq = database.getDatabaseInfo().getUpdateSeq();
            streamChanges(updateSeq);
        }
    };
    executor.submit(r);
}

From source file:com.jdom.ajatt.viewer.util.HtmlUtil.java

public static String getRequest(Activity activity, final String url) {
    SharedPreferences prefs = activity.getSharedPreferences(CLASS_NAME, Context.MODE_PRIVATE);
    String cachedUrlContents = prefs.getString(url, null);
    String urlRetrievalTimeKey = url + ".time";
    long cachedUrlRetrievalTime = prefs.getLong(urlRetrievalTimeKey, 0L);
    long ageOfCachedData = System.currentTimeMillis() - cachedUrlRetrievalTime;
    if (cachedUrlRetrievalTime == 0) {
        Log.d(CLASS_NAME, "Did not find cached data for URL [" + url + "].");
    } else {//  w w w  .  ja  v a  2 s. com
        Log.d(CLASS_NAME, "URL [" + url + "] has been cached for [" + ageOfCachedData + "] ms.");
    }

    Future<String> result = null;

    boolean expired = ageOfCachedData > CACHE_URL_MILLISECONDS;

    if (expired) {
        Log.d(CLASS_NAME, "URL [" + url + "] data is stale.");
    } else {
        long timeRemainingValidCache = CACHE_URL_MILLISECONDS - ageOfCachedData;
        Log.d(CLASS_NAME,
                "URL [" + url + "] data has [" + timeRemainingValidCache + "] ms of validity remaining.");
    }

    if (cachedUrlContents == null || expired) {
        Callable<String> callable = new Callable<String>() {
            public String call() throws Exception {
                long start = System.currentTimeMillis();
                Log.d(CLASS_NAME, "Retrieving URL [" + url + "].");
                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet(url);
                try {
                    HttpResponse response = client.execute(request);
                    return HttpHelper.request(response);
                } catch (Exception ex) {
                    Log.e(CLASS_NAME, "Failure to retrieve the url!", ex);
                    return null;
                } finally {
                    Log.d(CLASS_NAME, "Retrieving URL [" + url + "] took ["
                            + (System.currentTimeMillis() - start) + "] ms to retrieve.");
                }
            }
        };

        ExecutorService executor = Executors.newSingleThreadExecutor();
        result = executor.submit(callable);
    }

    if (cachedUrlContents == null) {
        try {
            cachedUrlContents = result.get();

            Editor editor = prefs.edit();
            editor.putLong(urlRetrievalTimeKey, System.currentTimeMillis());
            editor.putString(url, cachedUrlContents);
            editor.commit();
        } catch (Exception e) {
            Log.e(CLASS_NAME, "Failure to retrieve the url!", e);
        }
    }

    return cachedUrlContents;
}

From source file:com.stimulus.archiva.incoming.IAPService.java

public void testConnection(MailboxConnection connection, IAPRunnable.IAPTestCallback testCallback) {
    Config config = Config.getConfig();/* w  w  w  . j  av  a 2  s.  c  o  m*/
    ExecutorService executor = Executors.newSingleThreadExecutor();
    IAPRunnable worker = new IAPRunnable("iap test", testCallback, connection,
            config.getMailboxConnections().getPollingIntervalSecs(), null);
    executor.execute(worker);
}

From source file:ly.count.android.api.ConnectionQueueTests.java

public void testExecutor() {
    final ExecutorService executor = Executors.newSingleThreadExecutor();
    freshConnQ.setExecutor(executor);//from  ww w.j a v a 2s  .c om
    assertSame(executor, freshConnQ.getExecutor());
}

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

public static void sendScxmlOnTransitionEvent(final String id, final TransitionTarget from,
        final TransitionTarget to, final Transition transition) {
    if (getEventAdmin() == null)
        return;//from w w w.  j a v a 2 s  .c om
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        @Override
        public void run() {
            getEventAdmin().sendEvent(new SCXMLOnTransitionEvent(id, from, to, transition));
        }
    });
}

From source file:com.ottogroup.bi.spqr.pipeline.MicroPipelineManager.java

/**
 * Initializes the micro pipeline manager
 * @param processingNodeId identifier of node this manager lives on
 * @param componentRepository reference to {@link ComponentRepository} which provides access to all {@link MicroPipelineComponent}
 * @param maxNumberOfThreads max. number of threads assigned to {@link ExecutorService} (1 = single threaded, n = fixed number of threads, other = cached thread pool)
 * @throws RequiredInputMissingException   
 *//*from   w w  w .j  a  v  a 2 s. c  o  m*/
public MicroPipelineManager(final String processingNodeId, final ComponentRepository componentRepository,
        final int maxNumberOfThreads) throws RequiredInputMissingException {

    //////////////////////////////////////////////////////////////////////////////
    // validate provided input
    if (componentRepository == null)
        throw new RequiredInputMissingException("Missing required component repository");
    if (StringUtils.isBlank(processingNodeId))
        throw new RequiredInputMissingException("Missing required processing node identifier");
    //
    //////////////////////////////////////////////////////////////////////////////

    this.processingNodeId = StringUtils.lowerCase(StringUtils.trim(processingNodeId));
    this.microPipelineFactory = new MicroPipelineFactory(this.processingNodeId, componentRepository);

    if (maxNumberOfThreads == 1)
        this.executorService = Executors.newSingleThreadExecutor();
    else if (maxNumberOfThreads > 1)
        this.executorService = Executors.newFixedThreadPool(maxNumberOfThreads);
    else
        this.executorService = Executors.newCachedThreadPool();

}

From source file:com.sixt.service.framework.registry.consul.RegistrationManager.java

public void register() {
    executorService = Executors.newSingleThreadExecutor();
    executorService.submit(this);
}

From source file:org.volkszaehler.android.JsonController.java

/**
 * A method that will execute a UrlConnect thread in the
 * given executionTime read from the globalStorage
 * @param urlConnect UrlConnect Instance that will be executed
 *///from  w ww  .  j av  a 2  s .  c o m
private void executeUrlConnect(UrlConnect urlConnect) {
    converter = null; // Delete old data
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<?> future = executor.submit(urlConnect);
    try {
        // wait for task to complete
        int timer = globalStorage.getExecutionTime();
        future.get(timer, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        errorMessage = "Timeout Exception";
    } catch (InterruptedException e) {
        errorMessage = "Interrupted Exception";
    } catch (ExecutionException e) {
        errorMessage = "Execution Exception";
    } finally {
        executor.shutdownNow(); // cleanup
    }
}

From source file:com.uber.hoodie.hive.util.HiveTestService.java

public HiveServer2 start() throws IOException {
    Preconditions.checkState(workDir != null, "The work dir must be set before starting cluster.");

    if (hadoopConf == null) {
        hadoopConf = new Configuration();
    }/*from  www.  ja  va 2 s .c o m*/

    String localHiveLocation = getHiveLocation(workDir);
    if (clean) {
        LOG.info("Cleaning Hive cluster data at: " + localHiveLocation + " and starting fresh.");
        File file = new File(localHiveLocation);
        FileUtils.deleteDirectory(file);
    }

    HiveConf serverConf = configureHive(hadoopConf, localHiveLocation);

    executorService = Executors.newSingleThreadExecutor();
    tServer = startMetaStore(bindIP, metastorePort, serverConf);

    hiveServer = startHiveServer(serverConf);

    String serverHostname;
    if (bindIP.equals("0.0.0.0")) {
        serverHostname = "localhost";
    } else {
        serverHostname = bindIP;
    }
    if (!waitForServerUp(serverConf, serverHostname, metastorePort, CONNECTION_TIMEOUT)) {
        throw new IOException("Waiting for startup of standalone server");
    }

    LOG.info("Hive Minicluster service started.");
    return hiveServer;
}

From source file:com.sixt.service.framework.kafka.messaging.KafkaFailoverIntegrationTest.java

@Test
public void manualKafkaTest() throws InterruptedException {

    ServiceProperties serviceProperties = fillServiceProperties();

    // Topics are created with 3 partitions - see docker-compose-kafkafailover-integrationtest.yml
    Topic ping = new Topic("ping");
    Topic pong = new Topic("pong");

    AtomicInteger sentMessages = new AtomicInteger(0);
    AtomicInteger sendFailures = new AtomicInteger(0);
    AtomicInteger recievedMessages = new AtomicInteger(0);

    Producer producer = new ProducerFactory(serviceProperties).createProducer();

    final AtomicBoolean produceMessages = new AtomicBoolean(true);

    // Produce messages until test tells producer to stop.
    ExecutorService producerExecutor = Executors.newSingleThreadExecutor();
    producerExecutor.submit(new Runnable() {
        @Override//www .j  a  va2s  . c  om
        public void run() {
            OrangeContext context = new OrangeContext();
            Sleeper sleeper = new Sleeper();

            while (produceMessages.get()) {
                try {

                    String key = RandomStringUtils.randomAscii(5);
                    SayHelloToCmd payload = SayHelloToCmd.newBuilder().setName(key).build();

                    Message request = Messages.requestFor(ping, pong, key, payload, context);
                    producer.send(request);
                    sentMessages.incrementAndGet();

                    sleeper.sleepNoException(1000);
                } catch (Throwable t) {
                    sendFailures.incrementAndGet();
                    logger.error("Caught exception in producer loop", t);
                }
            }
        }
    });

    Consumer consumer = consumerFactoryWithHandler(serviceProperties, SayHelloToCmd.class,
            new MessageHandler<SayHelloToCmd>() {
                @Override
                public void onMessage(Message<SayHelloToCmd> message, OrangeContext context) {
                    recievedMessages.incrementAndGet();
                }
            }).consumerForTopic(ping, new DiscardFailedMessages());

    // Wait to allow manual fiddling with Kafka. Sync with global test timeout above.
    Thread.sleep(2 * 60 * 1000);

    produceMessages.set(false);
    producer.shutdown();

    Thread.sleep(10_000);

    consumer.shutdown();

    logger.info("sentMessages: " + sentMessages.get());
    logger.info("sendFailures: " + sendFailures.get());
    logger.info("recievedMessages: " + recievedMessages.get());
}