Example usage for java.util.concurrent Executors newFixedThreadPool

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

Introduction

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

Prototype

public static ExecutorService newFixedThreadPool(int nThreads) 

Source Link

Document

Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue.

Usage

From source file:org.alfresco.contentstore.AbstractContentStore.java

public void init() {
    if (isAsync != null && !isAsync.isEmpty()) {
        this.async = Boolean.valueOf(isAsync);
    }/*from   ww w .  j ava2 s.  c om*/

    this.contentRoot = TempFileProvider.getTempDir("RepoContentStore").getAbsolutePath();
    logger.info("ContentStore root directory " + contentRoot);

    this.executor = Executors.newFixedThreadPool(5);
}

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 */
    /*/* w  w  w .j ava2 s.  c om*/
     * 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.futureplatforms.kirin.extensions.databases.DatabasesBackend.java

public DatabasesBackend(Context context) {
    this(context, null, null, Executors.newCachedThreadPool(), Executors.newFixedThreadPool(1));
}

From source file:com.espertech.esper.multithread.TestMTStmtNamedWindowUpdate.java

private void trySend(int numThreads, int numEventsPerThread) throws Exception {
    Configuration config = SupportConfigFactory.getConfiguration();
    config.addEventType("SupportBean", SupportBean.class);
    engine = EPServiceProviderManager.getDefaultProvider(config);
    engine.initialize();//from   ww  w  .ja  v  a  2 s.  co  m

    // setup statements
    engine.getEPAdministrator().createEPL(
            "create window MyWindow.std:unique(theString, intPrimitive) as select * from SupportBean");
    engine.getEPAdministrator()
            .createEPL("insert into MyWindow select * from SupportBean(boolPrimitive = true)");
    engine.getEPAdministrator().createEPL("on SupportBean(boolPrimitive = false) sb "
            + "update MyWindow win set intBoxed = win.intBoxed + 1, doublePrimitive = win.doublePrimitive + sb.doublePrimitive"
            + " where sb.theString = win.theString and sb.intPrimitive = win.intPrimitive");

    // send primer events, initialize totals
    Map<MultiKeyUntyped, UpdateTotals> totals = new HashMap<MultiKeyUntyped, UpdateTotals>();
    for (int i = 0; i < NUM_STRINGS; i++) {
        for (int j = 0; j < NUM_INTS; j++) {
            SupportBean primer = new SupportBean(Integer.toString(i), j);
            primer.setBoolPrimitive(true);
            primer.setIntBoxed(0);
            primer.setDoublePrimitive(0);

            engine.getEPRuntime().sendEvent(primer);
            MultiKeyUntyped key = new MultiKeyUntyped(primer.getTheString(), primer.getIntPrimitive());
            totals.put(key, new UpdateTotals(0, 0));
        }
    }

    // execute
    long startTime = System.currentTimeMillis();
    ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
    Future<StmtNamedWindowUpdateCallable.UpdateResult> future[] = new Future[numThreads];
    for (int i = 0; i < numThreads; i++) {
        future[i] = threadPool
                .submit(new StmtNamedWindowUpdateCallable("Thread" + i, engine, numEventsPerThread));
    }

    threadPool.shutdown();
    threadPool.awaitTermination(10, TimeUnit.SECONDS);
    long endTime = System.currentTimeMillis();

    // total up result
    long deltaCumulative = 0;
    for (int i = 0; i < numThreads; i++) {
        StmtNamedWindowUpdateCallable.UpdateResult result = future[i].get();
        deltaCumulative += result.getDelta();
        for (StmtNamedWindowUpdateCallable.UpdateItem item : result.getUpdates()) {
            MultiKeyUntyped key = new MultiKeyUntyped(item.getTheString(), item.getIntval());
            UpdateTotals total = totals.get(key);
            if (total == null) {
                throw new RuntimeException("Totals not found for key " + key);
            }
            total.setNum(total.getNum() + 1);
            total.setSum(total.getSum() + item.getDoublePrimitive());
        }
    }

    // compare
    EventBean[] rows = engine.getEPRuntime().executeQuery("select * from MyWindow").getArray();
    assertEquals(rows.length, totals.size());
    long totalUpdates = 0;
    for (EventBean row : rows) {
        UpdateTotals total = totals.get(new MultiKeyUntyped(row.get("theString"), row.get("intPrimitive")));
        assertEquals(total.getNum(), row.get("intBoxed"));
        assertEquals(total.getSum(), row.get("doublePrimitive"));
        totalUpdates += total.getNum();
    }

    assertEquals(totalUpdates, numThreads * numEventsPerThread);
    //long deltaTime = endTime - startTime;
    //System.out.println("Totals updated: " + totalUpdates + "  Delta cumu: " + deltaCumulative + "  Delta pooled: " + deltaTime);
}

From source file:de.berber.kindle.annotator.controller.WorkQueue.java

/**
 * Startup the executors/*w  w  w .jav a 2s.co  m*/
 */
private void start() {
    final int cpuCount = Runtime.getRuntime().availableProcessors();
    LOG.info("Starting " + cpuCount + " threads.");

    executor = Executors.newFixedThreadPool(cpuCount);
}

From source file:edu.mit.oidc.web.StatusEndpoint.java

@RequestMapping(value = "/" + URL, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String getStatus(Model m) {

    Map<String, Map<String, Object>> e = new HashMap<>();

    ExecutorService executor = Executors.newFixedThreadPool(3);

    try {//from  w  ww. java 2s .  c o  m
        List<Future<Map<String, Map<String, Object>>>> results = executor
                .invokeAll(Arrays.asList(new Callable<Map<String, Map<String, Object>>>() {
                    // get database status
                    @Override
                    public Map<String, Map<String, Object>> call() throws Exception {
                        return getDbStatus();
                    }
                }, new Callable<Map<String, Map<String, Object>>>() {
                    // get kerberos status
                    @Override
                    public Map<String, Map<String, Object>> call() throws Exception {
                        return getKerbStatus();
                    }
                }, new Callable<Map<String, Map<String, Object>>>() {
                    // get LDAP status
                    @Override
                    public Map<String, Map<String, Object>> call() throws Exception {
                        return getLdapStatus();
                    }
                }), getTimeoutSeconds(), TimeUnit.SECONDS);

        // collect all the results and return them
        for (Future<Map<String, Map<String, Object>>> result : results) {
            e.putAll(result.get());
        }

        m.addAttribute(JsonEntityView.ENTITY, e);
        return JsonEntityView.VIEWNAME;
    } catch (InterruptedException | ExecutionException ex) {

        m.addAttribute(HttpCodeView.CODE, HttpStatus.INTERNAL_SERVER_ERROR);
        m.addAttribute(JsonErrorView.ERROR_MESSAGE, ex.getMessage());

        return JsonErrorView.VIEWNAME;
    }

}

From source file:com.flipkart.foxtrot.core.querystore.actions.NonCacheableActionTest.java

@Before
public void setUp() throws Exception {
    ElasticsearchUtils.setMapper(mapper);
    DataStore dataStore = TestUtils.getDataStore();

    //Initializing Cache Factory
    hazelcastInstance = new TestHazelcastInstanceFactory(1).newHazelcastInstance();
    HazelcastConnection hazelcastConnection = Mockito.mock(HazelcastConnection.class);
    when(hazelcastConnection.getHazelcast()).thenReturn(hazelcastInstance);
    CacheUtils.setCacheFactory(new DistributedCacheFactory(hazelcastConnection, mapper));

    elasticsearchServer = new MockElasticsearchServer(UUID.randomUUID().toString());
    ElasticsearchConnection elasticsearchConnection = Mockito.mock(ElasticsearchConnection.class);
    when(elasticsearchConnection.getClient()).thenReturn(elasticsearchServer.getClient());
    ElasticsearchUtils.initializeMappings(elasticsearchServer.getClient());

    // Ensure that table exists before saving/reading data from it
    TableMetadataManager tableMetadataManager = Mockito.mock(TableMetadataManager.class);
    when(tableMetadataManager.exists(TestUtils.TEST_TABLE_NAME)).thenReturn(true);
    when(tableMetadataManager.get(anyString())).thenReturn(TestUtils.TEST_TABLE);
    QueryStore queryStore = new ElasticsearchQueryStore(tableMetadataManager, elasticsearchConnection,
            dataStore);/*from   w  w  w .  ja v a  2 s.com*/
    AnalyticsLoader analyticsLoader = new AnalyticsLoader(tableMetadataManager, dataStore, queryStore,
            elasticsearchConnection);
    TestUtils.registerActions(analyticsLoader, mapper);
    ExecutorService executorService = Executors.newFixedThreadPool(1);
    queryExecutor = new QueryExecutor(analyticsLoader, executorService);
    queryStore.save(TestUtils.TEST_TABLE_NAME, TestUtils.getQueryDocuments(mapper));
}

From source file:com.dtstack.jlogstash.inputs.Netty.java

@Override
public void prepare() {
    // TODO Auto-generated method stub
    if (StringUtils.isNotBlank(whiteListPath)) {
        if (executors == null) {
            synchronized (Netty.class) {
                if (executors == null) {
                    whiteIpTask = new WhiteIpTask(whiteListPath, whiteList);
                    executors = Executors.newFixedThreadPool(1);
                    executors.execute(whiteIpTask);
                }/*ww w .j  av a  2 s. com*/
            }
        }
    }
}

From source file:com.amazonaws.services.kinesis.aggregators.datastore.DynamoQueryEngine.java

public List<TableKeyStructure> parallelQueryKeys(QueryKeyScope scope, int threads) throws Exception {
    List<ParallelKeyScanWorker> workers = new ArrayList<>();
    Collection<Future<?>> workerStatus = new ArrayList<>();
    List<TableKeyStructure> output = new ArrayList<>();
    int totalResultsProcessed = 0;

    // set up the executor thread pool
    ExecutorService executor = Executors.newFixedThreadPool(threads);

    // create workers for each segment that we need to do queries against
    for (int i = 0; i < threads; i++) {
        ParallelKeyScanWorker worker = new ParallelKeyScanWorker(this.tableName, i, threads, scope,
                this.labelAttribute, this.dateAttribute);
        workers.add(worker);/*w w  w.  jav  a2  s.  c  o m*/
        workerStatus.add(executor.submit(worker));
    }

    for (Future<?> f : workerStatus) {
        f.get();
    }
    executor.shutdown();

    for (ParallelKeyScanWorker w : workers) {
        // throw any exceptions the worker incurred
        w.throwExceptions();

        if (w.getResultCount() > 0) {
            output.addAll(w.getOutput());
        }

        totalResultsProcessed += w.getResultsProcessed();
    }

    LOG.info(String.format("Key Extraction Complete - Processed %s Key Items", totalResultsProcessed));

    return output;
}

From source file:io.hops.erasure_coding.ReedSolomonDecoder.java

@Override
protected long fixErasedBlockImpl(FileSystem fs, Path srcFile, FileSystem parityFs, Path parityFile,
        boolean fixSource, long blockSize, long errorOffset, long limit, boolean partial, OutputStream out,
        Progressable reporter, CRC32 crc) throws IOException {
    if (partial) {
        throw new IOException("We don't support partial reconstruction");
    }/* w  w  w .j a  v a  2 s . c om*/
    FSDataInputStream[] inputs = new FSDataInputStream[stripeSize + paritySize];
    int[] erasedLocations = buildInputs(fs, srcFile, parityFs, parityFile, fixSource, errorOffset, inputs);
    int erasedLocationToFix;
    if (fixSource) {
        int blockIdxInStripe = ((int) (errorOffset / blockSize)) % stripeSize;
        erasedLocationToFix = paritySize + blockIdxInStripe;
    } else {
        // generate the idx for parity fixing.
        int blockIdxInStripe = ((int) (errorOffset / blockSize)) % paritySize;
        erasedLocationToFix = blockIdxInStripe;
    }

    // Allows network reads to go on while decode is going on.
    int boundedBufferCapacity = 2;
    parallelDecoder = Executors.newFixedThreadPool(parallelism);
    ParallelStreamReader parallelReader = new ParallelStreamReader(reporter, inputs, bufSize, parallelism,
            boundedBufferCapacity, blockSize);
    parallelReader.start();
    decodeTime = 0;
    waitTime = 0;
    try {
        return writeFixedBlock(inputs, erasedLocations, erasedLocationToFix, limit, out, reporter,
                parallelReader, crc);
    } finally {
        // Inputs will be closed by parallelReader.shutdown().
        parallelReader.shutdown();
        LOG.info("Time spent in read " + parallelReader.readTime + ", decode " + decodeTime + " wait "
                + waitTime);
        parallelDecoder.shutdownNow();
    }
}