Java Code Examples for java.util.concurrent.Executors

The following are top voted examples for showing how to use java.util.concurrent.Executors. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: googles-monorepo-demo   File: UninterruptibleFutureTest.java   View source code 6 votes vote down vote up
@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();
    }
  });
}
 
Example 2
Project: chromium-net-for-android   File: JavaCronetEngine.java   View source code 6 votes vote down vote up
@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();
        }
    });
}
 
Example 3
Project: rskj   File: ECKeyTest.java   View source code 6 votes vote down vote up
@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());
}
 
Example 4
Project: LivroJavaComoProgramar10Edicao   File: SharedBufferTest2.java   View source code 6 votes vote down vote up
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); 
}
 
Example 5
Project: openjdk-jdk10   File: ForkJoinPoolTest.java   View source code 6 votes vote down vote up
/**
 * 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"));
}
 
Example 6
Project: jsf-core   File: RecorderSchedule.java   View source code 6 votes vote down vote up
/**
 * 定时清数据
 */
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);
}
 
Example 7
Project: outcomes   File: Main.java   View source code 6 votes vote down vote up
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);
    }
 
Example 8
Project: the-vigilantes   File: ConnectionRegressionTest.java   View source code 6 votes vote down vote up
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;
        }
    });
}
 
Example 9
Project: rskj   File: EthereumImpl.java   View source code 6 votes vote down vote up
@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());
}
 
Example 10
Project: pdf-table   File: PdfTableReaderTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 11
Project: eds   File: PublishManager.java   View source code 6 votes vote down vote up
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();
}
 
Example 12
Project: TakinRPC   File: RemotingNettyClient.java   View source code 6 votes vote down vote up
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();
}
 
Example 13
Project: jvm-dynamic-optimizations-performance-test   File: Nullness.java   View source code 6 votes vote down vote up
@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);
}
 
Example 14
Project: MiniDownloader   File: MiniDownloader.java   View source code 6 votes vote down vote up
/**
 * 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();
}
 
Example 15
Project: uavstack   File: Log4jTest.java   View source code 6 votes vote down vote up
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) {
                    }
                }

            }
        });
    }
 
Example 16
Project: rubenlagus-TelegramBots   File: DefaultAbsSender.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 17
Project: saluki   File: ConsulClient.java   View source code 6 votes vote down vote up
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);
}
 
Example 18
Project: Panako   File: Tap.java   View source code 5 votes vote down vote up
@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");
}
 
Example 19
Project: swage   File: StateCaptureTest.java   View source code 5 votes vote down vote up
@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);
}
 
Example 20
Project: jtier-ctx   File: OkHttpExample.java   View source code 5 votes vote down vote up
@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();
}
 
Example 21
Project: athena   File: Controller.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 22
Project: XinFramework   File: UploadThreadPool.java   View source code 5 votes vote down vote up
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;
}
 
Example 23
Project: GitHub   File: PostStringApiTest.java   View source code 5 votes vote down vote up
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());
    }
 
Example 24
Project: neoscada   File: PerfTest1.java   View source code 5 votes vote down vote up
@Before
public void setup () throws InvalidSyntaxException
{
    this.executor = Executors.newSingleThreadExecutor ();
    this.poolTracker = new ObjectPoolTracker<DataSource> ( Activator.instance.context, DataSource.class );
    this.poolTracker.open ();
}
 
Example 25
Project: JavaCommon   File: PrintABCTest.java   View source code 5 votes vote down vote up
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();
    }
 
Example 26
Project: chromium-net-for-android   File: UploadTest.java   View source code 5 votes vote down vote up
@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();
    }
}
 
Example 27
Project: Java-9-Concurrency-Cookbook-Second-Edition   File: Server.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 28
Project: think-in-java   File: DaemonFromFactory.java   View source code 5 votes vote down vote up
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
}
 
Example 29
Project: webBee   File: Executor.java   View source code 5 votes vote down vote up
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();
        }
 
Example 30
Project: GitHub   File: MultipartJSONApiTest.java   View source code 5 votes vote down vote up
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());
    }
 
Example 31
Project: https-github.com-hyb1996-NoRootScriptDroid   File: AccessibilityService.java   View source code 5 votes vote down vote up
@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;
}
 
Example 32
Project: GitHub   File: PostObjectApiTest.java   View source code 5 votes vote down vote up
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());
    }
 
Example 33
Project: ijaas   File: IjaasServer.java   View source code 5 votes vote down vote up
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();
}
 
Example 34
Project: GitHub   File: JacksonGetObjectApiTest.java   View source code 5 votes vote down vote up
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());
    }
 
Example 35
Project: elephant   File: ProducerManager.java   View source code 5 votes vote down vote up
@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);
  }
 
Example 36
Project: r8   File: R8EntryPointTests.java   View source code 5 votes vote down vote up
@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)));
}
 
Example 37
Project: hadoop   File: TestByteArrayManager.java   View source code 5 votes vote down vote up
@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());
}
 
Example 38
Project: GitHub   File: GetObjectApiTest.java   View source code 5 votes vote down vote up
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());
    }
 
Example 39
Project: micrometer   File: ExecutorServiceSample.java   View source code 5 votes vote down vote up
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) {}
}
 
Example 40
Project: neoscada   File: JdbcValueMapper.java   View source code 5 votes vote down vote up
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 ();
}