Java Code Examples for java.util.concurrent.Executors#newSingleThreadExecutor()

The following examples show how to use java.util.concurrent.Executors#newSingleThreadExecutor() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConcurrencyVersioningTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Test that if a put of an existing key is removed after the put and before tx commit, it is evicted
 *
 * @throws Exception
 */
@Test
public void testGetRemovePutOnExisting() throws Exception {
    final DefaultCacheManager cacheManager = getVersionedCacheManager();
    ExecutorService executor = Executors.newSingleThreadExecutor();

    RemoveThread removeThread = new RemoveThread(cacheManager);

    Cache<String, String> cache = cacheManager.getCache(InfinispanConnectionProvider.REALM_CACHE_NAME);
    cache.put("key", "value0");
    startBatch(cache);
    cache.get("key");
    executor.execute(removeThread);
    removeThread.getLatch().await();
    cache.put("key", "value1");
    try {
        endBatch(cache);
        Assert.fail("Write skew should be detected");
    } catch (Exception e) {


    }
    Assert.assertNull(cache.get("key"));
    Assert.assertTrue(removeThread.isSuccess());
}
 
Example 2
Source File: KinesisPersistWriter.java    From streams with Apache License 2.0 6 votes vote down vote up
@Override
public void prepare(Object configurationObject) {
  // Connect to Kinesis
  synchronized (this) {
    // Create the credentials Object
    AWSCredentials credentials = new BasicAWSCredentials(config.getKey(), config.getSecretKey());

    ClientConfiguration clientConfig = new ClientConfiguration();
    clientConfig.setProtocol(Protocol.valueOf(config.getProtocol().toString()));

    this.client = new AmazonKinesisClient(credentials, clientConfig);
    if (StringUtils.isNotEmpty(config.getRegion())) {
      this.client.setRegion(Region.getRegion(Regions.fromName(config.getRegion())));
    }
  }
  executor = Executors.newSingleThreadExecutor();

}
 
Example 3
Source File: Server.java    From Summer with Apache License 2.0 6 votes vote down vote up
public static Server create(ServerConfig config) {
	log.info("server cluster {}", config.getCluster());
	log.info("server serverName {}", config.getServerName());
	log.info("server address {}", config.getAddress());
	log.info("server port {}", config.getPort());
	log.info("server protocol {}", config.getProtocol());
	log.info("server charset {}", config.getCharset());
	log.info("server password {}", config.getPassword());
	log.info("server bossThread {}", config.getBossThread());
	log.info("server workerThread {}", config.getWorkerThread());
	log.info("server eventThread {}", config.getEventThread());
	log.info("server msgLength {}", config.getMsgLength());
	log.info("server heartSec {}", config.getHeartSec());
	log.info("server coldDownMs {}", config.getColdDownMs());
	log.info("server allowAddressEnable {}", config.isAllowAddressEnable());
	log.info("server allowAddressList {}", Arrays.toString(config.getAllowAddressList()));
	log.info("server optionSoBacklog {}", config.getOptionSoBacklog());
	config.setUseMainServerThreadPool(false);
	return new Server(config,
			new NioEventLoopGroup(config.getBossThread(), new DefaultThreadFactory("ServerBoss")),
			new NioEventLoopGroup(config.getWorkerThread(), new DefaultThreadFactory("ServerWorker")),
			Executors.newFixedThreadPool(ThreadCountUtil.convert(config.getEventThread()), new DefaultThreadFactory("ServerEvent")),
			Executors.newSingleThreadExecutor(new DefaultThreadFactory("ServerPush")));
}
 
Example 4
Source File: CameraModuleHelper.java    From Camera2 with Apache License 2.0 5 votes vote down vote up
public static Camera2ActionProvider provideCamera2ActionProvider()
{
    CameraManager cameraManager = AndroidServices.instance().provideCameraManager();

    HandlerFactory handlerFactory = new HandlerFactory();
    ExecutorService backgroundRunner = Executors.newSingleThreadExecutor();

    return new Camera2ActionProvider(cameraManager, handlerFactory, backgroundRunner,
            Loggers.tagFactory());
}
 
Example 5
Source File: ThreadPool.java    From ans-android-sdk with GNU General Public License v3.0 5 votes vote down vote up
public static void execute(Runnable command) {
    if (executor.isShutdown()) {
        executor = Executors.newSingleThreadExecutor();
    }

    executor.execute(command);
}
 
Example 6
Source File: OrderedExecutorSanityTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void shutdownNowWithBlocked() throws Exception {
   final ExecutorService executorService = Executors.newSingleThreadExecutor();
   try {
      final OrderedExecutor executor = new OrderedExecutor(executorService);
      final CyclicBarrier latch = new CyclicBarrier(2);
      final CyclicBarrier secondlatch = new CyclicBarrier(2);
      final CountDownLatch ran = new CountDownLatch(1);

      executor.execute(() -> {
         try {
            latch.await(1, TimeUnit.MINUTES);
            secondlatch.await(1, TimeUnit.MINUTES);
            ran.countDown();
         } catch (Exception e) {
            e.printStackTrace();
         }
      });


      for (int i = 0; i < 100; i++) {
         executor.execute(() -> System.out.println("Dont worry, this will never happen"));
      }

      latch.await();
      try {
         Assert.assertEquals(100, executor.shutdownNow());
      } finally {
         secondlatch.await();
      }

      Assert.assertEquals(ProcessorBase.STATE_FORCED_SHUTDOWN, executor.status());
      Assert.assertEquals(0, executor.remaining());
   } finally {
      executorService.shutdown();
   }
}
 
Example 7
Source File: AsyncFileSubscriberTest.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 5 votes vote down vote up
@Test
public void checkWriteAllDataCorrectlyInLowPrefetch() throws Exception {
    File temp = null;

    try {
        temp = File.createTempFile("checkWriteAllDataCorrectly", ".tmp");

        System.out.println("Temp file : " + temp.getAbsolutePath());
        AsyncFileSubscriber subscriber =
                new AsyncFileSubscriber(temp.getAbsolutePath(),
                        Executors.newSingleThreadExecutor(), 1);
        Observable.range(0, 20)
                  .map(i -> "[" + System.nanoTime() + "] [LogServiceApplication] " + "[Thread " + Thread.currentThread() + "] Some loge here " + i + "\n")
                  .flatMap(l -> Observable.defer(() -> Observable.just(l))
                                          .subscribeOn(Schedulers.io()))
                  .subscribe(subscriber);

        while (!subscriber.terminated) {
            Thread.yield();
        }

        long count = Files.lines(Paths.get(temp.getAbsolutePath()))
                          .count();

        Assert.assertEquals(20, count);
    }
    finally {
        if (temp != null && !temp.delete()) {
            temp.deleteOnExit();
        }
    }
}
 
Example 8
Source File: Node.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
public Node(OPERATOR operator, OperatorContext context)
{
  this.operator = operator;
  this.context = context;
  executorService = Executors.newSingleThreadExecutor();
  taskQueue = new LinkedList<>();

  outputs = new HashMap<>();

  descriptor = new PortMappingDescriptor();
  Operators.describe(operator, descriptor);

  endWindowDequeueTimes = new HashMap<>();
  tmb = ManagementFactory.getThreadMXBean();
  commandResponse = new LinkedBlockingQueue<>();

  metricFields = Lists.newArrayList();
  for (Field field : ReflectionUtils.getDeclaredFieldsIncludingInherited(operator.getClass())) {
    if (field.isAnnotationPresent(AutoMetric.class)) {
      metricFields.add(field);
      field.setAccessible(true);
    }
  }

  metricMethods = Maps.newHashMap();
  try {
    for (PropertyDescriptor pd : Introspector.getBeanInfo(operator.getClass()).getPropertyDescriptors()) {
      Method readMethod = pd.getReadMethod();
      if (readMethod != null) {
        AutoMetric rfa = readMethod.getAnnotation(AutoMetric.class);
        if (rfa != null) {
          metricMethods.put(pd.getName(), readMethod);
        }
      }
    }
  } catch (IntrospectionException e) {
    throw new RuntimeException("introspecting {}", e);
  }
}
 
Example 9
Source File: BackgroundInitializerTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Tests the get() method if waiting for the initialization is interrupted.
 */
public void testGetInterruptedException() throws Exception {
    ExecutorService exec = Executors.newSingleThreadExecutor();
    final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl(
            exec);
    final CountDownLatch latch1 = new CountDownLatch(1);
    init.shouldSleep = true;
    init.start();
    final AtomicReference<InterruptedException> iex = new AtomicReference<InterruptedException>();
    Thread getThread = new Thread() {
        @Override
        public void run() {
            try {
                init.get();
            } catch (ConcurrentException cex) {
                if (cex.getCause() instanceof InterruptedException) {
                    iex.set((InterruptedException) cex.getCause());
                }
            } finally {
                assertTrue("Thread not interrupted", isInterrupted());
                latch1.countDown();
            }
        }
    };
    getThread.start();
    getThread.interrupt();
    latch1.await();
    exec.shutdownNow();
    exec.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
    assertNotNull("No interrupted exception", iex.get());
}
 
Example 10
Source File: TreeCache.java    From xian with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the {@link TreeCache} based on configured values.
 */
public TreeCache build()
{
    ExecutorService executor = executorService;
    if ( executor == null )
    {
        executor = Executors.newSingleThreadExecutor(defaultThreadFactory);
    }
    return new TreeCache(client, path, cacheData, dataIsCompressed, maxDepth, executor, createParentNodes, selector);
}
 
Example 11
Source File: GaugeCollector.java    From glowroot with Apache License 2.0 5 votes vote down vote up
GaugeCollector(ConfigService configService, Collector collector,
        LazyPlatformMBeanServer lazyPlatformMBeanServer,
        final @Nullable Instrumentation instrumentation, Clock clock, Ticker ticker) {
    this.configService = configService;
    this.collector = collector;
    this.lazyPlatformMBeanServer = lazyPlatformMBeanServer;
    this.clock = clock;
    this.ticker = ticker;
    startTimeMillis = clock.currentTimeMillis();
    collectionExecutor = Executors.newSingleThreadScheduledExecutor(
            ThreadFactories.create("Glowroot-Gauge-Collection"));
    flushingExecutor = Executors
            .newSingleThreadExecutor(ThreadFactories.create("Glowroot-Gauge-Flushing"));
    lazyPlatformMBeanServer.addInitListener(new InitListener() {
        @Override
        public void postInit(MBeanServer mbeanServer) {
            try {
                if (JavaVersion.isGreaterThanOrEqualToJava9() && instrumentation != null) {
                    Java9.grantAccess(instrumentation, "org.glowroot.agent.init.GaugeCollector",
                            "sun.management.ManagementFactoryHelper", true);
                }
                Class<?> sunManagementFactoryHelperClass =
                        Class.forName("sun.management.ManagementFactoryHelper");
                Method registerInternalMBeansMethod = sunManagementFactoryHelperClass
                        .getDeclaredMethod("registerInternalMBeans", MBeanServer.class);
                registerInternalMBeansMethod.setAccessible(true);
                registerInternalMBeansMethod.invoke(null, mbeanServer);
            } catch (Throwable t) {
                logger.debug(t.getMessage(), t);
            }
        }
    });
    flushingExecutor.execute(new GaugeFlushingLoop());
}
 
Example 12
Source File: FirmataAdapter.java    From diozero with MIT License 5 votes vote down vote up
public FirmataAdapter(FirmataEventListener eventListener) {
	this.eventListener = eventListener;

	running = new AtomicBoolean(false);
	responseQueue = new ConcurrentLinkedQueue<>();
	lock = new ReentrantLock();
	condition = lock.newCondition();
	pins = new ConcurrentHashMap<>();
	adcToGpioMapping = new ConcurrentHashMap<>();

	executor = Executors.newSingleThreadExecutor();
}
 
Example 13
Source File: ExecutorServiceWorkRunnerTest.java    From mobius with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotReturnFromDisposeUntilFinishedRunning() throws Exception {
  final Semaphore blockBackground = new Semaphore(0);
  final Semaphore blockUnderTest = new Semaphore(0);
  final Semaphore blockMainThread = new Semaphore(0);

  final List<Integer> output = new CopyOnWriteArrayList<>();

  underTest.post(
      new Runnable() {
        @Override
        public void run() {
          output.add(1);
          blockBackground.release();
          blockUnderTest.acquireUninterruptibly();
          output.add(3);
          blockMainThread.release();
        }
      });

  ExecutorServiceWorkRunner backgroundWorkRunner =
      new ExecutorServiceWorkRunner(Executors.newSingleThreadExecutor());
  backgroundWorkRunner.post(
      new Runnable() {
        @Override
        public void run() {
          blockBackground.acquireUninterruptibly();
          output.add(2);
          blockUnderTest.release();
        }
      });

  blockMainThread.acquire();
  underTest.dispose();
  output.add(4);

  Thread.sleep(40); // wait a bit and make sure nothing else is added after the 4

  assertThat(output, equalTo(asList(1, 2, 3, 4)));
}
 
Example 14
Source File: BufferOverflowStrategyTest.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void init() {
    executor = Executors.newSingleThreadExecutor();
}
 
Example 15
Source File: JobContextTest.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
@Test
public void testParallelCommit()
    throws Exception {

  Properties jobProps = new Properties();

  jobProps.setProperty(ConfigurationKeys.JOB_NAME_KEY, "test");
  jobProps.setProperty(ConfigurationKeys.JOB_ID_KEY, "job_id_12345");
  jobProps.setProperty(ConfigurationKeys.METRICS_ENABLED_KEY, "false");
  jobProps.setProperty(ConfigurationKeys.PARALLELIZE_DATASET_COMMIT, "true");

  Map<String, JobState.DatasetState> datasetStateMap = Maps.newHashMap();
  for (int i = 0; i < 5; i++) {
    datasetStateMap.put(Integer.toString(i), new JobState.DatasetState());
  }

  final BlockingQueue<ControllableCallable<Void>> callables = Queues.newLinkedBlockingQueue();

  final JobContext jobContext =
      new ControllableCommitJobContext(jobProps, log, datasetStateMap, new Predicate<String>() {
        @Override
        public boolean apply(@Nullable String input) {
          return true;
        }
      }, callables);

  ExecutorService executorService = Executors.newSingleThreadExecutor();
  Future future = executorService.submit(new Runnable() {
    @Override
    public void run() {
      try {
        jobContext.commit();
      } catch (IOException ioe) {
        throw new RuntimeException(ioe);
      }
    }
  });

  // Parallelized, should be able to get all 5 commits running
  Queue<ControllableCallable<Void>> drainedCallables = Lists.newLinkedList();
  Assert.assertEquals(Queues.drain(callables, drainedCallables, 5, 1, TimeUnit.SECONDS), 5);
  Assert.assertFalse(future.isDone());

  // unblock all commits
  for (ControllableCallable<Void> callable : drainedCallables) {
    callable.unblock();
  }

  // check that future is done
  future.get(1, TimeUnit.SECONDS);

  // check that no more commits were added
  Assert.assertTrue(callables.isEmpty());
  Assert.assertEquals(jobContext.getJobState().getState(), JobState.RunningState.COMMITTED);
}
 
Example 16
Source File: Util.java    From glowroot with Apache License 2.0 4 votes vote down vote up
private static void runTest(String modulePath, @Nullable String test, JavaVersion javaVersion,
        String... profiles) throws Exception {
    System.out.println(javaVersion);
    report.println(javaVersion);
    List<String> command = Lists.newArrayList();
    command.add(MVN);
    command.add("-P");
    // don't recompile plugin classes since in some cases they won't recompile with older
    // versions of libraries
    // need to recompile tests in some cases to align bytecode with test version
    // also need to recompile tests in some cases where default test compilation target is 1.7
    // but there is alternate 1.6 profile triggered above by -Dglowroot.test.java6
    StringBuilder sb = new StringBuilder("compile-test-classes-only,fail-failsafe-if-no-tests");
    List<String> propertyArgs = Lists.newArrayList();
    for (String profile : profiles) {
        if (profile.startsWith("-D")) {
            propertyArgs.add(profile);
        } else {
            sb.append(",");
            sb.append(profile);
        }
    }
    command.add(sb.toString());
    for (String propertyArg : propertyArgs) {
        command.add(propertyArg);
    }
    command.add("-pl");
    command.add(modulePath);
    command.add("-Djvm=" + javaVersion.getJavaHome() + File.separator + "bin" + File.separator
            + "java");
    if (javaVersion == JavaVersion.JAVA6 || javaVersion == JavaVersion.JAVA7) {
        // maven central no longer supports TLSv1.1 and below
        command.add("-Dhttps.protocols=TLSv1.2");
    }
    if (javaVersion == JavaVersion.JAVA6) {
        command.add("-Dglowroot.test.java6");
    }
    // cassandra plugin tests need java7.home when running under java 6 in order to run
    // cassandra itself
    command.add("-Djava7.home=" + JAVA7.getJavaHome());
    if (test != null) {
        command.add("-Dit.test=" + test);
    }
    command.add("-Dglowroot.it.harness=javaagent");
    command.add("-Dglowroot.test.shaded");
    command.add("-Denforcer.skip");
    command.add("-Danimal.sniffer.skip");
    String sourceOfRandomness = System.getProperty("java.security.egd");
    if (sourceOfRandomness != null) {
        command.add("-Djava.security.egd=" + sourceOfRandomness);
    }
    command.add("clean"); // using profile above "clean-test-classes-only"
    command.add("verify");
    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.redirectErrorStream(true);
    processBuilder.directory(new File(BASE_DIR));
    if (javaVersion == JavaVersion.JAVA6) {
        // maven requires Java 7+
        processBuilder.environment().put("JAVA_HOME", JavaVersion.JAVA7.getJavaHome());
    } else {
        processBuilder.environment().put("JAVA_HOME", javaVersion.getJavaHome());
    }
    System.out.println("\n\n" + Joiner.on(' ').join(command) + "\n\n");
    Process process = processBuilder.start();
    InputStream in = checkNotNull(process.getInputStream());
    ConsoleOutputPipe consoleOutputPipe = new ConsoleOutputPipe(in, System.out);
    ExecutorService consolePipeExecutorService = Executors.newSingleThreadExecutor();
    Future<?> future = consolePipeExecutorService.submit(consoleOutputPipe);
    int exit = process.waitFor();
    future.get();
    consolePipeExecutorService.shutdown();
    consolePipeExecutorService.awaitTermination(10, SECONDS);
    if (exit != 0) {
        report.println("FAIL");
    }
    System.out.println("\n\n");
}
 
Example 17
Source File: StyleTableModel.java    From pentaho-reporting with GNU Lesser General Public License v2.1 4 votes vote down vote up
public StyleTableModel() {
  this( Executors.newSingleThreadExecutor() );
}
 
Example 18
Source File: UntilLaterTest.java    From ReactFX with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@BeforeClass
public static void setupExecutor() {
    executor = Executors.newSingleThreadExecutor();
}
 
Example 19
Source File: DiskIOThreadExecutor.java    From Deadline with GNU General Public License v3.0 4 votes vote down vote up
public DiskIOThreadExecutor() {
    mDiskIO = Executors.newSingleThreadExecutor();
}
 
Example 20
Source File: EditorTestBase.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static ExecutorService getExecutor() {
    if (executor == null) {
        executor = Executors.newSingleThreadExecutor();
    }
    return executor;
}