Java Code Examples for java.util.concurrent.Executors.newFixedThreadPool()

The following are Jave code examples for showing how to use newFixedThreadPool() of the java.util.concurrent.Executors class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: ts-benchmark   File: HttpRequestTest.java   View Source Code Vote up 7 votes
public static void main(String[] args) {
	ExecutorService pool = Executors.newFixedThreadPool(50);
	for(int i=0;i<50;i++){
		pool.execute(new Runnable() {
			@Override
			public void run() {
				while(true){
					Map<String, String> data = new HashMap<String, String>();
					data.put("q", "SELECT MAX(value) FROM sensor where device_code='d_bt_0' and sensor_code='s_btg_8' and time>=1485541192230000000 and time<=1485627592230000000");
					HttpRequest.post("http://10.77.110.226:8086/query?db=ruc_test1").form(data).code();
				}
			}
		});
	}
	try {
		pool.awaitTermination(Long.MAX_VALUE,TimeUnit.DAYS);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
}
 
Example 2
Project: ditb   File: TestIdLock.java   View Source Code Vote up 7 votes
@Test
public void testMultipleClients() throws Exception {
  ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS);
  try {
    ExecutorCompletionService<Boolean> ecs =
        new ExecutorCompletionService<Boolean>(exec);
    for (int i = 0; i < NUM_THREADS; ++i)
      ecs.submit(new IdLockTestThread("client_" + i));
    for (int i = 0; i < NUM_THREADS; ++i) {
      Future<Boolean> result = ecs.take();
      assertTrue(result.get());
    }
    idLock.assertMapEmpty();
  } finally {
    exec.shutdown();
    exec.awaitTermination(5000, TimeUnit.MILLISECONDS);
  }
}
 
Example 3
Project: openjdk-jdk10   File: Bug8066652.java   View Source Code Vote up 6 votes
public static void main(String args[]) {
    ExecutorService executor = Executors.newFixedThreadPool(10);
    Callable<TimeZone> calTimeZone = () -> TimeZone.getDefault();
    List<Callable<TimeZone>> tasks = new ArrayList<>();
    for (int j = 1; j < 10; j++) {
        tasks.add(calTimeZone);
    }
    try {
        List<Future<TimeZone>> results = executor.invokeAll(tasks);
        for (Future<TimeZone> f : results) {
            TimeZone tz = f.get();
            if (! tz.getID().equals("GMT")) {
                throw new RuntimeException("wrong Time zone ID: " + tz.getID()
                        + ", It should be GMT");
            }
        }
    } catch (InterruptedException | ExecutionException e) {
        throw new RuntimeException("Execution interrupted or Execution Exception occurred", e);
    } finally {
        executor.shutdown();
    }
}
 
Example 4
Project: FlashLib   File: CvTemplateMatcher.java   View Source Code Vote up 6 votes
public static MatchResult match(Mat scene, Mat[] templs, Method method, double scaleFactor){
		
	MatchRunner[] t = new MatchRunner[templs.length];
	ExecutorService sr = Executors.newFixedThreadPool(templs.length);
	for(int i = 0; i < templs.length; i++){
		t[i] = new MatchRunner(scene,templs[i],method,scaleFactor);
		sr.execute(t[i]);
	}
	try {
		sr.shutdown();
		sr.awaitTermination(1, TimeUnit.DAYS);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	
	MatchResult best = findBestMatch(t);
	/*if(best != null){
		Imgproc.circle(scene, new Point(best.centerx +best.scaleFactor,best.centery +best.scaleFactor) ,3,new Scalar(51,51,51));
		//Imgproc.circle(scene, new Point(best.center.x ,best.center.y ) ,3,new Scalar(50,203,122));
		Imgcodecs.imwrite("/home/klein/dev/frc/test.png", scene);
	}*/
	return best;
}
 
Example 5
Project: playTorrent   File: Peer.java   View Source Code Vote up 6 votes
public Peer(String host, int port) throws ConnectException {
    mConnection = Connection.fromAddress(host, port);
    if (mConnection == null) {
        throw new ConnectException("Failed to create connection");
    }

    mConnectionListener = new Connection.ConnectionListener() {
        @Override
        public void onReceived(@NonNull byte[] received) {
            handleReceiveBytes(received);
        }
    };

    mReceiveMessageService = Executors.newFixedThreadPool(1);
    mReceivedMessageBuffer = new ArrayList<>();
}
 
Example 6
Project: openjdk-jdk10   File: LinkedBlockingDequeTest.java   View Source Code Vote up 6 votes
/**
 * offer transfers elements across Executor tasks
 */
public void testOfferInExecutor() {
    final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
    q.add(one);
    q.add(two);
    final CheckedBarrier threadsStarted = new CheckedBarrier(2);
    final ExecutorService executor = Executors.newFixedThreadPool(2);
    try (PoolCleaner cleaner = cleaner(executor)) {
        executor.execute(new CheckedRunnable() {
            public void realRun() throws InterruptedException {
                assertFalse(q.offer(three));
                threadsStarted.await();
                assertTrue(q.offer(three, LONG_DELAY_MS, MILLISECONDS));
                assertEquals(0, q.remainingCapacity());
            }});

        executor.execute(new CheckedRunnable() {
            public void realRun() throws InterruptedException {
                threadsStarted.await();
                assertSame(one, q.take());
            }});
    }
}
 
Example 7
Project: minsx-java-example   File: FixedThreadPool.java   View Source Code Vote up 6 votes
public static void main(String args[]) throws Exception {

        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);

        fixedThreadPool.execute(() -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println("-----------");
        fixedThreadPool.shutdownNow();


    }
 
Example 8
Project: athena   File: PollingAlarmProvider.java   View Source Code Vote up 6 votes
@Activate
public void activate(ComponentContext context) {
    alarmsExecutor = Executors.newScheduledThreadPool(CORE_POOL_SIZE);
    eventHandlingExecutor =
            Executors.newFixedThreadPool(CORE_POOL_SIZE,
                                         groupedThreads("onos/pollingalarmprovider",
                                                        "device-installer-%d", log));

    providerService = providerRegistry.register(this);

    deviceService.addListener(deviceListener);
    mastershipService.addListener(mastershipListener);

    if (context == null) {
        alarmPollFrequencySeconds = DEFAULT_POLL_FREQUENCY_SECONDS;
        log.info("No component configuration");
    } else {
        Dictionary<?, ?> properties = context.getProperties();
        alarmPollFrequencySeconds = getNewPollFrequency(properties, alarmPollFrequencySeconds);
    }
    scheduledTask = schedulePolling();
    log.info("Started");
}
 
Example 9
Project: api-batchupload-sample-application   File: Main.java   View Source Code Vote up 6 votes
@Override
public void run(String... args) {
    Client client = new Client.Builder()
            .setBaseUrl(baseUrl)
            .setClientId(clientId)
            .setClientSecret(clientSecret)
            .setUsername(username)
            .setPassword(password)
            .build();

    BlockingQueue<String> loanQueue = new LinkedBlockingQueue();
    ExecutorService service = Executors.newFixedThreadPool(4);

    LoanChangeWatcher watcher = new LoanChangeWatcher(client, loanFolder, loanQueue, service);

    LoanProcessor processor1 = new LoanProcessor(loanQueue, client, outputFile);
    LoanProcessor processor2 = new LoanProcessor(loanQueue, client, outputFile);
    LoanProcessor processor3 = new LoanProcessor(loanQueue, client, outputFile);

    service.submit(watcher);
    service.submit(processor1);
    service.submit(processor2);
    service.submit(processor3);
}
 
Example 10
Project: DAA_Converter   File: MAF_Streamer.java   View Source Code Vote up 5 votes
public MAF_Streamer(File queryFile, File tmpFolder, Integer chunkSize, int cores, boolean doFiltering, boolean verbose) {
	this.queryFile = queryFile;
	this.tmpFolder = tmpFolder;
	this.cores = cores;
	this.verbose = verbose;
	this.doFiltering = doFiltering;
	this.executor = Executors.newFixedThreadPool(1);
	this.chunkSize = chunkSize != null ? chunkSize : this.chunkSize;
}
 
Example 11
Project: okhttp-byte-counter   File: Crawler.java   View Source Code Vote up 5 votes
private void parallelDrainQueue(int threadCount) {
  ExecutorService executor = Executors.newFixedThreadPool(threadCount);
  for (int i = 0; i < threadCount; i++) {
    executor.execute(new NamedRunnable("Crawler %s", i) {
      @Override protected void execute() {
        try {
          drainQueue();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    });
  }
  executor.shutdown();
}
 
Example 12
Project: s-store   File: ThreadUtil.java   View Source Code Vote up 4 votes
/**
 * @param <R>
 * @param threads
 */
public static <R extends Runnable> void runNewPool(final Collection<R> threads, int max_concurrent) {
    ExecutorService pool = Executors.newFixedThreadPool(max_concurrent, factory);
    ThreadUtil.run(threads, pool, true);
}
 
Example 13
Project: hadoop   File: TestNodeStatusUpdater.java   View Source Code Vote up 4 votes
@Test
public void testConcurrentAccessToSystemCredentials(){
  final Map<ApplicationId, ByteBuffer> testCredentials = new HashMap<>();
  ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[300]);
  ApplicationId applicationId = ApplicationId.newInstance(123456, 120);
  testCredentials.put(applicationId, byteBuffer);

  final List<Throwable> exceptions = Collections.synchronizedList(new
      ArrayList<Throwable>());

  final int NUM_THREADS = 10;
  final CountDownLatch allDone = new CountDownLatch(NUM_THREADS);
  final ExecutorService threadPool = Executors.newFixedThreadPool(
      NUM_THREADS);

  final AtomicBoolean stop = new AtomicBoolean(false);

  try {
    for (int i = 0; i < NUM_THREADS; i++) {
      threadPool.submit(new Runnable() {
        @Override
        public void run() {
          try {
            for (int i = 0; i < 100 && !stop.get(); i++) {
              NodeHeartbeatResponse nodeHeartBeatResponse =
                  newNodeHeartbeatResponse(0, NodeAction.NORMAL,
                      null, null, null, null, 0);
              nodeHeartBeatResponse.setSystemCredentialsForApps(
                  testCredentials);
              NodeHeartbeatResponseProto proto =
                  ((NodeHeartbeatResponsePBImpl)nodeHeartBeatResponse)
                      .getProto();
              Assert.assertNotNull(proto);
            }
          } catch (Throwable t) {
            exceptions.add(t);
            stop.set(true);
          } finally {
            allDone.countDown();
          }
        }
      });
    }

    int testTimeout = 2;
    Assert.assertTrue("Timeout waiting for more than " + testTimeout + " " +
            "seconds",
        allDone.await(testTimeout, TimeUnit.SECONDS));
  } catch (InterruptedException ie) {
    exceptions.add(ie);
  } finally {
    threadPool.shutdownNow();
  }
  Assert.assertTrue("Test failed with exception(s)" + exceptions,
      exceptions.isEmpty());
}
 
Example 14
Project: nat-network-stream   File: DefaultHttpAdapter.java   View Source Code Vote up 4 votes
private void execute(Runnable runnable){
    if(mExecutorService==null){
        mExecutorService = Executors.newFixedThreadPool(3);
    }
    mExecutorService.execute(runnable);
}
 
Example 15
Project: url-to-google-drive   File: UploadManager.java   View Source Code Vote up 4 votes
private UploadManager() {
    executorService = Executors.newFixedThreadPool(10);
    idToTaskMap = new HashMap<>();
}
 
Example 16
Project: euphrates   File: Replicator.java   View Source Code Vote up 4 votes
private void doFullDump() {
  ExecutorService threadPoolExecutor = Executors.newFixedThreadPool(config.mysql.maxConnections);

  // create list of lists
  List<TableGroup> groups = new ArrayList<>();
  for (int i = 0; i != config.mysql.maxConnections; i++) {
    groups.add(new TableGroup());
  }

  // populate lists by using sizes
  config.tables.stream()
    .sorted((t1, t2) -> getTableSize(t2).compareTo(getTableSize(t1)))
    .forEach(t -> {
      TableGroup smallestGroup = groups.stream()
                                   .sorted((g1, g2) -> g1.getSizeInMb().compareTo(g2.getSizeInMb()))
                                   .findFirst()
                                   .get();
      smallestGroup.add(t.name);
      smallestGroup.incrementSizeInMb(getTableSize(t));
    });

  LOG.debug(String.format("Groups are %s", groups));

  try {
    // create a table copier per group
    List<Future> futures = groups.stream()
                             .map(group -> threadPoolExecutor.submit(new TableCopier(this, config.mysql, group)))
                             .collect(Collectors.toList());
    futures.stream()
      .forEach(f -> {
        try {
          f.get();
        } catch (java.util.concurrent.ExecutionException ee) {
          throw new RuntimeException(ee);
        } catch (InterruptedException ie) {
          // do nothing
        }
      });
    LOG.info("Swaping redshift tables");
    redshift.swapRedshiftTables();
    LOG.info("Done swaping redshift tables");
  } catch (Exception e) {
    App.fatal(e);
  } finally {
    threadPoolExecutor.shutdownNow();
  }
}
 
Example 17
Project: ABC-List   File: TestdataPresenter.java   View Source Code Vote up 4 votes
private void initializeProcesses() {
    LoggerFacade.getDefault().info(this.getClass(), "Initialize Processes"); // NOI18N
    
    sequentialExecutorService = Executors.newFixedThreadPool(1, new SequentialThreadFactory());
}
 
Example 18
Project: hadoop   File: TestPread.java   View Source Code Vote up 4 votes
@Test
public void testMaxOutHedgedReadPool() throws IOException,
    InterruptedException, ExecutionException {
  isHedgedRead = true;
  Configuration conf = new Configuration();
  int numHedgedReadPoolThreads = 5;
  final int initialHedgedReadTimeoutMillis = 50000;
  final int fixedSleepIntervalMillis = 50;
  conf.setInt(DFSConfigKeys.DFS_DFSCLIENT_HEDGED_READ_THREADPOOL_SIZE,
      numHedgedReadPoolThreads);
  conf.setLong(DFSConfigKeys.DFS_DFSCLIENT_HEDGED_READ_THRESHOLD_MILLIS,
      initialHedgedReadTimeoutMillis);

  // Set up the InjectionHandler
  DFSClientFaultInjector.instance = Mockito
      .mock(DFSClientFaultInjector.class);
  DFSClientFaultInjector injector = DFSClientFaultInjector.instance;
  // make preads sleep for 50ms
  Mockito.doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocation) throws Throwable {
      Thread.sleep(fixedSleepIntervalMillis);
      return null;
    }
  }).when(injector).startFetchFromDatanode();

  MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(3)
      .format(true).build();
  DistributedFileSystem fileSys = cluster.getFileSystem();
  DFSClient dfsClient = fileSys.getClient();
  DFSHedgedReadMetrics metrics = dfsClient.getHedgedReadMetrics();
  // Metrics instance is static, so we need to reset counts from prior tests.
  metrics.hedgedReadOps.set(0);
  metrics.hedgedReadOpsWin.set(0);
  metrics.hedgedReadOpsInCurThread.set(0);

  try {
    Path file1 = new Path("hedgedReadMaxOut.dat");
    writeFile(fileSys, file1);
    // Basic test. Reads complete within timeout. Assert that there were no
    // hedged reads.
    pReadFile(fileSys, file1);
    // assert that there were no hedged reads. 50ms + delta < 500ms
    assertTrue(metrics.getHedgedReadOps() == 0);
    assertTrue(metrics.getHedgedReadOpsInCurThread() == 0);
    /*
     * Reads take longer than timeout. But, only one thread reading. Assert
     * that there were hedged reads. But, none of the reads had to run in the
     * current thread.
     */
    dfsClient.setHedgedReadTimeout(50); // 50ms
    pReadFile(fileSys, file1);
    // assert that there were hedged reads
    assertTrue(metrics.getHedgedReadOps() > 0);
    assertTrue(metrics.getHedgedReadOpsInCurThread() == 0);
    /*
     * Multiple threads reading. Reads take longer than timeout. Assert that
     * there were hedged reads. And that reads had to run in the current
     * thread.
     */
    int factor = 10;
    int numHedgedReads = numHedgedReadPoolThreads * factor;
    long initialReadOpsValue = metrics.getHedgedReadOps();
    ExecutorService executor = Executors.newFixedThreadPool(numHedgedReads);
    ArrayList<Future<Void>> futures = new ArrayList<Future<Void>>();
    for (int i = 0; i < numHedgedReads; i++) {
      futures.add(executor.submit(getPReadFileCallable(fileSys, file1)));
    }
    for (int i = 0; i < numHedgedReads; i++) {
      futures.get(i).get();
    }
    assertTrue(metrics.getHedgedReadOps() > initialReadOpsValue);
    assertTrue(metrics.getHedgedReadOpsInCurThread() > 0);
    cleanupFile(fileSys, file1);
    executor.shutdown();
  } finally {
    fileSys.close();
    cluster.shutdown();
    Mockito.reset(injector);
  }
}
 
Example 19
Project: JavaCommon   File: VolatileDemo.java   View Source Code Vote up 4 votes
public static void test1() {
    final VolatileDemo test = new VolatileDemo();
    VolatileDemo.Model model = new VolatileDemo.Model();
    model.a = 1;
    model.b = 2;
    test.setModel(model);
    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(1);
    ExecutorService fixedThreadPool1 = Executors.newFixedThreadPool(1);
    ExecutorService fixedThreadPool2 = Executors.newFixedThreadPool(1);
    for (int i = 0; i < 1; i++) {
        fixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    test.change();
                }
            }
        });
        fixedThreadPool1.execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    test.init();
                }
            }
        });
        fixedThreadPool2.execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    test.print();
                }
            }
        });
    }
    try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    for (Map.Entry entry : num.entrySet()) {
        System.out.println("key:" + entry.getKey() + "--value:" + entry.getValue());
    }
}
 
Example 20
Project: jwala   File: GroupWebServerControlServiceImpl.java   View Source Code Vote up 4 votes
public GroupWebServerControlServiceImpl(final GroupService theGroupService, WebServerControlService theWebServerControlService) {
    groupService = theGroupService;
    webServerControlService = theWebServerControlService;
    executorService = Executors.newFixedThreadPool(Integer.parseInt(ApplicationProperties.get("thread-task-executor.group-control.pool.size", "25")));
}