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:cn.edu.zjnu.acm.judge.service.LoginlogService.java

@PostConstruct
public void init() {
    executorService = Executors.newSingleThreadExecutor();
    executorService.submit(this::savebatch);
    executorService.shutdown();
}

From source file:com.opentable.etcd.SmokeTest.java

@Before
public void initialize() {
    backgroundThread = Executors.newSingleThreadExecutor();
    this.prefix = "/unittest-" + UUID.randomUUID().toString();

    jaxrsClient = new JaxRsClientFactory(Config.getEmptyConfig())
            .addFeatureToAllClients(JsonClientFeature.forMapper(new ObjectMapper()))
            .newClient("etcd", StandardFeatureGroup.PUBLIC);

    final EtcdClientFactory factory = new EtcdClientFactory(jaxrsClient, new ObjectMapper());
    client = factory.createClient(URI.create(server.getConnectString()));
}

From source file:org.mayocat.webhooks.Webhooks.java

public void notifyHook(final Webhook event, final Object payload) {

    WebhooksSettings hooksSettings = configurationService.getSettings(WebhooksSettings.class);
    List<Hook> hooks = FluentIterable.from(hooksSettings.getHooks().getValue()).filter(hookMatchesEvent(event))
            .toList();/*  www.  j a va 2  s . c  o m*/

    for (final Hook hook : hooks) {
        Executors.newSingleThreadExecutor().submit(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                doNotifyHook(event, hook, payload);
                return null;
            }
        });
    }
}

From source file:com.microsoft.azure.servicebus.samples.queueswithproxy.QueuesWithProxy.java

public void run(String connectionString) throws Exception {
    // Set the transport type to AmqpWithWebsockets
    ConnectionStringBuilder connStrBuilder = new ConnectionStringBuilder(connectionString, "BasicQueue");
    connStrBuilder.setTransportType(TransportType.AMQP_WEB_SOCKETS);

    // Create a QueueClient instance for receiving using the connection string builder
    // We set the receive mode to "PeekLock", meaning the message is delivered
    // under a lock and must be acknowledged ("completed") to be removed from the queue
    QueueClient receiveClient = new QueueClient(connStrBuilder, ReceiveMode.PEEKLOCK);
    // We are using single thread executor as we are only processing one message at a time
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    this.registerReceiver(receiveClient, executorService);

    // Create a QueueClient instance for sending and then asynchronously send messages.
    // Close the sender once the send operation is complete.
    QueueClient sendClient = new QueueClient(connStrBuilder, ReceiveMode.PEEKLOCK);
    this.sendMessagesAsync(sendClient).thenRunAsync(() -> sendClient.closeAsync());

    // wait for ENTER or 10 seconds elapsing
    waitForEnter(10);/*w  w w  .  j  a  v  a2s . com*/

    // shut down receiver to close the receive loop
    receiveClient.close();
    executorService.shutdown();
}

From source file:be.solidx.hot.test.data.jdbc.TestJsCollectionApi.java

@Test
public void testSync() throws Exception {
    JSScriptExecutor executor = new JSScriptExecutor();
    Map<String, Object> context = new HashMap<>();
    context.put("db", db);
    context.put("adb", new JSAsyncDB(db, Executors.newCachedThreadPool(), Executors.newSingleThreadExecutor(),
            executor.getGlobalScope()));

    executor.setGlobalScopeScripts(Arrays.asList("/js/qunit-1.14.js"));
    Script<org.mozilla.javascript.Script> script = new Script<>(
            IOUtils.toByteArray(getClass().getResourceAsStream("/be/solidx/hot/test/data/jdbc/scripts/db.js")),
            "db.js");
    StringWriter out = new StringWriter();
    executor.execute(script, context, out);

    Assert.assertFalse(out.toString().contains("FAIL"));
}

From source file:be.solidx.hot.test.data.jdbc.TestJsAsyncCollectionApi.java

@Test
public void testAsync() throws Exception {
    JSScriptExecutor executor = new JSScriptExecutor();
    Map<String, Object> context = new HashMap<>();
    context.put("db", db);
    context.put("adb", new JSAsyncDB(db, Executors.newCachedThreadPool(), Executors.newSingleThreadExecutor(),
            executor.getGlobalScope()));

    executor.setGlobalScopeScripts(Arrays.asList("/js/qunit-1.14.js"));
    Script<org.mozilla.javascript.Script> script = new Script<>(
            IOUtils.toByteArray(//from ww  w.  j  a v a2s  . c o  m
                    getClass().getResourceAsStream("/be/solidx/hot/test/data/jdbc/scripts/async-db.js")),
            "async-db.js");
    StringWriter out = new StringWriter();
    executor.execute(script, context, out);
    System.out.println(out.toString());
    Assert.assertFalse(out.toString().contains("FAIL"));
}

From source file:com.bbytes.jfilesync.sync.ftp.FTPClientFactory.java

/**
 * Get {@link FTPClient} with initialized connects to server given in properties file
 * @return/*from  ww w .j a  v  a  2  s. c  o  m*/
 */
public FTPClient getClientInstance() {

    ExecutorService ftpclientConnThreadPool = Executors.newSingleThreadExecutor();
    Future<FTPClient> future = ftpclientConnThreadPool.submit(new Callable<FTPClient>() {

        FTPClient ftpClient = new FTPClient();

        boolean connected;

        public FTPClient call() throws Exception {

            try {
                while (!connected) {
                    try {
                        ftpClient.connect(host, port);
                        if (!ftpClient.login(username, password)) {
                            ftpClient.logout();
                        }
                        connected = true;
                        return ftpClient;
                    } catch (Exception e) {
                        connected = false;
                    }

                }

                int reply = ftpClient.getReplyCode();
                // FTPReply stores a set of constants for FTP reply codes.
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftpClient.disconnect();
                }

                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            return ftpClient;
        }
    });

    FTPClient ftpClient = new FTPClient();
    try {
        // wait for 100 secs for acquiring conn else terminate
        ftpClient = future.get(100, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        log.info("FTP client Conn wait thread terminated!");
    } catch (InterruptedException e) {
        log.error(e.getMessage(), e);
    } catch (ExecutionException e) {
        log.error(e.getMessage(), e);
    }

    ftpclientConnThreadPool.shutdownNow();
    return ftpClient;

}

From source file:com.echopf.ECHOQuery.java

/**
 * Does Find objects from the remote server.
 * @param sync : if set TRUE, then the main (UI) thread is waited for complete the finding in a background thread. 
 *              (a synchronous communication)
 * @param listKey the key associated with the object list
 * @param clazz the object class//from  w  w  w.j av  a 2 s . co  m
 * @param callback invoked after the finding is completed
 * @param instanceId the reference ID of the finding target instance
 * @param resourceType the type of this object
 * @param params to control the output objects
 * @throws ECHOException
 */
public static <T extends ECHODataObject<T>> ECHOList<T> doFind(final boolean sync, final String listKey,
        final String resourceType, final FindCallback<T> callback, final String instanceId,
        final JSONObject fParams, final ECHODataObjectFactory<T> factory) throws ECHOException {

    // Get ready a background thread
    final Handler handler = new Handler();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<ECHOList<T>> communicator = new Callable<ECHOList<T>>() {
        @Override
        public ECHOList<T> call() throws ECHOException {
            ECHOException exception = null;
            ECHOList<T> objList = null;

            try {
                JSONObject response = getRequest(instanceId + "/" + resourceType, fParams);

                /* begin copying data */
                objList = new ECHOList<T>(response.optJSONObject("paginate"));

                JSONArray items = response.optJSONArray(listKey);
                if (items == null)
                    throw new ECHOException(0, "Invalid data type for response-field `" + listKey + "`.");

                for (int i = 0; i < items.length(); i++) {
                    JSONObject item = items.optJSONObject(i);
                    if (item == null)
                        throw new ECHOException(0, "Invalid data type for response-field `" + listKey + "`.");

                    String refid = item.optString("refid");
                    if (refid.isEmpty())
                        continue;

                    T obj = factory.create(instanceId, refid, item);
                    objList.add(obj);
                }
                /* end copying 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;
                    final ECHOList<T> fObjList = objList;

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.done(fObjList, fException);
                        }
                    });
                }

                return null;

            } else {

                if (exception == null)
                    return objList;
                throw exception;

            }
        }
    };

    Future<ECHOList<T>> future = executor.submit(communicator);

    if (sync) {
        try {
            return 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);
        }
    }

    return null;
}

From source file:oz.hadoop.yarn.api.utils.MiniClusterUtils.java

public static void startMiniCluster() {
    try {/*  w w w  . j a  v  a 2  s  .  c  om*/
        semaphore.acquire();
    } catch (InterruptedException e) {
        throw new IllegalStateException("Acquisition of semaphore is interrupted. Exiting");
    }
    if (clusterLauncher != null) {
        throw new IllegalStateException("MiniClustrer is currently running");
    }
    File file = new File("");
    Path path = Paths.get(file.getAbsolutePath());

    Path parentPath = path.getParent();

    File clusterConfiguration = new File(parentPath + "/yarn-test-cluster/src/main/resources");
    Assert.isTrue(clusterConfiguration.exists());
    ConfigUtils.addToClasspath(clusterConfiguration);

    File miniClusterExe = new File(
            parentPath.toString() + "/yarn-test-cluster/build/install/yarn-test-cluster/bin/yarn-test-cluster");
    System.out.println(miniClusterExe.getAbsolutePath());
    if (!miniClusterExe.exists()) {
        logger.info("BUILDING MINI_CLUSTER");
        CommandProcessLauncher buildLauncher = new CommandProcessLauncher(
                path.toString() + "/build-mini-cluster");
        buildLauncher.launch();
    }
    Assert.isTrue(miniClusterExe.exists(), "Failed to find mini-cluster executable");
    clusterLauncher = new CommandProcessLauncher(miniClusterExe.getAbsolutePath());
    executor = Executors.newSingleThreadExecutor();
    executor.execute(new Runnable() {
        @Override
        public void run() {
            logger.info("STARTING MINI_CLUSTER");
            clusterLauncher.launch();
            System.out.println("EXITING>>>>>>>>>");
        }
    });
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}

From source file:com.tangrainc.inappbilling.InAppBillingHelper.java

public InAppBillingHelper(Context context, String[] productIdentifiers) {
    _executor = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());
    _productIdentifiers = productIdentifiers;
    _context = context;/*ww w .j  a  v  a 2  s .c o  m*/
    ServiceConnection _serviceConn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "Billing Service disconnected.");
            _service = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "Billing Service connected.");
            _service = IInAppBillingService.Stub.asInterface(service);
        }
    };

    Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
    serviceIntent.setPackage("com.android.vending");
    _context.bindService(serviceIntent, _serviceConn, Context.BIND_AUTO_CREATE);
}