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:com.cisco.oss.foundation.monitoring.service.TestMultiService.java

@Ignore
@Test/*from   w  w w .ja  v  a  2 s. co m*/
public void testHistogram() {
    final int tpsTime = 10;
    final Histogram tpsHistogram = new Histogram(new SlidingTimeWindowReservoir(tpsTime, TimeUnit.SECONDS));

    ExecutorService threadPool = Executors.newFixedThreadPool(35);

    int numOfServices = 600000;

    final CountDownLatch latch = new CountDownLatch(numOfServices);

    for (int i = 0; i < numOfServices; i++) {

        final int index = i;
        threadPool.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    if (index >= 10000 & index < 15000) {
                        Thread.sleep(50);
                    } else if (index % 100 == 0) {
                        Thread.sleep(1000);
                        tpsHistogram.update(index);
                    } else if (index % 1000 == 0) {
                        Thread.sleep(15000);
                        tpsHistogram.update(index);
                    } else if (index % 2 == 0) {
                        Thread.sleep(10);
                        tpsHistogram.update(index);
                    } else {
                        Thread.sleep(50);
                        tpsHistogram.update(index);
                    }
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                if (index % 1000 == 0) {
                    int total = tpsHistogram.getSnapshot().getValues().length;
                    System.out.println("index: " + index + ", count: " + tpsHistogram.getCount()
                            + ", snapshot count: " + total);
                    int tps = total / tpsTime;
                    System.out.println("TPS: " + tps);
                }

                latch.countDown();
            }
        });
    }

    try {
        latch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

From source file:org.wso2.carbon.automation.extensions.servers.httpserver.SimpleHttpServer.java

public void start() throws IOException {
    serverSocket = new ServerSocket(port);
    params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
            getParameter(CoreConnectionPNames.SO_TIMEOUT, 60000))
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE,
                    getParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024))
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK,
                    getParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, 0) == 1)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY,
                    getParameter(CoreConnectionPNames.TCP_NODELAY, 1) == 1)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "WSO2ESB-Test-Server");
    // Configure HTTP protocol processor
    BasicHttpProcessor httpProcessor = new BasicHttpProcessor();
    httpProcessor.addInterceptor(new ResponseDate());
    httpProcessor.addInterceptor(new ResponseServer());
    httpProcessor.addInterceptor(new ResponseContent());
    httpProcessor.addInterceptor(new ResponseConnControl());
    HttpRequestHandlerRegistry registry = new HttpRequestHandlerRegistry();
    registry.register("*", requestHandler);
    // Set up the HTTP service
    httpService = new HttpService(httpProcessor, new DefaultConnectionReuseStrategy(),
            new DefaultHttpResponseFactory(), registry, params);
    listener = Executors.newSingleThreadExecutor();
    workerPool = Executors.newFixedThreadPool(getParameter("ThreadCount", 2));
    shutdown = false;/*from  w  w  w. j ava2s  .com*/
    listener.submit(new HttpListener());
}

From source file:com.yahoo.yrlhaifa.liveqa.challenge.http_operation.QuestionOperationHttpRequestSender.java

public void sendRequestsAndCollectAnswers() throws QuestionOperationException, InterruptedException {
    if (mapParticipantToAnswer.size() > 0) {
        throw new QuestionOperationException("BUG: The given map from system-id to answers is not empty.");
    }/*from  w  w  w.  j  a v a  2  s  .c  om*/

    CloseableHttpClient httpClient = HttpClients.custom().setMaxConnPerRoute(participants.size()).build();
    try {
        ExecutorService executor = Executors.newFixedThreadPool(participants.size());
        try {
            FutureRequestExecutionService requestExecutor = new FutureRequestExecutionService(httpClient,
                    executor);
            logger.info("Sending requests using request-executor...");
            sendRequestsWithRequestExecutor(requestExecutor);
            logger.info("Sending requests using request-executor - done.");
        } finally {
            try {
                executor.shutdownNow();
            } catch (RuntimeException e) {
                // TODO Add more error handling
                logger.error("Failed to shutdown executor. Program continues.", e);
            }
        }

    } finally {
        try {
            httpClient.close();
        } catch (IOException | RuntimeException e) {
            // TODO Add more error handling
            logger.error("Failed to close HTTP client. Program continues.", e);
        }
    }

    // Remove those who did not finish on time, but did write results.
    Set<Participant> didNotSucceed = new LinkedHashSet<Participant>();
    for (Participant participant : mapParticipantToAnswer.keySet()) {
        if (!(systemsSucceeded.contains(participant))) {
            didNotSucceed.add(participant);
        }
    }
    for (Participant toRemove : didNotSucceed) {
        mapParticipantToAnswer.remove(toRemove);
    }

    if (exception != null) {
        throw exception;
    }
}

From source file:fr.bmartel.android.tictactoe.GameSingleton.java

private GameSingleton(Context context) {

    this.context = context.getApplicationContext();
    this.executor = Executors.newFixedThreadPool(1);

    //queue = Volley.newRequestQueue(context.getApplicationContext());
    HttpStack hurlStack = new HurlStack() {
        @Override//  w  ww  .jav  a2s . co  m
        protected HttpURLConnection createConnection(URL url) throws IOException {
            HttpsURLConnection httpsURLConnection = (HttpsURLConnection) super.createConnection(url);
            try {
                httpsURLConnection.setSSLSocketFactory(SSLCertificateSocketFactory.getInsecure(0, null));
                httpsURLConnection.setHostnameVerifier(new AllowAllHostnameVerifier());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return httpsURLConnection;
        }
    };
    queue = Volley.newRequestQueue(context, hurlStack);

    final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);

    //load device id from shared preference
    DEVICE_ID = sharedPreferences.getString(RequestConstants.DEVICE_ID, "");
    deviceName = sharedPreferences.getString(RequestConstants.DEVICE_NAME, RequestConstants.DEFAULT_USERNAME);

    if (DEVICE_ID.equals("")) {
        //register deviceId in shared preference
        SharedPreferences.Editor editor = sharedPreferences.edit();
        DEVICE_ID = new RandomGen(DEVICE_ID_SIZE).nextString();
        editor.putString(RequestConstants.DEVICE_ID, DEVICE_ID);
        editor.commit();
    }

    JsonObjectRequest jsObjRequest = new JsonObjectRequest(BuildConfig.APP_ROUTE + "/connect",
            RequestBuilder.buildConnectionRequest(DEVICE_ID, deviceName), new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    Log.i(TAG, "response received connect : " + response.toString());
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO Auto-generated method stub
                    error.printStackTrace();
                }
            });
    jsObjRequest.setShouldCache(false);

    queue.add(jsObjRequest);

    Log.i(TAG, "device id " + DEVICE_ID + " initialized");

    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(context, RegistrationIntentService.class);
        context.startService(intent);
    }
}

From source file:br.prof.salesfilho.oci.service.BodyWomanNudeClassifier.java

public void tClassify() {

    long startTime;
    long endTime;
    double totalTime = 0;

    EuclidianClassifier chestWorker;//w w  w  .ja  v  a2s  .c  o  m
    EuclidianClassifier buttockWorker;
    EuclidianClassifier genitalWorker;

    ClassificationResult classificationResult;
    ExecutorService executor;

    bodyWomanDescriptorService.openDatabase(new File(this.databaseName));

    BodyPartDescriptor nudeChestDescriptor = bodyWomanDescriptorService
            .findNudeBodyPartDescriptorByName("Chest");
    BodyPartDescriptor notNudeChestDescriptor = bodyWomanDescriptorService
            .findNotNudeBodyPartDescriptorByName("Chest");

    BodyPartDescriptor nudeButtockDescriptor = bodyWomanDescriptorService
            .findNudeBodyPartDescriptorByName("Buttock");
    BodyPartDescriptor notNudeButtockDescriptor = bodyWomanDescriptorService
            .findNotNudeBodyPartDescriptorByName("Buttock");

    BodyPartDescriptor nudeGenitalDescriptor = bodyWomanDescriptorService
            .findNudeBodyPartDescriptorByName("Genital");
    BodyPartDescriptor notNudeGenitalDescriptor = bodyWomanDescriptorService
            .findNotNudeBodyPartDescriptorByName("Genital");

    fileList = OCIUtils.getImageFiles(this.inputDir);

    List<EuclidianClassifier> classifiers = new ArrayList();

    for (String imagePath : fileList) {
        startTime = System.currentTimeMillis();

        try {
            System.out.println(
                    "-------------------------------------------------------------------------------------");
            System.out.println("Classifying image...: ".concat(imagePath));
            System.out.println(
                    "-------------------------------------------------------------------------------------");

            BufferedImage img = ImageIO.read(new File(imagePath));
            ImageProcessor imageProcessor = new ImageProcessor(img);
            imageProcessorService = new ImageProcessorService(imageProcessor);
            List<BufferedImage> partImageList = imageProcessorService.getSubImages(128);

            //Create new thread pool to each image file
            executor = Executors.newFixedThreadPool(10);
            for (BufferedImage subImg : partImageList) {

                chestWorker = new EuclidianClassifier(nudeChestDescriptor, notNudeChestDescriptor, subImg,
                        this.kernelSize);
                chestWorker.setClassificationLevel(this.classificationLevel);
                executor.execute(chestWorker);
                classifiers.add(chestWorker);

                buttockWorker = new EuclidianClassifier(nudeButtockDescriptor, notNudeButtockDescriptor, subImg,
                        this.kernelSize);
                buttockWorker.setClassificationLevel(this.classificationLevel);
                executor.execute(buttockWorker);
                classifiers.add(buttockWorker);

                genitalWorker = new EuclidianClassifier(nudeGenitalDescriptor, notNudeGenitalDescriptor, subImg,
                        this.kernelSize);
                genitalWorker.setClassificationLevel(this.classificationLevel);
                executor.execute(genitalWorker);
                classifiers.add(genitalWorker);
            }
            //Wait finish
            executor.shutdown();
            while (!executor.isTerminated()) {
            }

            classificationResult = printResult(classifiers);
            classificationResult.setFileName(imagePath);

            endTime = System.currentTimeMillis();

            classificationResult.setExecutionTime(endTime - startTime);
            classificationResults.add(classificationResult);

            classifiers.clear();

        } catch (IOException ex) {
            Logger.getLogger(BodyWomanNudeClassifier.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
    System.out.println("--------------------------------------------------------");
    System.out.println("Total time.: " + (totalTime) + " ms.");
    System.out.println("--------------------------------------------------------");
}

From source file:org.yamj.core.service.ScanningScheduler.java

@Scheduled(initialDelay = 5000, fixedDelay = 45000)
public void scanMediaData() throws Exception {
    int maxThreads = configService.getIntProperty("yamj3.scheduler.mediadatascan.maxThreads", 1);
    if (maxThreads <= 0) {
        if (!messageDisabledMediaData) {
            messageDisabledMediaData = Boolean.TRUE;
            LOG.info("Media data scanning is disabled");
        }/*ww w .j  ava 2 s  . c  om*/
        return;
    } else {
        messageDisabledMediaData = Boolean.FALSE;
    }

    int maxResults = configService.getIntProperty("yamj3.scheduler.mediadatascan.maxResults", 20);
    List<QueueDTO> queueElements = metadataStorageService.getMediaQueueForScanning(maxResults);
    if (CollectionUtils.isEmpty(queueElements)) {
        LOG.debug("No media data found to scan");
        return;
    }

    LOG.info("Found {} media data objects to process; scan with {} threads", queueElements.size(), maxThreads);
    BlockingQueue<QueueDTO> queue = new LinkedBlockingQueue<QueueDTO>(queueElements);

    ExecutorService executor = Executors.newFixedThreadPool(maxThreads);
    for (int i = 0; i < maxThreads; i++) {
        PluginMetadataRunner worker = new PluginMetadataRunner(queue, pluginMetadataService);
        executor.execute(worker);
    }
    executor.shutdown();

    // run until all workers have finished
    while (!executor.isTerminated()) {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException ignore) {
        }
    }

    LOG.debug("Finished media data scanning");
}