Java 类java.util.concurrent.Executors 实例源码

项目:googles-monorepo-demo    文件:UninterruptibleFutureTest.java   
@Override protected void setUp() {
  final ExecutorService executor = Executors.newSingleThreadExecutor();
  tearDownStack.addTearDown(new TearDown() {
    @Override
    public void tearDown() {
      executor.shutdownNow();
    }
  });
  sleeper = new SleepingRunnable(1000);
  delayedFuture = executor.submit(sleeper, true);

  tearDownStack.addTearDown(new TearDown() {
    @Override
    public void tearDown() {
      Thread.interrupted();
    }
  });
}
项目:chromium-net-for-android    文件:JavaCronetEngine.java   
@Override
public Thread newThread(final Runnable r) {
    return Executors.defaultThreadFactory().newThread(new Runnable() {
        @Override
        public void run() {
            Thread.currentThread().setName("JavaCronetEngine");
            // On android, all background threads (and all threads that are part
            // of background processes) are put in a cgroup that is allowed to
            // consume up to 5% of CPU - these worker threads spend the vast
            // majority of their time waiting on I/O, so making them contend with
            // background applications for a slice of CPU doesn't make much sense.
            // We want to hurry up and get idle.
            android.os.Process.setThreadPriority(
                    THREAD_PRIORITY_BACKGROUND + THREAD_PRIORITY_MORE_FAVORABLE);
            r.run();
        }
    });
}
项目:rskj    文件:ECKeyTest.java   
@Test
public void testSValue() throws Exception {
    // Check that we never generate an S value that is larger than half the curve order. This avoids a malleability
    // issue that can allow someone to change a transaction [hash] without invalidating the signature.
    final int ITERATIONS = 10;
    ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(ITERATIONS));
    List<ListenableFuture<ECKey.ECDSASignature>> sigFutures = Lists.newArrayList();
    final ECKey key = new ECKey();
    for (byte i = 0; i < ITERATIONS; i++) {
        final byte[] hash = HashUtil.sha3(new byte[]{i});
        sigFutures.add(executor.submit(new Callable<ECDSASignature>() {
            @Override
            public ECKey.ECDSASignature call() throws Exception {
                return key.doSign(hash);
            }
        }));
    }
    List<ECKey.ECDSASignature> sigs = Futures.allAsList(sigFutures).get();
    for (ECKey.ECDSASignature signature : sigs) {
        assertTrue(signature.s.compareTo(ECKey.HALF_CURVE_ORDER) <= 0);
    }
    final ECKey.ECDSASignature duplicate = new ECKey.ECDSASignature(sigs.get(0).r, sigs.get(0).s);
    assertEquals(sigs.get(0), duplicate);
    assertEquals(sigs.get(0).hashCode(), duplicate.hashCode());
}
项目:LivroJavaComoProgramar10Edicao    文件:SharedBufferTest2.java   
public static void main(String[] args) throws InterruptedException
{
   // create new thread pool with two threads
   ExecutorService executorService = Executors.newCachedThreadPool();

   // create SynchronizedBuffer to store ints
   Buffer sharedLocation = new SynchronizedBuffer();

   System.out.printf("%-40s%s\t\t%s%n%-40s%s%n%n", "Operation", 
      "Buffer", "Occupied", "---------", "------\t\t--------");

   // execute the Producer and Consumer tasks
   executorService.execute(new Producer(sharedLocation));
   executorService.execute(new Consumer(sharedLocation));

   executorService.shutdown();
   executorService.awaitTermination(1, TimeUnit.MINUTES); 
}
项目:openjdk-jdk10    文件:ForkJoinPoolTest.java   
/**
 * A submitted privileged exception action runs to completion
 */
public void testSubmitPrivilegedExceptionAction() throws Exception {
    final Callable callable =
        Executors.callable(new PrivilegedExceptionAction() {
            public Object run() { return TEST_STRING; }});
    Runnable r = new CheckedRunnable() {
    public void realRun() throws Exception {
        ExecutorService e = new ForkJoinPool(1);
        try (PoolCleaner cleaner = cleaner(e)) {
            Future future = e.submit(callable);
            assertSame(TEST_STRING, future.get());
        }
    }};

    runWithPermissions(r, new RuntimePermission("modifyThread"));
}
项目:jsf-core    文件:RecorderSchedule.java   
/**
 * 定时清数据
 */
private void schedule() {
    ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("recoder"));
    scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
        public void run() {
            try {
                CallbackRecoder.recordTime();
                CallbackRecoder.calCallbackCount();
                RequestRecoder.calProviderRegistryCount();
                RequestRecoder.calConsumerRegistryCount();
                IpRequestHandler.calAllCount();
                sendMonitorData();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }, getDelaySecond(), interval, TimeUnit.SECONDS);
}
项目:outcomes    文件:Main.java   
private void reentrantlock() {

        ExecutorService executor = Executors.newFixedThreadPool(2);
        ReentrantLock lock = new ReentrantLock();

        executor.submit(() -> {
            lock.lock();
            try {
                sleep(1);
            } finally {
                lock.unlock();
            }
        });

        executor.submit(() -> {
            System.out.println("Locked: " + lock.isLocked());
            System.out.println("Held by me: " + lock.isHeldByCurrentThread());
            boolean locked = lock.tryLock();
            System.out.println("Lock acquired: " + locked);
        });

        stop(executor);
    }
项目:the-vigilantes    文件:ConnectionRegressionTest.java   
public void testBug75615() throws Exception {
    // Main use case: although this could cause an exception due to a race condition in MysqlIO.mysqlConnection it is silently swallowed within the running
    // thread.
    final Connection testConn1 = getConnectionWithProps("");
    testConn1.setNetworkTimeout(Executors.newSingleThreadExecutor(), 1000);
    testConn1.close();

    // Main use case simulation: this simulates the above by capturing an eventual exeption in the main thread. This is where this test would actually fail.
    // This part is repeated several times to increase the chance of hitting the reported bug.
    for (int i = 0; i < 25; i++) {
        final ExecutorService execService = Executors.newSingleThreadExecutor();
        final Connection testConn2 = getConnectionWithProps("");
        testConn2.setNetworkTimeout(new Executor() {
            public void execute(Runnable command) {
                // Attach the future to the parent object so that it can track the exception in the main thread.
                ConnectionRegressionTest.this.testBug75615Future = execService.submit(command);
            }
        }, 1000);
        testConn2.close();
        try {
            this.testBug75615Future.get();
        } catch (ExecutionException e) {
            e.getCause().printStackTrace();
            fail("Exception thrown in the thread that was setting the network timeout: " + e.getCause());
        }
        execService.shutdownNow();
    }

    // Test the expected exception on null executor.
    assertThrows(SQLException.class, "Executor can not be null", new Callable<Void>() {
        public Void call() throws Exception {
            Connection testConn = getConnectionWithProps("");
            testConn.setNetworkTimeout(null, 1000);
            testConn.close();
            return null;
        }
    });
}
项目:rskj    文件:EthereumImpl.java   
@Override
public void init() {
    if (config.listenPort() > 0) {
        peerServiceExecutor = Executors.newSingleThreadExecutor(runnable -> {
            Thread thread = new Thread(runnable, "Peer Server");
            thread.setUncaughtExceptionHandler((exceptionThread, exception) -> {
                gLogger.error("Unable to start peer server", exception);
            });
            return thread;
        });
        peerServiceExecutor.execute(() -> peerServer.start(config.listenPort()));
    }
    compositeEthereumListener.addListener(gasPriceTracker);

    gLogger.info("RskJ node started: enode://{}@{}:{}" , Hex.toHexString(config.nodeId()), config.getExternalIp(), config.listenPort());
}
项目:pdf-table    文件:PdfTableReaderTest.java   
@Test
public void multiThreadedSavePdfTablePageDebugImage() throws IOException {
    long start = System.currentTimeMillis();
    PdfTableReader reader = new PdfTableReader();
    ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);

    List<Future<Boolean>> futures = new ArrayList<>();
    for (final int pageNum : IntStream.rangeClosed(1, PDFdoc.getNumberOfPages()).toArray()) {
        Callable<Boolean> callable = () -> {
            reader.savePdfTablePageDebugImage(PDFdoc, pageNum, TEST_OUT_PATH);
            return true;
        };
        futures.add(executor.submit(callable));
    }

    try {
        for (Future<Boolean> f : futures) {
            f.get();
        }
    } catch (Exception e) {
        throw new TestException(e);
    }

    long end = System.currentTimeMillis();
    System.out.println("save debug images - multi thread: " + (end - start) / 1000.0);
}
项目:eds    文件:PublishManager.java   
private void initDisruptor(int processors, int ringBufferSize) {
  LOG.info("eds client init disruptor with processors="
      + processors + " and ringBufferSize=" + ringBufferSize);

  executor = Executors.newFixedThreadPool(
      processors,
      new ThreadFactoryBuilder().setNameFormat("disruptor-executor-%d").build());

  final WaitStrategy waitStrategy = createWaitStrategy();
  ringBufferSize = sizeFor(ringBufferSize); // power of 2
  disruptor = new Disruptor<>(EdsRingBufferEvent.FACTORY, ringBufferSize, executor,
      ProducerType.MULTI, waitStrategy);

  EdsEventWorkHandler[] handlers = new EdsEventWorkHandler[processors];
  for (int i = 0; i < handlers.length; i++) {
    handlers[i] = new EdsEventWorkHandler();
  }
  // handlers number = threads number
  disruptor.handleEventsWithWorkerPool(handlers); // "handleEventsWith" just like topics , with multiple consumers

  disruptor.start();
}
项目:TakinRPC    文件:RemotingNettyClient.java   
private RemotingNettyClient(final NettyClientConfig nettyClientConfig) {
    super(nettyClientConfig.getOnewaySemaphoreValue(), nettyClientConfig.getAsyncSemaphoreValue());
    int publicThreadNums = nettyClientConfig.getCallbackExecutorThreads();
    if (publicThreadNums <= 0) {
        publicThreadNums = 4;
    }
    this.publicExecutor = Executors.newFixedThreadPool(publicThreadNums, new ThreadFactory() {
        private AtomicInteger threadIndex = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "NettyClientPublicExecutor_" + this.threadIndex.incrementAndGet());
        }
    });

    group = new NioEventLoopGroup(nettyClientConfig.getWorkerThreads(), new CustomThreadFactory("client"));

    start();
}
项目:jvm-dynamic-optimizations-performance-test    文件:Nullness.java   
@Setup
public void setup() {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    executor.schedule(
            () -> {
                System.out.println("Deoptimize: 1");
                state = 1;
            },
            25, TimeUnit.SECONDS);
    executor.schedule(
            () -> {
                System.out.println("Deoptimize :0");
                state = 0;
            },
            30, TimeUnit.SECONDS);
}
项目:MiniDownloader    文件:MiniDownloader.java   
/**
 * Initial MiniDownloader.
 *
 * @param context
 */
public void init(Context context) {
    this.appContext = context.getApplicationContext();
    /** Create work executor. */
    this.workExecutor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), Runtime.getRuntime().availableProcessors(), 0L, TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>()) {
        @Override
        protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
            if (callable instanceof CustomFutureCallable) {
                return ((CustomFutureCallable) callable).newTaskFor();
            }
            return super.newTaskFor(callable);
        }
    };
    /** Create command executor. */
    this.commandExecutor = Executors.newSingleThreadExecutor();
    /** Create and initial task manager. */
    taskManager = new TaskManager();
    taskManager.init(context);
    /** Create and start ProgressUpdater. */
    progressUpdater = new ProgressUpdater();
    progressUpdater.start();
}
项目:uavstack    文件:Log4jTest.java   
private void whileOutLog(String outs) {

        ser = Executors.newSingleThreadExecutor();
        ser.execute(new Runnable() {

            @Override
            public void run() {

                while (true) {
                    try {
                        logger.info("Test HBase insert Log info-" + new Date());
                        Thread.sleep(5000);
                    }
                    catch (InterruptedException e) {
                    }
                }

            }
        });
    }
项目:rubenlagus-TelegramBots    文件:DefaultAbsSender.java   
protected DefaultAbsSender(DefaultBotOptions options) {
    super();
    this.exe = Executors.newFixedThreadPool(options.getMaxThreads());
    this.options = options;
    httpclient = HttpClientBuilder.create()
            .setSSLHostnameVerifier(new NoopHostnameVerifier())
            .setConnectionTimeToLive(70, TimeUnit.SECONDS)
            .setMaxConnTotal(100)
            .build();

    requestConfig = options.getRequestConfig();

    if (requestConfig == null) {
        requestConfig = RequestConfig.copy(RequestConfig.custom().build())
                .setSocketTimeout(SOCKET_TIMEOUT)
                .setConnectTimeout(SOCKET_TIMEOUT)
                .setConnectionRequestTimeout(SOCKET_TIMEOUT).build();
    }
}
项目:saluki    文件:ConsulClient.java   
public ConsulClient(String host, int port){
    client = new com.ecwid.consul.v1.ConsulClient(host, port);
    ttlScheduler = new TtlScheduler(client);
    scheduleRegistry = Executors.newScheduledThreadPool(1, new NamedThreadFactory("retryFailedTtl", true));
    scheduleRegistry.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            try {
                retryFailedTtl();
            } catch (Throwable e) {
                log.info("retry registry znode failed", e);
            }
        }
    }, ConsulConstants.HEARTBEAT_CIRCLE, ConsulConstants.HEARTBEAT_CIRCLE, TimeUnit.MILLISECONDS);
    log.info("ConsulEcwidClient init finish. client host:" + host + ", port:" + port);
}
项目:Panako    文件:Tap.java   
@Override
public void handle(int responseCode, String response,String source, String type, long millis) {
    final List<Double> beats = PanakoWebserviceClient.beatListFromResponse(response);

    double requestTime = (System.currentTimeMillis() - startQuery)/1000.0;
       double systemLatency = 0.072;
       double totalOffset = requestTime  + systemLatency + queryDuration + matchStart;
       for(int i = 0 ; i < beats.size() ; i++){
           double newTime= beats.get(i) - totalOffset;
           if(newTime < 0.1){
            beats.remove(i);
               i--;
           }else{
               beats.set(i,newTime);
           }
       }

       if(es!=null){
        es.shutdownNow();
       }
       es = Executors.newFixedThreadPool(50);
       for(int i = 0 ; i < beats.size() && beats.get(i) < 25 ; i++){
         es.execute(new Waiter((int) (beats.get(i)*1000)));
       }

    System.out.println("Total offset time " + totalOffset + " s");
    System.out.println("recieved " + beats.size() + " beats");
    System.out.println("Total query time " + (System.currentTimeMillis()-startQuery) + " ms");
}
项目:swage    文件:StateCaptureTest.java   
@Test
public void testScheduledExecutorServiceCaptures() throws InterruptedException {
    // Setup
    ScheduledExecutorService e = Executors.newScheduledThreadPool(10);
    ScheduledExecutorService f = StateCapture.capturingDecorator(e);

    CapturedState mockCapturedState = mock(CapturedState.class);
    Runnable mockRunnable = mock(Runnable.class);
    ThreadLocalStateCaptor.THREAD_LOCAL.set(mockCapturedState);
    f.execute(mockRunnable);
    e.shutdown();
    e.awaitTermination(10, TimeUnit.HOURS);

    verifyStandardCaptures(mockCapturedState, mockRunnable);
}
项目:jtier-ctx    文件:OkHttpExample.java   
@Before
public void setUp() throws Exception {
    final Dispatcher d = new Dispatcher(AttachingExecutor.infect(Executors.newCachedThreadPool()));
    this.ok = new OkHttpClient.Builder()
            .dispatcher(d)
            .addInterceptor(new ExampleInterceptor())
            .build();
}
项目:athena    文件:Controller.java   
/**
 * Retry connection with exponential back-off mechanism.
 *
 * @param retryDelay retry delay
 */
private void scheduleConnectionRetry(long retryDelay) {
    if (connectExecutor == null) {
        connectExecutor = Executors.newSingleThreadScheduledExecutor();
    }
    future = connectExecutor.schedule(new ConnectionRetry(), retryDelay, TimeUnit.MINUTES);
}
项目:XinFramework    文件:UploadThreadPool.java   
public XExecutor getExecutor() {
    if (executor == null) {
        synchronized (UploadThreadPool.class) {
            if (executor == null) {
                executor = new XExecutor(corePoolSize, MAX_IMUM_POOL_SIZE, KEEP_ALIVE_TIME, UNIT, //
                                         new PriorityBlockingQueue<Runnable>(),   //无限容量的缓冲队列
                                         Executors.defaultThreadFactory(),        //线程创建工厂
                                         new ThreadPoolExecutor.AbortPolicy());   //继续超出上限的策略,阻止
            }
        }
    }
    return executor;
}
项目:GitHub    文件:PostStringApiTest.java   
public void testHeaderPostRequest() throws InterruptedException {

        server.enqueue(new MockResponse().setBody("data"));

        final AtomicReference<String> responseRef = new AtomicReference<>();
        final AtomicReference<String> headerRef = new AtomicReference<>();
        final AtomicReference<Boolean> responseBodySuccess = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(1);

        AndroidNetworking.post(server.url("/").toString())
                .addHeaders("headerKey", "headerValue")
                .addBodyParameter("fistName", "Amit")
                .addBodyParameter("lastName", "Shekhar")
                .setExecutor(Executors.newSingleThreadExecutor())
                .build()
                .getAsOkHttpResponseAndString(new OkHttpResponseAndStringRequestListener() {
                    @Override
                    public void onResponse(Response okHttpResponse, String response) {
                        responseRef.set(response);
                        responseBodySuccess.set(okHttpResponse.isSuccessful());
                        headerRef.set(okHttpResponse.request().header("headerKey"));
                        latch.countDown();
                    }

                    @Override
                    public void onError(ANError anError) {
                        assertTrue(false);
                    }
                });

        assertTrue(latch.await(2, SECONDS));

        assertTrue(responseBodySuccess.get());
        assertEquals("data", responseRef.get());
        assertEquals("headerValue", headerRef.get());
    }
项目:neoscada    文件:PerfTest1.java   
@Before
public void setup () throws InvalidSyntaxException
{
    this.executor = Executors.newSingleThreadExecutor ();
    this.poolTracker = new ObjectPoolTracker<DataSource> ( Activator.instance.context, DataSource.class );
    this.poolTracker.open ();
}
项目:JavaCommon    文件:PrintABCTest.java   
public static void main(String[] args) {

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        A.release();
        for(int i = 0 ; i < 10; i ++) {
            executorService.execute(new SayA());
            executorService.execute(new SayB());
            executorService.execute(new SayC());
        }

        executorService.shutdown();
    }
项目:chromium-net-for-android    文件:UploadTest.java   
@SmallTest
@Feature({"Cronet"})
public void testAppendChunkRaceWithCancel() throws Exception {
    ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024);
    byteBuffer.put(UPLOAD_DATA.getBytes());
    byteBuffer.position(0);

    // Try to recreate race described in crbug.com/434855 when request
    // is canceled from another thread while adding chunks to upload.
    for (int test = 0; test < 100; ++test) {
        TestHttpUrlRequestListener listener =
                new TestHttpUrlRequestListener();
        final ChromiumUrlRequest request =
                (ChromiumUrlRequest) createRequest("http://127.0.0.1:8000",
                                                   listener);
        request.setChunkedUpload("dangerous/crocodile");
        request.start();
        Runnable cancelTask = new Runnable() {
            public void run() {
                request.cancel();
            }
        };
        Executors.newCachedThreadPool().execute(cancelTask);
        try {
            request.appendChunk(byteBuffer, false);
            request.appendChunk(byteBuffer, false);
            request.appendChunk(byteBuffer, false);
            request.appendChunk(byteBuffer, true);
            // IOException may be thrown if appendChunk detects that request
            // is already destroyed.
        } catch (IOException e) {
            assertEquals("Native peer destroyed.", e.getMessage());
        }
        listener.blockForComplete();
    }
}
项目:Java-9-Concurrency-Cookbook-Second-Edition    文件:Server.java   
/**
 * Constructor of the class. Creates the executor object
 */
public Server(){
    // Create the executor
    executor=(ThreadPoolExecutor)Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    // Create the controller for the Rejected tasks
    RejectedTaskController controller=new RejectedTaskController();
    // Establish the rejected task controller
    executor.setRejectedExecutionHandler(controller);
}
项目:think-in-java    文件:DaemonFromFactory.java   
public static void main(String[] args) throws Exception
{
    ExecutorService exec = Executors
            .newCachedThreadPool(new DaemonThreadFactory());
    for (int i = 0; i < 10; i++)
    {
        exec.execute(new DaemonFromFactory());
    }
    print("All daemons started");
    TimeUnit.MILLISECONDS.sleep(500); // Run for a while
}
项目:webBee    文件:Executor.java   
public static void main(String[] args){
            //ExecutorService 的生命周期包括三种状态:运行、关闭、终止。创建后便进入运行状态,当调用了 shutdown()方法时
            // ,便进入关闭状态,此时意味着 ExecutorService 不再接受新的任务,但它还在执行已经提交了的任务
          ExecutorService executorService = Executors.newCachedThreadPool();
//          ExecutorService executorService = Executors.newFixedThreadPool(5);
            //创建一个单线程化的Executor。
//          ExecutorService executorService = Executors.newSingleThreadExecutor();
            for (int i = 0; i < 5; i++){
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println(Thread.currentThread().getName() + "线程被调用了。");
                    }
                });
                System.out.println("************* a" + i + " *************");
            }
            executorService.shutdown();
        }
项目:GitHub    文件:MultipartJSONApiTest.java   
public void testResponseBodyAndJSONArrayMultipart404() throws InterruptedException {

        server.enqueue(new MockResponse().setResponseCode(404).setBody("data"));

        final AtomicReference<String> errorBodyRef = new AtomicReference<>();
        final AtomicReference<Integer> errorCodeRef = new AtomicReference<>();
        final AtomicReference<String> errorDetailRef = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(1);

        AndroidNetworking.upload(server.url("/").toString())
                .addMultipartParameter("key", "value")
                .setExecutor(Executors.newSingleThreadExecutor())
                .build()
                .getAsOkHttpResponseAndJSONArray(new OkHttpResponseAndJSONArrayRequestListener() {
                    @Override
                    public void onResponse(Response okHttpResponse, JSONArray response) {
                        assertTrue(false);
                    }

                    @Override
                    public void onError(ANError anError) {
                        errorBodyRef.set(anError.getErrorBody());
                        errorDetailRef.set(anError.getErrorDetail());
                        errorCodeRef.set(anError.getErrorCode());
                        latch.countDown();
                    }
                });

        assertTrue(latch.await(2, SECONDS));

        assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get());

        assertEquals("data", errorBodyRef.get());

        assertEquals(404, errorCodeRef.get().intValue());
    }
项目:https-github.com-hyb1996-NoRootScriptDroid    文件:AccessibilityService.java   
@Override
protected boolean onKeyEvent(final KeyEvent event) {
    if (mKeyEventExecutor == null) {
        mKeyEventExecutor = Executors.newSingleThreadExecutor();
    }
    mKeyEventExecutor.execute(new Runnable() {
        @Override
        public void run() {
            stickOnKeyObserver.onKeyEvent(event.getKeyCode(), event);
            mOnKeyObserver.onKeyEvent(event.getKeyCode(), event);
        }
    });
    return false;
}
项目:GitHub    文件:PostObjectApiTest.java   
public void testResponseBodyAndObjectListPost() throws InterruptedException {

        server.enqueue(new MockResponse().setBody("[{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}]"));

        final AtomicReference<String> firstNameRef = new AtomicReference<>();
        final AtomicReference<String> lastNameRef = new AtomicReference<>();
        final AtomicReference<Boolean> responseBodySuccess = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(1);

        AndroidNetworking.post(server.url("/").toString())
                .addBodyParameter("fistName", "Amit")
                .addBodyParameter("lastName", "Shekhar")
                .setExecutor(Executors.newSingleThreadExecutor())
                .build()
                .getAsOkHttpResponseAndObjectList(User.class,
                        new OkHttpResponseAndParsedRequestListener<List<User>>() {
                            @Override
                            public void onResponse(Response okHttpResponse, List<User> userList) {
                                firstNameRef.set(userList.get(0).firstName);
                                lastNameRef.set(userList.get(0).lastName);
                                responseBodySuccess.set(okHttpResponse.isSuccessful());
                                latch.countDown();
                            }

                            @Override
                            public void onError(ANError anError) {
                                assertTrue(false);
                            }
                        });

        assertTrue(latch.await(2, SECONDS));

        assertTrue(responseBodySuccess.get());
        assertEquals("Amit", firstNameRef.get());
        assertEquals("Shekhar", lastNameRef.get());
    }
项目:ijaas    文件:IjaasServer.java   
void start() {
  new Thread(
          () -> {
            ExecutorService executorService = Executors.newCachedThreadPool();
            try (ServerSocket serverSocket =
                new ServerSocket(port, 0, InetAddress.getLoopbackAddress())) {
              while (true) {
                Socket socket = serverSocket.accept();
                executorService.execute(() -> process(socket));
              }
            } catch (IOException e) {
              throw new RuntimeException(e);
            }
          })
      .start();
}
项目:GitHub    文件:JacksonGetObjectApiTest.java   
public void testResponseBodyAndObjectListGet404() throws InterruptedException {

        server.enqueue(new MockResponse().setResponseCode(404).setBody("data"));

        final AtomicReference<String> errorBodyRef = new AtomicReference<>();
        final AtomicReference<Integer> errorCodeRef = new AtomicReference<>();
        final AtomicReference<String> errorDetailRef = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(1);

        AndroidNetworking.get(server.url("/").toString())
                .setExecutor(Executors.newSingleThreadExecutor())
                .build()
                .getAsOkHttpResponseAndObjectList(User.class,
                        new OkHttpResponseAndParsedRequestListener<List<User>>() {
                            @Override
                            public void onResponse(Response okHttpResponse, List<User> userList) {
                                assertTrue(false);
                            }

                            @Override
                            public void onError(ANError anError) {
                                errorBodyRef.set(anError.getErrorBody());
                                errorDetailRef.set(anError.getErrorDetail());
                                errorCodeRef.set(anError.getErrorCode());
                                latch.countDown();
                            }
                        });

        assertTrue(latch.await(2, SECONDS));

        assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get());

        assertEquals("data", errorBodyRef.get());

        assertEquals(404, errorCodeRef.get().intValue());
    }
项目:elephant    文件:ProducerManager.java   
@PostConstruct
  public void initMethod(){
    ThreadFactory threadFactory = new ThreadFactoryBuilder()
      .setNameFormat("producer-manager-%d")
      .setDaemon(true)
      .build();
    this.removeExpireKeyExecutor = Executors.newSingleThreadScheduledExecutor(threadFactory);
    this.removeExpireKeyExecutor.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        log.debug("groupChannelTable:{}",groupChannelTable);
        ProducerManager.this.scanNotActiveChannel();
    }
}, 1000 * 10, 1000 * 10, TimeUnit.MILLISECONDS);
  }
项目:r8    文件:R8EntryPointTests.java   
@Test
public void testRun2Dir() throws IOException, CompilationException, ProguardRuleParserException {
  Path out = temp.newFolder("outdex").toPath();
  ExecutorService executor = Executors.newWorkStealingPool(2);
  try {
    R8.run(getCommand(out), executor);
  } finally {
    executor.shutdown();
  }
  Assert.assertTrue(Files.isRegularFile(out.resolve(FileUtils.DEFAULT_DEX_FILENAME)));
  Assert.assertTrue(Files.isRegularFile(testFlags.getParent().resolve(MAPPING)));
  Assert.assertTrue(Files.isRegularFile(testFlags.getParent().resolve(SEEDS)));
}
项目:hadoop    文件:TestByteArrayManager.java   
@Test
public void testCounter() throws Exception {
  final long countResetTimePeriodMs = 200L;
  final Counter c = new Counter(countResetTimePeriodMs);

  final int n = DFSUtil.getRandom().nextInt(512) + 512;
  final List<Future<Integer>> futures = new ArrayList<Future<Integer>>(n);

  final ExecutorService pool = Executors.newFixedThreadPool(32);
  try {
    // increment
    for(int i = 0; i < n; i++) {
      futures.add(pool.submit(new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
          return (int)c.increment();
        }
      }));
    }

    // sort and wait for the futures
    Collections.sort(futures, CMP);
  } finally {
    pool.shutdown();
  }

  // check futures
  Assert.assertEquals(n, futures.size());
  for(int i = 0; i < n; i++) {
    Assert.assertEquals(i + 1, futures.get(i).get().intValue());
  }
  Assert.assertEquals(n, c.getCount());

  // test auto-reset
  Thread.sleep(countResetTimePeriodMs + 100);
  Assert.assertEquals(1, c.increment());
}
项目:GitHub    文件:GetObjectApiTest.java   
public void testResponseBodyAndObjectListGet404() throws InterruptedException {

        server.enqueue(new MockResponse().setResponseCode(404).setBody("data"));

        final AtomicReference<String> errorBodyRef = new AtomicReference<>();
        final AtomicReference<Integer> errorCodeRef = new AtomicReference<>();
        final AtomicReference<String> errorDetailRef = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(1);

        AndroidNetworking.get(server.url("/").toString())
                .setExecutor(Executors.newSingleThreadExecutor())
                .build()
                .getAsOkHttpResponseAndObjectList(User.class,
                        new OkHttpResponseAndParsedRequestListener<List<User>>() {
                            @Override
                            public void onResponse(Response okHttpResponse, List<User> userList) {
                                assertTrue(false);
                            }

                            @Override
                            public void onError(ANError anError) {
                                errorBodyRef.set(anError.getErrorBody());
                                errorDetailRef.set(anError.getErrorDetail());
                                errorCodeRef.set(anError.getErrorCode());
                                latch.countDown();
                            }
                        });

        assertTrue(latch.await(2, SECONDS));

        assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get());

        assertEquals("data", errorBodyRef.get());

        assertEquals(404, errorCodeRef.get().intValue());
    }
项目:micrometer    文件:ExecutorServiceSample.java   
public static void main(String[] args) {
    MeterRegistry registry = SampleConfig.myMonitoringSystem();
    ScheduledExecutorService es = Executors.newSingleThreadScheduledExecutor();
    new ExecutorServiceMetrics(es, "executor.sample", emptyList()).bindTo(registry);

    es.scheduleWithFixedDelay(() -> Mono.delay(Duration.ofMillis(20)).block(), 0,
            10, TimeUnit.MILLISECONDS);

    while(true) {}
}
项目:neoscada    文件:JdbcValueMapper.java   
public JdbcValueMapper ( final BundleContext context, final String id, final ManageableObjectPool<DataItem> objectPool )
{
    this.id = id;
    this.objectPool = objectPool;
    this.context = context;
    this.executor = Executors.newSingleThreadScheduledExecutor ( new NamedThreadFactory ( "org.eclipse.scada.da.mapper.osgi.jdbc" ) );

    this.state = new JdbcValueMapperState ();

    this.updateLock = new ReentrantLock ();
}