Example usage for java.util.concurrent ExecutorService submit

List of usage examples for java.util.concurrent ExecutorService submit

Introduction

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

Prototype

Future<?> submit(Runnable task);

Source Link

Document

Submits a Runnable task for execution and returns a Future representing that task.

Usage

From source file:com.rti.motorcontrolpub.MotorControlMainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_motor_control_main);

    /* Uncomment this to turn on additional logging */
    /*/*from   w w  w  . j a  va2 s.com*/
     * Logger.get_instance().set_verbosity_by_category(
     * LogCategory.NDDS_CONFIG_LOG_CATEGORY_API,
     * LogVerbosity.NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
     */
    // Log.i(TAG, "calling publisherMain");
    // Starting DDS subscriber as separate threaded task...
    if (MotorControlPublisher.Pub_sub_create_count == 1) {
        ExecutorService service = Executors.newFixedThreadPool(4);
        service.submit(new Runnable() {
            @Override
            public void run() {
                String[] args = { "0" };// {"0", "0"};
                MotorControlPublisher.main(args);
            }
        });
        MotorControlPublisher.Pub_sub_create_count = 0;

    }

    final Button StartBtn = (Button) findViewById(R.id.btnSubmit);
    StartBtn.setOnClickListener(new OnClickListener() {
        final Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
        final Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);
        final Spinner spinner3 = (Spinner) findViewById(R.id.spinner3);
        final Spinner spinner4 = (Spinner) findViewById(R.id.spinner4);

        // Do click handling here
        public void onClick(View view) {
            MotorControlPublisher.flagBtn = true;
            spinner1.setEnabled(true);
            spinner2.setEnabled(true);
            spinner3.setEnabled(true);
            spinner4.setEnabled(true);

            if (spinner1.getSelectedItem().toString().equals("Green")) {
                MotorControlMainActivity.mMotor_id = "1";
            }
            if (spinner1.getSelectedItem().toString().equals("Yellow")) {
                MotorControlMainActivity.mMotor_id = "2";
            }
            if (spinner1.getSelectedItem().toString().equals("Both")) {
                MotorControlMainActivity.mMotor_id = "3";
            }

            MotorControlMainActivity.mTime_sec = Integer.valueOf(spinner2.getSelectedItem().toString());

            if (spinner3.getSelectedItem().toString().equals("Clock")) {
                MotorControlMainActivity.mDirection = "0";
            }
            if (spinner3.getSelectedItem().toString().equals("Anti")) {
                MotorControlMainActivity.mDirection = "1";
            }
            if (spinner3.getSelectedItem().toString().equals("Invrt")) {
                MotorControlMainActivity.mDirection = "2";
            }
            if (spinner3.getSelectedItem().toString().equals("Outvt")) {
                MotorControlMainActivity.mDirection = "3";
            }

            if (spinner4.getSelectedItem().toString().equals("Fastest")) {
                MotorControlMainActivity.mSpeed = 1;
            }
            if (spinner4.getSelectedItem().toString().equals("Faster")) {
                MotorControlMainActivity.mSpeed = 2;
            }
            if (spinner4.getSelectedItem().toString().equals("Fast")) {
                MotorControlMainActivity.mSpeed = 3;
            }
            if (spinner4.getSelectedItem().toString().equals("Slow")) {
                MotorControlMainActivity.mSpeed = 4;
            }
            if (spinner4.getSelectedItem().toString().equals("Slower")) {
                MotorControlMainActivity.mSpeed = 6;
            }
            if (spinner4.getSelectedItem().toString().equals("Slowest")) {
                MotorControlMainActivity.mSpeed = 8;
            }

            System.out.println("MotorControlPublisher.mMotor_id " + MotorControlMainActivity.mMotor_id);
            System.out.println("MotorControlPublisher.mTime_sec " + MotorControlMainActivity.mTime_sec);
            System.out.println("MotorControlPublisher.mDirection" + MotorControlMainActivity.mDirection);
            System.out.println("otorControlPublisher.mSpeed" + MotorControlMainActivity.mSpeed);

            // code for Web DDS HTTP POST //

            final DefaultHttpClient httpClient = new DefaultHttpClient();
            httpClient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE);
            httpClient.getParams().getParameter("http.protocol.version");

            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    // replace with your url
                    StringEntity se = null;
                    httppost = new HttpPost(
                            "http://87.82.193.136:8080/dds/rest1/applications/LED_Demo/participants/LEDs/publishers/MyPublisher/datawriters/MyMCWriter");
                    try {
                        se = new StringEntity("<MotorControl><motor_id>" + MotorControlMainActivity.mMotor_id
                                + "</motor_id><time_sec>" + MotorControlMainActivity.mTime_sec
                                + "</time_sec><direction>" + MotorControlMainActivity.mDirection
                                + "</direction><speed>" + MotorControlMainActivity.mSpeed
                                + "</speed><action>0</action></MotorControl>", "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    //System.out.println("POST: " + se);
                    se.setContentType("application/webdds+xml");
                    httppost.addHeader("Cache-Control", "no-cache");

                    httppost.setEntity(se);
                    try {
                        httpClient.execute(httppost);
                    }

                    catch (ClientProtocolException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            });
            t.start();

            final TextView mTextField = (TextView) findViewById(R.id.textView4);

            new CountDownTimer(MotorControlMainActivity.mTime_sec * 1000, 1000) {

                public void onTick(long millisUntilFinished) {
                    StartBtn.setEnabled(false);
                    spinner1.setEnabled(false);
                    spinner2.setEnabled(false);
                    spinner3.setEnabled(false);
                    spinner4.setEnabled(false);

                    mTextField.setText("Finishing in: " + millisUntilFinished / 1000 + " secs");
                }

                public void onFinish() {
                    // MotorControlPublisher.flagBtn = false;
                    mTextField.setText("               ");
                    StartBtn.setEnabled(true);
                    spinner1.setEnabled(true);
                    spinner2.setEnabled(true);
                    spinner3.setEnabled(true);
                    spinner4.setEnabled(true);

                    if (spinner1.getSelectedItem().toString().equals("Green")) {
                        MotorControlMainActivity.mMotor_id = "1";
                    }
                    if (spinner1.getSelectedItem().toString().equals("Yellow")) {
                        MotorControlMainActivity.mMotor_id = "2";
                    }
                    if (spinner1.getSelectedItem().toString().equals("Both")) {
                        MotorControlMainActivity.mMotor_id = "3";
                    }

                    MotorControlMainActivity.mTime_sec = Integer.valueOf(spinner2.getSelectedItem().toString());

                    if (spinner3.getSelectedItem().toString().equals("Clock")) {
                        MotorControlMainActivity.mDirection = "0";
                    }

                    if (spinner3.getSelectedItem().toString().equals("Anti")) {
                        MotorControlMainActivity.mDirection = "1";
                    }

                    if (spinner3.getSelectedItem().toString().equals("Invrt")) {
                        MotorControlMainActivity.mDirection = "2";
                    }

                    if (spinner3.getSelectedItem().toString().equals("Outvt")) {
                        MotorControlMainActivity.mDirection = "3";
                    }

                    if (spinner4.getSelectedItem().toString().equals("Fastest")) {
                        MotorControlMainActivity.mSpeed = 1;
                    }
                    if (spinner4.getSelectedItem().toString().equals("Faster")) {
                        MotorControlMainActivity.mSpeed = 2;
                    }
                    if (spinner4.getSelectedItem().toString().equals("Fast")) {
                        MotorControlMainActivity.mSpeed = 3;
                    }
                    if (spinner4.getSelectedItem().toString().equals("Slow")) {
                        MotorControlMainActivity.mSpeed = 4;
                    }
                    if (spinner4.getSelectedItem().toString().equals("Slower")) {
                        MotorControlMainActivity.mSpeed = 6;
                    }
                    if (spinner4.getSelectedItem().toString().equals("Slowest")) {
                        MotorControlMainActivity.mSpeed = 8;
                    }

                }
            }.start();

        }
    });

    /* Integration code for WebCam */

    SharedPreferences preferences = getSharedPreferences("SAVED_VALUES", MODE_PRIVATE);
    width = preferences.getInt("width", width);
    height = preferences.getInt("height", height);
    ip_ad1 = preferences.getInt("ip_ad1", ip_ad1);
    ip_ad2 = preferences.getInt("ip_ad2", ip_ad2);
    ip_ad3 = preferences.getInt("ip_ad3", ip_ad3);
    ip_ad4 = preferences.getInt("ip_ad4", ip_ad4);
    ip_port = preferences.getInt("ip_port", ip_port);
    ip_command = preferences.getString("ip_command", ip_command);

    StringBuilder sb = new StringBuilder();
    String s_http = "http://";
    String s_dot = ".";
    String s_colon = ":";
    String s_slash = "/";
    sb.append(s_http);
    sb.append(ip_ad1);
    sb.append(s_dot);
    sb.append(ip_ad2);
    sb.append(s_dot);
    sb.append(ip_ad3);
    sb.append(s_dot);
    sb.append(ip_ad4);
    sb.append(s_colon);
    sb.append(ip_port);
    sb.append(s_slash);
    sb.append(ip_command);
    URL = new String(sb);

    mv = (MjpegView) findViewById(R.id.mv);
    if (mv != null) {
        mv.setResolution(width, height);
    }

    // setTitle(R.string.title_connecting);
    /* (e.g. x.new A() where x is an instance of MjpegActivity). */
    MjpegActivity x = new MjpegActivity();

    x.new DoRead().execute(URL);
}

From source file:com.marketplace.Main.java

/**
 * Creates <code>PublisherThread</code> for each publisher found in the
 * file./*from  w  w w .  j a  va  2  s  .c  om*/
 * 
 * @return a set containing <code>PublisherThread</code>
 */
private Set<Future<?>> createPublisherThread() {
    log.info("Creating threads for fetching apps via publishers.");

    if (this.publisherFile == null) {
        System.err.println("Please pass the location of file");
        System.exit(1);
    }

    Fetcher fetcher = new Fetcher();
    ExecutorService executorService = Executors.newFixedThreadPool(22);

    Set<Future<?>> set = new HashSet<Future<?>>();
    Session[] sessions = this.sessionManager.getSessions();
    Iterator<String> pubNames = fetcher.readFile(this.publisherFile).iterator();

    for (int i = sessions.length; i > 0; i--) {
        while (pubNames.hasNext()) {
            set.add(executorService.submit(new PublisherThread(sessions[i - 1], fetcher, pubNames.next())));
        }
        pubNames = fetcher.readFile(this.publisherFile).iterator();
    }

    return set;
}

From source file:com.echopf.members.ECHOMemberQuery.java

/**
 * Does Logout//from   w ww  .j av a2 s  .c  om
 * @param sync if set TRUE, then the main (UI) thread is waited for complete the logging-out in a background thread. 
 *              (a synchronous communication)
 * @param callback invoked after the logging-out is completed
 * @param instanceId the reference ID of the instance to which the logged-out member belong
 * @throws ECHOException
 */
protected static void doLogout(final boolean sync, final ResultCallback callback, final String instanceId)
        throws ECHOException {
    final Handler handler = new Handler();

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

        @Override
        public Void call() throws ECHOException {

            ECHOException exception = null;

            try {
                ECHOQuery.postRequest(instanceId + "/login", new JSONObject());
            } 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
                        public void run() {
                            callback.done(fException);
                        }
                    });
                }

                return null;

            } else {

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

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

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

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

@Test
public void testMaxPerSession() throws Exception {
    final int CLIENT_QTY = 10;
    final int LOOP_QTY = 100;
    final Random random = new Random();
    final int SESSION_MAX = random.nextInt(75) + 25;

    List<Future<Object>> futures = Lists.newArrayList();
    ExecutorService service = Executors.newCachedThreadPool();
    final Counter counter = new Counter();
    final AtomicInteger available = new AtomicInteger(SESSION_MAX);
    for (int i = 0; i < CLIENT_QTY; ++i) {
        futures.add(service.submit(new Callable<Object>() {
            @Override//w ww.ja  v  a 2s  . co  m
            public Object call() throws Exception {
                CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                        new RetryOneTime(1));
                client.start();
                try {
                    InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test",
                            SESSION_MAX);

                    for (int i = 0; i < LOOP_QTY; ++i) {
                        long start = System.currentTimeMillis();
                        int thisQty;
                        synchronized (available) {
                            if ((System.currentTimeMillis() - start) > 10000) {
                                throw new TimeoutException();
                            }
                            while (available.get() == 0) {
                                available.wait(10000);
                            }

                            thisQty = (available.get() > 1) ? (random.nextInt(available.get()) + 1) : 1;

                            available.addAndGet(-1 * thisQty);
                            Assert.assertTrue(available.get() >= 0);
                        }
                        Collection<Lease> leases = semaphore.acquire(thisQty, 10, TimeUnit.SECONDS);
                        Assert.assertNotNull(leases);
                        try {
                            synchronized (counter) {
                                counter.currentCount += thisQty;
                                if (counter.currentCount > counter.maxCount) {
                                    counter.maxCount = counter.currentCount;
                                }
                            }
                            Thread.sleep(random.nextInt(25));
                        } finally {
                            synchronized (counter) {
                                counter.currentCount -= thisQty;
                            }
                            semaphore.returnAll(leases);
                            synchronized (available) {
                                available.addAndGet(thisQty);
                                available.notifyAll();
                            }
                        }
                    }
                } finally {
                    client.close();
                }
                return null;
            }
        }));
    }

    for (Future<Object> f : futures) {
        f.get();
    }

    synchronized (counter) {
        Assert.assertTrue(counter.currentCount == 0);
        Assert.assertTrue(counter.maxCount > 0);
        Assert.assertTrue(counter.maxCount <= SESSION_MAX);
        System.out.println(counter.maxCount);
    }
}

From source file:fsm.series.Series_CC.java

/**
 * Computes the 5 integrals simultaneously for increased performance.
 *
 * @param m Fourier term row//from   www.ja  v a  2s  .  co  m
 * @param n Fourier term column
 * @return double array of size 5 with indexes corresponding to integral
 * number (1-5)
 */
@Override
public double[] getIntegralValues(int m, int n) {

    double[] I = new double[5];

    //if (!integralsCalculated) {

    Callable<Double> tsk1 = () -> getI1(m, n);

    Callable<Double> tsk2 = () -> getI2(m, n);

    Callable<Double> tsk3 = () -> getI3(m, n);

    Callable<Double> tsk4 = () -> getI4(m, n);

    Callable<Double> tsk5 = () -> getI5(m, n);

    ExecutorService service;
    final Future<Double> thread1, thread2, thread3, thread4, thread5;

    service = Executors.newFixedThreadPool(5);
    thread1 = service.submit(tsk1);
    thread2 = service.submit(tsk2);
    thread3 = service.submit(tsk3);
    thread4 = service.submit(tsk4);
    thread5 = service.submit(tsk5);

    try {
        I[0] = thread1.get();
    } catch (InterruptedException | ExecutionException ex) {
        Logger.getLogger(Series_CC.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        I[1] = thread2.get();
    } catch (InterruptedException | ExecutionException ex) {
        Logger.getLogger(Series_CC.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        I[2] = thread3.get();
    } catch (InterruptedException | ExecutionException ex) {
        Logger.getLogger(Series_CC.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        I[3] = thread4.get();
    } catch (InterruptedException | ExecutionException ex) {
        Logger.getLogger(Series_CC.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        I[4] = thread5.get();
    } catch (InterruptedException | ExecutionException ex) {
        Logger.getLogger(Series_CC.class.getName()).log(Level.SEVERE, null, ex);
    }

    service.shutdownNow();
    //        } else {
    //            if (n >= m) {
    //                I[0] = I1Mat.get(m - 1, n - 1);
    //                I[1] = I2Mat.get(m - 1, n - 1);
    //                I[2] = I3Mat.get(m - 1, n - 1);
    //                I[3] = I4Mat.get(m - 1, n - 1);
    //                I[4] = I5Mat.get(m - 1, n - 1);
    //            } else {
    //                I[0] = I1Mat.get(n - 1, m - 1);
    //                I[1] = I3Mat.get(n - 1, m - 1);
    //                I[2] = I2Mat.get(n - 1, m - 1);
    //                I[3] = I4Mat.get(n - 1, m - 1);
    //                I[4] = I5Mat.get(n - 1, m - 1);
    //            }
    //        }

    return I;
}

From source file:com.adaptris.core.services.splitter.ServiceWorkerPool.java

public void warmup(final GenericObjectPool<Worker> objectPool) throws CoreException {
    ExecutorService populator = Executors
            .newCachedThreadPool(new ManagedThreadFactory(this.getClass().getSimpleName()));
    try {/*ww w. ja v  a 2 s . c  o m*/
        log.trace("Warming up {} service-workers", maxThreads);
        final List<Future<Worker>> futures = new ArrayList<>(maxThreads);

        for (int i = 0; i < maxThreads; i++) {
            futures.add(populator.submit(new Callable<Worker>() {

                @Override
                public Worker call() throws Exception {
                    return objectPool.borrowObject();
                }

            }));
        }
        for (Worker w : waitFor(futures)) {
            objectPool.returnObject(w);
        }
        log.trace("ObjectPool contains {} (active) of {} objects", objectPool.getNumActive(),
                objectPool.getNumIdle());
    } catch (Exception e) {
        throw ExceptionHelper.wrapCoreException(e);
    } finally {
        populator.shutdownNow();
    }
}

From source file:com.vmware.bdd.manager.SoftwareManagerCollector.java

private void updateVersion(AppManagerRead appManagerRead) {
    String softMgrVersion = "UNKNOWN";

    final SoftwareManager softwareManager = this.getSoftwareManager(appManagerRead.getName());
    // fork a child thread to do the actual connecting action
    // this is to avoid the time out issue for the socket connection when the target host is shutdown
    ExecutorService exec = Executors.newFixedThreadPool(1);
    Future<String> futureResult = exec.submit(new Callable<String>() {
        @Override//from   w  w w. j av  a 2 s.co  m
        public String call() throws Exception {
            // TODO Auto-generated method stub
            return softwareManager.getVersion();
        }
    });

    String result = (String) CommonUtil.waitForThreadResult(futureResult, waitTimeForAppMgrConn);
    if (null != result) {
        softMgrVersion = result;
    }
    exec.shutdown();

    appManagerRead.setVersion(softMgrVersion);
}

From source file:com.netflix.dyno.queues.redis.RedisDynoQueue.java

private <R> R executeWithRetry(ExecutorService es, Callable<R> r, int retryCount) {

    try {//from  ww w.ja v  a  2 s .  co  m

        return es.submit(r).get(1, TimeUnit.MINUTES);

    } catch (ExecutionException e) {

        if (e.getCause() instanceof DynoException) {
            if (retryCount < this.retryCount) {
                return executeWithRetry(es, r, ++retryCount);
            }
        }
        throw new RuntimeException(e.getCause());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.netflix.curator.framework.recipes.queue.TestDistributedQueue.java

@Test
public void testSimple() throws Exception {
    final int itemQty = 10;

    DistributedQueue<TestQueueItem> queue = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();/*from w w w.j a  v a2s .c o m*/
    try {
        BlockingQueueConsumer<TestQueueItem> consumer = new BlockingQueueConsumer<TestQueueItem>(
                Mockito.mock(ConnectionStateListener.class));

        queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH).buildQueue();
        queue.start();

        QueueTestProducer producer = new QueueTestProducer(queue, itemQty, 0);

        ExecutorService service = Executors.newCachedThreadPool();
        service.submit(producer);

        int iteration = 0;
        while (consumer.size() < itemQty) {
            Assert.assertTrue(++iteration < 10);
            Thread.sleep(1000);
        }

        int i = 0;
        for (TestQueueItem item : consumer.getItems()) {
            Assert.assertEquals(item.str, Integer.toString(i++));
        }
    } finally {
        IOUtils.closeQuietly(queue);
        IOUtils.closeQuietly(client);
    }
}

From source file:com.adaptris.core.services.splitter.ServiceWorkerPool.java

/**
 * //ww w  .  jav  a2 s.  c  o m
 * @deprecated since 3.8.3 switch to commons-pool2 instead.
 */
@Deprecated
@Removal(version = "3.9.0", message = "use commons-pool2 variant instead")
public void warmup(final org.apache.commons.pool.impl.GenericObjectPool<Worker> objectPool)
        throws CoreException {
    logDeprecationWarning();
    ExecutorService populator = Executors
            .newCachedThreadPool(new ManagedThreadFactory(this.getClass().getSimpleName()));
    try {
        log.trace("Warming up {} service-workers", maxThreads);
        final List<Future<Worker>> futures = new ArrayList<>(maxThreads);

        for (int i = 0; i < maxThreads; i++) {
            futures.add(populator.submit(new Callable<Worker>() {

                @Override
                public Worker call() throws Exception {
                    return objectPool.borrowObject();
                }

            }));
        }
        for (Worker w : waitFor(futures)) {
            objectPool.returnObject(w);
        }
        log.trace("ObjectPool contains {} (active) of {} objects", objectPool.getNumActive(),
                objectPool.getNumIdle());

    } catch (Exception e) {
        throw ExceptionHelper.wrapCoreException(e);
    } finally {
        populator.shutdownNow();
    }
}