Esempio n. 1
0
  @Override
  public synchronized NettyWebServer start() {
    if (isRunning()) {
      throw new IllegalStateException("Server already started.");
    }

    // Configure the server.
    bootstrap = new ServerBootstrap();

    // Set up the event pipeline factory.
    bootstrap.setPipelineFactory(
        new ChannelPipelineFactory() {
          @Override
          public ChannelPipeline getPipeline() throws Exception {
            long timestamp = timestamp();
            Object id = nextId();
            ChannelPipeline pipeline = pipeline();
            pipeline.addLast("staleconnectiontracker", staleConnectionTrackingHandler);
            pipeline.addLast("connectiontracker", connectionTrackingHandler);
            pipeline.addLast("flashpolicydecoder", new FlashPolicyFileDecoder(getPort()));
            pipeline.addLast(
                "decoder",
                new HttpRequestDecoder(maxInitialLineLength, maxHeaderSize, maxChunkSize));
            pipeline.addLast("aggregator", new HttpChunkAggregator(maxContentLength));
            pipeline.addLast("decompressor", new HttpContentDecompressor());
            pipeline.addLast("encoder", new HttpResponseEncoder());
            pipeline.addLast("compressor", new HttpContentCompressor());
            pipeline.addLast(
                "handler",
                new NettyHttpChannelHandler(
                    executor, handlers, id, timestamp, exceptionHandler, ioExceptionHandler));
            return pipeline;
          }
        });

    staleConnectionTrackingHandler =
        new StaleConnectionTrackingHandler(staleConnectionTimeout, executor);
    ScheduledExecutorService staleCheckExecutor = Executors.newSingleThreadScheduledExecutor();
    staleCheckExecutor.scheduleWithFixedDelay(
        new Runnable() {
          @Override
          public void run() {
            staleConnectionTrackingHandler.closeStaleConnections();
          }
        },
        staleConnectionTimeout / 2,
        staleConnectionTimeout / 2,
        TimeUnit.MILLISECONDS);
    executorServices.add(staleCheckExecutor);

    connectionTrackingHandler = new ConnectionTrackingHandler();
    ExecutorService bossExecutor = Executors.newSingleThreadExecutor();
    executorServices.add(bossExecutor);
    ExecutorService workerExecutor = Executors.newSingleThreadExecutor();
    executorServices.add(workerExecutor);
    bootstrap.setFactory(new NioServerSocketChannelFactory(bossExecutor, workerExecutor, 1));
    channel = bootstrap.bind(socketAddress);
    return this;
  }
Esempio n. 2
0
 @Issue("JENKINS-15816")
 @SuppressWarnings({"unchecked", "rawtypes"})
 @Test
 public void timezoneOfID() throws Exception {
   TimeZone origTZ = TimeZone.getDefault();
   try {
     final Run r;
     String id;
     TimeZone.setDefault(TimeZone.getTimeZone("America/Chicago"));
     ExecutorService svc = Executors.newSingleThreadExecutor();
     try {
       r =
           svc.submit(
                   new Callable<Run>() {
                     @Override
                     public Run call() throws Exception {
                       return new Run(new StubJob(), 1234567890) {};
                     }
                   })
               .get();
       TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
       id = r.getId();
       assertEquals(
           id,
           svc.submit(
                   new Callable<String>() {
                     @Override
                     public String call() throws Exception {
                       return r.getId();
                     }
                   })
               .get());
     } finally {
       svc.shutdown();
     }
     TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
     svc = Executors.newSingleThreadExecutor();
     try {
       assertEquals(id, r.getId());
       assertEquals(
           id,
           svc.submit(
                   new Callable<String>() {
                     @Override
                     public String call() throws Exception {
                       return r.getId();
                     }
                   })
               .get());
     } finally {
       svc.shutdown();
     }
   } finally {
     TimeZone.setDefault(origTZ);
   }
 }
  @Test
  public void 用途_ワークキュー() throws Exception {
    o.l1("【どういうこと?】").e();
    o.l2("キューイングされたタスクを、順にデキューして、順に別のスレッドで実行。").e();

    o.l1("【どうすれば?】").e();
    o.l2("java.util.concurrent.Executors.newSingleThreadExecutor()ファクトリメソッドを使用。").e();

    o.l1("【たとえば?】").e();
    o.l2("newSingleThreadExecutor()でワークキューを作成。").e();

    o.l3("タスクがRunnableの場合").e();
    NameDecorateRunner runTask1 = new NameDecorateRunner("task1", 2);
    NameDecorateRunner runTask2 = new NameDecorateRunner("task2", 1);

    // executeされたタスクは1つの別スレッドで順々に処理される。
    ExecutorService executor = Executors.newSingleThreadExecutor();

    // 呼び出し順に処理が行われる
    executor.execute(runTask1);
    executor.execute(runTask2);

    // (ゆるやかな)終了指示
    executor.shutdown();

    // エグゼキューターの完了を待つ
    executor.awaitTermination(10 /* timeout */, TimeUnit.SECONDS);

    assertThat(runTask1.name, is("***task1***"));
    assertThat(runTask2.name, is("***task2***"));

    o.l3("タスクがCallableの場合").e();
    NameDecorateCaller callTask1 = new NameDecorateCaller("task1", 2);
    NameDecorateCaller callTask2 = new NameDecorateCaller("task2", 1);

    executor = Executors.newSingleThreadExecutor();

    Future<String> future1 = executor.submit(callTask1);
    Future<String> future2 = executor.submit(callTask2);

    executor.shutdown();

    // 処理の完了を待つ
    String result1 = future1.get();
    String result2 = future2.get();

    assertThat(result1, is("###task1###"));
    assertThat(result2, is("###task2###"));

    {
      /** 【補】invokeAllメソッドとinvokeAnyメソッド */
      // あるタスクの集まりの完了を待つことができるメソッド。
      // invokeAllメソッドは、タスクをすべて実行し、すべての完了を待つ。
      // invokeAnyメソッドは、タスクをすべて実行し、どれか1つでも完了することを待つ。
    }
  }
Esempio n. 4
0
 protected void startThreads() {
   if (mInitialized) {
     throw new IllegalArgumentException("Threads already initialized.");
   }
   mExecutor = Executors.newSingleThreadExecutor();
   mSendExecutor = Executors.newSingleThreadExecutor();
   mReceiveExecutor = Executors.newSingleThreadExecutor();
   mExecutor.execute(this);
   mInitialized = true;
 }
Esempio n. 5
0
 public void initializeExecutors() {
   if (namingService != null) {
     namingExecutor = Executors.newSingleThreadExecutor();
     namingExecutor.execute(namingService);
   }
   if (serverHandler != null) {
     serverExecutor = Executors.newSingleThreadExecutor();
     serverExecutor.execute(serverHandler);
   }
 }
  /** Called by Felix DM when starting this component. */
  protected void start() throws Exception {
    // start calculating avg
    m_avgExecutor = Executors.newSingleThreadExecutor();
    m_avgFuture =
        m_avgExecutor.submit(
            () -> {
              long oldTimeMillis = System.currentTimeMillis();
              while (!Thread.currentThread().isInterrupted()) {
                try {
                  long processedCount = getProcessedCount();
                  long currentTimeMillis = System.currentTimeMillis();
                  m_processedAvg = (1000.0 * processedCount) / (currentTimeMillis - oldTimeMillis);
                  oldTimeMillis = currentTimeMillis;

                  TimeUnit.MILLISECONDS.sleep(900);
                } catch (InterruptedException e) {
                  // Break out of our loop...
                  Thread.currentThread().interrupt();
                } catch (Exception e) {
                  // Ignore, not much we can do about this...
                  info(
                      "Failed to process sample(s)! Cause: %s",
                      (e.getMessage() == null ? "NullPointerException" : e.getMessage()));
                }
              }
            });

    // start producing
    m_processExecutor = Executors.newSingleThreadExecutor();
    m_processFuture =
        m_processExecutor.submit(
            () -> {
              while (!Thread.currentThread().isInterrupted() && !m_processExecutor.isShutdown()) {
                try {
                  processSampleData();
                  TimeUnit.MILLISECONDS.sleep(getTaskInterval());
                } catch (InterruptedException e) {
                  // Break out of our loop...
                  Thread.currentThread().interrupt();
                } catch (Exception e) {
                  // Ignore, not much we can do about this...
                  info(
                      "Failed to process sample(s)! Cause: %s",
                      (e.getMessage() == null ? "NullPointerException" : e.getMessage()));
                }
              }
            });
    info("Processor %s started...", getName());
  }
 protected void waitForConfirms(final String testTitle) throws Exception
 {
     try {
         FutureTask<?> waiter = new FutureTask<Object>(new Runnable() {
                 public void run() {
                     try {
                         channel.waitForConfirmsOrDie();
                     } catch (IOException e) {
                         throw (ShutdownSignalException)e.getCause();
                     } catch (InterruptedException _) {
                         fail(testTitle + ": interrupted");
                     }
                 }
             }, null);
         (Executors.newSingleThreadExecutor()).execute(waiter);
         waiter.get(10, TimeUnit.SECONDS);
     } catch (ExecutionException ee) {
         Throwable t = ee.getCause();
         if (t instanceof ShutdownSignalException) throw (ShutdownSignalException) t;
         if (t instanceof AssertionFailedError) throw (AssertionFailedError) t;
         throw (Exception)t;
     } catch (TimeoutException _) {
         fail(testTitle + ": timeout");
     }
 }
 /**
  * Executes the specified runnable on the worker thread of the view. Execution is performed
  * sequentially in the same sequence as the runnables have been passed to this method.
  */
 @Override
 public void execute(Runnable worker) {
   if (executor == null) {
     executor = Executors.newSingleThreadExecutor();
   }
   executor.execute(worker);
 }
  /**
   * Implements the Token Bucket algorithm to provide a maximum number of invocations within each
   * fixed time window. Useful for rate-limiting. If given a non-null executor, the scheduled
   * runnables are passed to that executor for execution at the rate limit. If executor is null, a
   * single-threaded executor is used
   *
   * @param executor the Executor which executes the Runnables. the executor is not called with the
   *     runnable until the rate limit has been fulfilled
   * @param invocations number of queries allowed during each time window
   * @param per the duration of each time window
   */
  public RateLimiter(Executor executor, final int invocations, final Duration per) {
    if (executor != null) {
      this.executor = executor;
    } else {
      this.executor = Executors.newSingleThreadExecutor();
    }

    // This thread fills the TokenBucket with available requests every time window
    ScheduledThreadPoolExecutor replenisher = new ScheduledThreadPoolExecutor(1);
    replenisher.scheduleAtFixedRate(
        new Runnable() {
          public void run() {
            int permitsToCreate = invocations - requestsAvailable.availablePermits();
            if (permitsToCreate > 0) {
              synchronized (requestsAvailable) {
                // bring the number of requests up to the maximum size per time window
                requestsAvailable.release(permitsToCreate);
              }
            }
          }
        },
        0,
        per.getMillis(),
        TimeUnit.MILLISECONDS);

    pump = new RunnablePump();
    pump.start();
  }
  /**
   * Creates a request to the server (with the whole process time set to the maximum of 5 seconds)
   * for the given {@code path} and {@code mediaType} that should result in the {@code
   * expectedResponse}.
   */
  private void _testExceptionInWriteResponseMethod(
      final String path, final String mediaType, final Response.Status expectedResponse)
      throws Exception {
    // Executor.
    final ExecutorService executor = Executors.newSingleThreadExecutor();

    final Future<Response> responseFuture =
        executor.submit(
            new Callable<Response>() {

              @Override
              public Response call() throws Exception {
                return target().path(path).request(mediaType).get();
              }
            });

    executor.shutdown();
    final boolean inTime = executor.awaitTermination(5000, TimeUnit.MILLISECONDS);

    // Asserts.
    assertTrue(inTime);

    // Response.
    final Response response = responseFuture.get();
    assertEquals(expectedResponse, response.getStatusInfo());
  }
Esempio n. 11
0
  public void start() throws Exception {
    m_leaderLatch =
        new LeaderLatch(
            m_client.get(),
            m_config.getMetaServerLeaderElectionZkPath(),
            m_config.getMetaServerName());

    m_leaderLatch.addListener(
        new LeaderLatchListener() {

          @Override
          public void notLeader() {
            log.info("Become follower");
            m_hasLeadership.set(false);
            m_leader.set(fetcheLeaderInfoFromZk());
            m_listenerContainer.notLeader(ClusterStateHolder.this);
          }

          @Override
          public void isLeader() {
            log.info("Become leader");
            m_hasLeadership.set(true);
            m_leader.set(fetcheLeaderInfoFromZk());
            m_listenerContainer.isLeader(ClusterStateHolder.this);
          }
        },
        Executors.newSingleThreadExecutor(
            HermesThreadFactory.create("LeaderLatchListenerPool", true)));

    // call notLeader before start, since if this is not leader, it won't trigger notLeader on start
    m_listenerContainer.notLeader(this);

    m_leaderLatch.start();
  }
  public void start() throws ExecutionException, InterruptedException {

    // Use the default MtGox settings
    Exchange mtGoxExchange = ExchangeFactory.INSTANCE.createExchange(MtGoxExchange.class.getName());

    // Configure BTC/USD ticker stream for MtGox
    ExchangeStreamingConfiguration btcusdConfiguration =
        new MtGoxStreamingConfiguration(10, 10000, Currencies.BTC, Currencies.USD, false);

    // Interested in the public streaming market data feed (no authentication)
    StreamingExchangeService btcusdStreamingMarketDataService =
        mtGoxExchange.getStreamingExchangeService(btcusdConfiguration);

    // Requesting initial order book using the polling service
    PollingMarketDataService marketDataService = mtGoxExchange.getPollingMarketDataService();
    MarketDataRunnable.book = marketDataService.getPartialOrderBook(Currencies.BTC, Currencies.USD);

    // Open the connections to the exchange
    btcusdStreamingMarketDataService.connect();

    ExecutorService executorService = Executors.newSingleThreadExecutor();
    Future<?> mtGoxMarketDataFuture =
        executorService.submit(new MarketDataRunnable(btcusdStreamingMarketDataService));

    // the thread waits here until the Runnable is done.
    mtGoxMarketDataFuture.get();

    executorService.shutdown();

    // Disconnect and exit
    System.out.println(Thread.currentThread().getName() + ": Disconnecting...");
    btcusdStreamingMarketDataService.disconnect();
  }
public class LogService2 {
  private static final long TIMEOUT = 10;
  private static final TimeUnit UNIT = TimeUnit.SECONDS;
  private final ExecutorService exec = Executors.newSingleThreadExecutor();
  private final PrintWriter writer;

  @GuardedBy("this")
  private boolean isShutdown;

  @GuardedBy("this")
  private int reservations;

  public void start() {}

  public LogService2(PrintWriter writer) {
    this.writer = writer;
  }

  public void stop() throws InterruptedException {
    try {
      exec.shutdown();
      exec.awaitTermination(TIMEOUT, UNIT);
    } finally {
      writer.close();
    }
  }

  public void log(String msg) throws InterruptedException {
    try {
      exec.execute(new WriteTask(msg));
    } catch (RejectedExecutionException ignored) {

    }
  }
}
 @Inject
 public WaveMap(
     final DeltaAndSnapshotStore waveletStore,
     final WaveletNotificationSubscriber notifiee,
     final LocalWaveletContainer.Factory localFactory,
     final RemoteWaveletContainer.Factory remoteFactory,
     @Named(CoreSettings.WAVE_SERVER_DOMAIN) final String waveDomain) {
   // NOTE(anorth): DeltaAndSnapshotStore is more specific than necessary, but
   // helps Guice out.
   // TODO(soren): inject a proper executor (with a pool of configurable size)
   this.store = waveletStore;
   final Executor lookupExecutor = Executors.newSingleThreadExecutor();
   waves =
       new MapMaker()
           .makeComputingMap(
               new Function<WaveId, Wave>() {
                 @Override
                 public Wave apply(WaveId waveId) {
                   ListenableFuture<ImmutableSet<WaveletId>> lookedupWavelets =
                       lookupWavelets(waveId, waveletStore, lookupExecutor);
                   return new Wave(
                       waveId,
                       lookedupWavelets,
                       notifiee,
                       localFactory,
                       remoteFactory,
                       waveDomain);
                 }
               });
 }
Esempio n. 15
0
 /** Run the command from an executor */
 private void runExecutor() {
   // Unlock Mode Codec
   try {
     session.getDataConn().getDataNetworkHandler().unlockModeCodec();
   } catch (FtpNoConnectionException e) {
     setTransferAbortedFromInternal(false);
     return;
   }
   // Run the command
   if (executorService == null) {
     executorService = Executors.newSingleThreadExecutor();
   }
   endOfCommand = new WaarpFuture(true);
   final ArrayList<Callable<Object>> tasks = new ArrayList<Callable<Object>>(1);
   tasks.add(Executors.callable(new FtpTransferExecutor(session, executingCommand)));
   try {
     executorService.invokeAll(tasks);
   } catch (InterruptedException e1) {
   }
   // XXX TRY FIX TO IMPROVE
   /*
   executorService.execute(new FtpTransferExecutor(session,
   	executingCommand));
   	*/
   try {
     commandFinishing.await();
   } catch (InterruptedException e) {
   }
 }
Esempio n. 16
0
  public static void main(String[] args) {

    ExecutorService threadPool = Executors.newSingleThreadExecutor();
    Future<Integer> future =
        threadPool.submit(
            new Callable<Integer>() {
              public Integer call() throws Exception {
                while (!Thread.interrupted()) {
                  Thread.sleep(1000); // 必须要有,不然cancel方法无效
                  System.out.println("call");
                }

                return 0;
              }
            });

    try {
      Thread.sleep(3000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    // threadPool.shutdown(); // 不会停止
    threadPool.shutdownNow();
    // future.cancel(true); // 停止

  }
Esempio n. 17
0
  private static boolean getResultWithTimeout(
      Callable<Boolean> startBloombergProcess, int timeout, TimeUnit timeUnit) {
    ExecutorService executor =
        Executors.newSingleThreadExecutor(
            new ThreadFactory() {
              @Override
              public Thread newThread(Runnable r) {
                Thread t = new Thread(r, "Bloomberg - bbcomm starter thread");
                t.setDaemon(true);
                return t;
              }
            });
    Future<Boolean> future = executor.submit(startBloombergProcess);

    try {
      return future.get(timeout, timeUnit);
    } catch (InterruptedException ignore) {
      Thread.currentThread().interrupt();
      return false;
    } catch (ExecutionException | TimeoutException e) {
      logger.error("Could not start bbcomm", e);
      return false;
    } finally {
      executor.shutdownNow();
      try {
        if (!executor.awaitTermination(100, TimeUnit.MILLISECONDS)) {
          logger.warn("bbcomm starter thread still running");
        }
      } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
      }
    }
  }
Esempio n. 18
0
 @Override
 protected void doInitialize() {
   m_watcherExecutorService =
       Executors.newSingleThreadExecutor(HermesThreadFactory.create("BrokerLeaseWatcher", true));
   m_brokerLeaseChangedWatcher = new BrokerLeaseChangedWatcher(m_watcherExecutorService, this);
   m_brokerLeaseAddedWatcher = new BrokerLeaseAddedWatcher(m_watcherExecutorService, this);
 }
  private InProcessEvaluationContext(
      InProcessPipelineOptions options,
      BundleFactory bundleFactory,
      Collection<AppliedPTransform<?, ?, ?>> rootTransforms,
      Map<PValue, Collection<AppliedPTransform<?, ?, ?>>> valueToConsumers,
      Map<AppliedPTransform<?, ?, ?>, String> stepNames,
      Collection<PCollectionView<?>> views) {
    this.options = checkNotNull(options);
    this.bundleFactory = checkNotNull(bundleFactory);
    checkNotNull(rootTransforms);
    checkNotNull(valueToConsumers);
    checkNotNull(stepNames);
    checkNotNull(views);
    this.stepNames = stepNames;

    this.watermarkManager =
        InMemoryWatermarkManager.create(
            NanosOffsetClock.create(), rootTransforms, valueToConsumers);
    this.sideInputContainer = InProcessSideInputContainer.create(this, views);

    this.applicationStateInternals = new ConcurrentHashMap<>();
    this.mergedCounters = new CounterSet();

    this.callbackExecutor = WatermarkCallbackExecutor.create(Executors.newSingleThreadExecutor());
  }
Esempio n. 20
0
  public ATSHook() {
    synchronized (LOCK) {
      if (executor == null) {

        executor =
            Executors.newSingleThreadExecutor(
                new ThreadFactoryBuilder().setDaemon(true).setNameFormat("ATS Logger %d").build());

        YarnConfiguration yarnConf = new YarnConfiguration();
        timelineClient = TimelineClient.createTimelineClient();
        timelineClient.init(yarnConf);
        timelineClient.start();

        ShutdownHookManager.addShutdownHook(
            new Runnable() {
              @Override
              public void run() {
                try {
                  executor.shutdown();
                  executor.awaitTermination(WAIT_TIME, TimeUnit.SECONDS);
                  executor = null;
                } catch (InterruptedException ie) {
                  /* ignore */
                }
                timelineClient.stop();
              }
            });
      }
    }

    LOG.info("Created ATS Hook");
  }
    @Override
    public Response apply(final ContainerRequestContext req) {
      // Suspend current request
      final ProcessingContext processingContext = processingContextProvider.get();
      processingContext.suspend();

      Executors.newSingleThreadExecutor()
          .submit(
              new Runnable() {

                @Override
                public void run() {
                  try {
                    Thread.sleep(500);
                  } catch (InterruptedException ex) {
                    ex.printStackTrace(System.err);
                  }

                  // Returning will enter the suspended request
                  processingContext.resume(Response.ok().entity(responseContent).build());
                }
              });

      return null;
    }
 public RecordWriter<IntermediateDataFormat<?>, Integer> getRecordWriter() {
   consumerFuture =
       Executors.newSingleThreadExecutor(
               new ThreadFactoryBuilder().setNameFormat("OutputFormatLoader-consumer").build())
           .submit(new ConsumerThread(context));
   return writer;
 }
Esempio n. 23
0
  @Test
  public void testAllRowsReaderWithException() throws Exception {
    AllRowsReader<String, String> reader =
        new AllRowsReader.Builder<String, String>(keyspace, CF_STANDARD1)
            .withPageSize(3)
            .withConcurrencyLevel(2)
            .forEachRow(
                new Function<Row<String, String>, Boolean>() {
                  @Override
                  public Boolean apply(Row<String, String> row) {
                    throw new RuntimeException("Very bad");
                  }
                })
            .build();

    Future<Boolean> future = Executors.newSingleThreadExecutor().submit(reader);

    try {
      boolean result = future.get();
      Assert.fail();
    } catch (Exception e) {
      Assert.assertTrue(e.getMessage().contains("Very bad"));
      LOG.info("Failed to execute", e);
    }
  }
Esempio n. 24
0
  public void testSlide() throws Exception {
    ExecutorService webThread = Executors.newSingleThreadExecutor();
    final Pusher pusher = new Pusher();

    Scripter rhiner = Scripter.create().start();
    rhiner.start();

    Craken r = Craken.inmemoryCreateWithTest();
    r.start();

    Radon radon =
        RadonConfiguration.newBuilder(9000)
            .add("/websocket/{id}", new BroadEchoWebSocket())
            .add("/script/{id}", new ScriptWebSocket(rhiner, r))
            .add(
                "/events/{id}",
                new EventSourceHandler() {
                  public void onOpen(EventSourceConnection conn) throws Exception {
                    pusher.addConnection(conn);
                  }

                  public void onClose(EventSourceConnection conn) throws Exception {
                    pusher.removeConnection(conn);
                  }
                })
            .add("/*", new SimpleStaticFileHandler(new File("./resource/docs/")))
            .createRadon();

    radon.start().get();
    pusher.pushPeriodicallyOn(webThread);

    new InfinityThread().startNJoin();
  }
Esempio n. 25
0
  @Before
  public void setUp() throws IOException, InterruptedException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(this, "query_command", tmp);
    workspace.setUp();
    Cell cell =
        new TestCellBuilder().setFilesystem(new ProjectFilesystem(workspace.getDestPath())).build();

    TestConsole console = new TestConsole();
    CommandRunnerParams params =
        CommandRunnerParamsForTesting.createCommandRunnerParamsForTesting(
            console,
            cell,
            new FakeAndroidDirectoryResolver(),
            new NoopArtifactCache(),
            BuckEventBusFactory.newInstance(),
            FakeBuckConfig.builder().build(),
            Platform.detect(),
            ImmutableMap.copyOf(System.getenv()),
            new FakeJavaPackageFinder(),
            new ObjectMapper(),
            Optional.<WebServer>absent());

    buckQueryEnvironment = new BuckQueryEnvironment(params, /* enableProfiling */ false);
    cellRoot = workspace.getDestPath();
    executor = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());
  }
  public void StartAsynchronousConsumer() {
    exService = Executors.newSingleThreadExecutor();
    exService.execute(
        new Runnable() {

          @Override
          public void run() {
            try {
              for (; ; ) {
                waitForConnection();
                synchronized (this) {
                  // this is very simple: reconnect every 5 seconds always. This
                  // could impact negatively
                  // the performance. More sophisticated approach would be,
                  // reconnect if no messages have
                  // been received for 1 second. Reconnect always after say 5
                  // minutes.
                  this.wait(5000);
                }
                disconnect();
              }
            } catch (InterruptedException ex) {
              // disconnect and exit
              disconnect();
            }
          }
        });
  }
  @Before
  public void setupStore() {
    InMemoryDOMDataStore operStore =
        new InMemoryDOMDataStore("OPER", MoreExecutors.newDirectExecutorService());
    InMemoryDOMDataStore configStore =
        new InMemoryDOMDataStore("CFG", MoreExecutors.newDirectExecutorService());
    schemaContext = TestModel.createTestContext();

    operStore.onGlobalContextUpdated(schemaContext);
    configStore.onGlobalContextUpdated(schemaContext);

    ImmutableMap<LogicalDatastoreType, DOMStore> stores =
        ImmutableMap.<LogicalDatastoreType, DOMStore>builder() //
            .put(CONFIGURATION, configStore) //
            .put(OPERATIONAL, operStore) //
            .build();

    commitExecutor = new CommitExecutorService(Executors.newSingleThreadExecutor());
    futureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(1, 5, "FCB");
    executor =
        new DeadlockDetectingListeningExecutorService(
            commitExecutor,
            TransactionCommitDeadlockException.DEADLOCK_EXCEPTION_SUPPLIER,
            futureExecutor);
    domBroker = new SerializedDOMDataBroker(stores, executor);
  }
Esempio n. 28
0
 void init() {
   for (int i = 0; i < threads; i++) {
     esOrderConsumer.execute(new PositionQueueSlurper());
   }
   topicFeed.addMessageListener(new StockStreamListener());
   mapNewOrders.addLocalEntryListener(new NewOrderListener());
   startStreamer();
   Executors.newSingleThreadExecutor()
       .execute(
           new Runnable() {
             public void run() {
               while (true) {
                 try {
                   Thread.sleep(5000);
                   long feeds = countReceivedStockUpdates.getAndSet(0) / 5;
                   long orders = countOrdersProcessed.getAndSet(0) / 5;
                   long events = countNewOrderEvents.getAndSet(0) / 5;
                   long views = countPositionViews.getAndSet(0) / 5;
                   log(
                       "Feeds:"
                           + feeds
                           + ", OrdersProcessed:"
                           + orders
                           + ", newOrderEvents:"
                           + events
                           + ", Views:"
                           + views);
                 } catch (Exception e) {
                   e.printStackTrace();
                 }
               }
             }
           });
 }
Esempio n. 29
0
  @Test
  public void testTwoEndPoints() throws Exception {
    new Thread(
            () -> {
              final ArrayList<ServiceDefinition> endpoints = new ArrayList<>();
              endpoints.add(DEF);
              endpoints.add(DEF2);

              final Server server = new Server(logger, handlerFactory());
              server.init(PORT, endpoints, Executors.newSingleThreadExecutor());
            })
        .start();

    final ClientFactory clientFactory = new MultiplexedClientFactory(PORT);

    final TestService.AsyncIface client = clientFactory.create(DEF, HOSTNAME);
    final TestResponse response = callTestService(client);
    logger.info("Received: " + response);
    assertEquals(response.getResult(), Handler.RESULT);

    final TestService2.AsyncIface client2 = clientFactory.create(DEF2, HOSTNAME);
    final TestResponse2 response2 = callTestService2(client2);
    logger.info("Received: " + response2);
    assertEquals(response2.getResult(), Handler2.RESULT);

    clientFactory.close();
  }
Esempio n. 30
0
  public Client() {
    api = new ClientApi(this);
    manager = new ClientManager(this);

    ExecutorService connectionExecutor = Executors.newSingleThreadExecutor();
    connectionExecutor.execute(new ConnectionHandler());
  }