List of usage examples for java.util.concurrent Executor Executor
Executor
From source file:io.servicecomb.loadbalance.LoadbalanceHandler.java
private void sendWithRetry(Invocation invocation, AsyncResponse asyncResp, final LoadBalancer chosenLB) throws Exception { long time = System.currentTimeMillis(); // retry in loadbalance, 2.0 feature final int currentHandler = invocation.getHandlerIndex(); final SyncResponseExecutor orginExecutor; final Executor newExecutor; if (invocation.getResponseExecutor() instanceof SyncResponseExecutor) { orginExecutor = (SyncResponseExecutor) invocation.getResponseExecutor(); newExecutor = new Executor() { @Override/* w w w . j av a 2 s .com*/ public void execute(Runnable command) { // retry?, ????; // ??event-loop?? RETRY_POOL.submit(command); } }; invocation.setResponseExecutor(newExecutor); } else { orginExecutor = null; newExecutor = null; } ExecutionListener<Invocation, Response> listener = new ExecutionListener<Invocation, Response>() { @Override public void onExecutionStart(ExecutionContext<Invocation> context) throws AbortExecutionException { } @Override public void onStartWithServer(ExecutionContext<Invocation> context, ExecutionInfo info) throws AbortExecutionException { } @Override public void onExceptionWithServer(ExecutionContext<Invocation> context, Throwable exception, ExecutionInfo info) { LOGGER.error("onExceptionWithServer msg {}; server {}", exception.getMessage(), context.getRequest().getEndpoint()); } @Override public void onExecutionSuccess(ExecutionContext<Invocation> context, Response response, ExecutionInfo info) { if (orginExecutor != null) { orginExecutor.execute(() -> { asyncResp.complete(response); }); } else { asyncResp.complete(response); } } @Override public void onExecutionFailed(ExecutionContext<Invocation> context, Throwable finalException, ExecutionInfo info) { if (orginExecutor != null) { orginExecutor.execute(() -> { asyncResp.consumerFail(finalException); }); } else { asyncResp.consumerFail(finalException); } } }; List<ExecutionListener<Invocation, Response>> listeners = new ArrayList<>(0); listeners.add(listener); ExecutionContext<Invocation> context = new ExecutionContext<>(invocation, null, null, null); LoadBalancerCommand<Response> command = LoadBalancerCommand.<Response>builder().withLoadBalancer(chosenLB) .withServerLocator(invocation) .withRetryHandler(ExtensionsManager.createRetryHandler(invocation.getMicroserviceName())) .withListeners(listeners).withExecutionContext(context).build(); Observable<Response> observable = command.submit(new ServerOperation<Response>() { public Observable<Response> call(Server s) { return Observable.create(f -> { try { ((CseServer) s).setLastVisitTime(time); chosenLB.getLoadBalancerStats().incrementNumRequests(s); invocation.setHandlerIndex(currentHandler); // for retry invocation.setEndpoint(((CseServer) s).getEndpoint()); invocation.next(resp -> { if (resp.isFailed()) { LOGGER.error("service call error, msg is {}, server is {} ", ((Throwable) resp.getResult()).getMessage(), s); chosenLB.getLoadBalancerStats().incrementSuccessiveConnectionFailureCount(s); f.onError(resp.getResult()); } else { chosenLB.getLoadBalancerStats().incrementActiveRequestsCount(s); chosenLB.getLoadBalancerStats().noteResponseTime(s, (System.currentTimeMillis() - time)); f.onNext(resp); f.onCompleted(); } }); } catch (Exception e) { LOGGER.error("execution error, msg is " + e.getMessage()); f.onError(e); } }); } }); observable.subscribe(response -> { }, error -> { }, () -> { }); }
From source file:org.apache.stratos.manager.subscription.utils.CartridgeSubscriptionUtils.java
public static void publishTenantSubscribedEvent(int tenantId, String serviceName, Set<String> clusterIds) { Executor exec = new Executor() { @Override//from ww w. j a va2 s .c o m public void execute(Runnable command) { command.run(); } }; exec.execute(new TenantSubscribedEventPublisher(tenantId, serviceName, clusterIds)); }
From source file:co.cask.cdap.internal.app.runtime.spark.SparkRuntimeService.java
@Override protected Executor executor() { // Always execute in new daemon thread. return new Executor() { @Override/*from w ww . j a v a 2 s . co m*/ public void execute(final Runnable runnable) { final Thread t = new Thread(new Runnable() { @Override public void run() { // note: this sets logging context on the thread level LoggingContextAccessor.setLoggingContext(context.getLoggingContext()); runnable.run(); } }); t.setDaemon(true); t.setName(getServiceName()); t.start(); } }; }
From source file:org.apache.servicecomb.loadbalance.LoadbalanceHandler.java
private void sendWithRetry(Invocation invocation, AsyncResponse asyncResp, final LoadBalancer chosenLB) throws Exception { long time = System.currentTimeMillis(); // retry in loadbalance, 2.0 feature final int currentHandler = invocation.getHandlerIndex(); final SyncResponseExecutor orginExecutor; final Executor newExecutor; if (invocation.getResponseExecutor() instanceof SyncResponseExecutor) { orginExecutor = (SyncResponseExecutor) invocation.getResponseExecutor(); newExecutor = new Executor() { @Override//from w w w. j ava 2 s .c o m public void execute(Runnable command) { // retry?, ????; // ??event-loop?? RETRY_POOL.submit(command); } }; invocation.setResponseExecutor(newExecutor); } else { orginExecutor = null; newExecutor = null; } ExecutionListener<Invocation, Response> listener = new ExecutionListener<Invocation, Response>() { @Override public void onExecutionStart(ExecutionContext<Invocation> context) throws AbortExecutionException { } @Override public void onStartWithServer(ExecutionContext<Invocation> context, ExecutionInfo info) throws AbortExecutionException { } @Override public void onExceptionWithServer(ExecutionContext<Invocation> context, Throwable exception, ExecutionInfo info) { LOGGER.error("Invoke server failed. Operation {}; server {}; {}-{} msg {}", context.getRequest().getInvocationQualifiedName(), context.getRequest().getEndpoint(), info.getNumberOfPastServersAttempted(), info.getNumberOfPastAttemptsOnServer(), exception.getMessage()); } @Override public void onExecutionSuccess(ExecutionContext<Invocation> context, Response response, ExecutionInfo info) { if (info.getNumberOfPastServersAttempted() > 0 || info.getNumberOfPastAttemptsOnServer() > 0) { LOGGER.error("Invoke server success. Operation {}; server {}", context.getRequest().getInvocationQualifiedName(), context.getRequest().getEndpoint()); } if (orginExecutor != null) { orginExecutor.execute(() -> { asyncResp.complete(response); }); } else { asyncResp.complete(response); } } @Override public void onExecutionFailed(ExecutionContext<Invocation> context, Throwable finalException, ExecutionInfo info) { if (orginExecutor != null) { orginExecutor.execute(() -> { asyncResp.consumerFail(finalException); }); } else { asyncResp.consumerFail(finalException); } } }; List<ExecutionListener<Invocation, Response>> listeners = new ArrayList<>(0); listeners.add(listener); ExecutionContext<Invocation> context = new ExecutionContext<>(invocation, null, null, null); LoadBalancerCommand<Response> command = LoadBalancerCommand.<Response>builder() .withLoadBalancer(new RetryLoadBalancer(chosenLB)).withServerLocator(invocation) .withRetryHandler(ExtensionsManager.createRetryHandler(invocation.getMicroserviceName())) .withListeners(listeners).withExecutionContext(context).build(); Observable<Response> observable = command.submit(new ServerOperation<Response>() { public Observable<Response> call(Server s) { return Observable.create(f -> { try { ServiceCombServer server = (ServiceCombServer) s; chosenLB.getLoadBalancerStats().incrementNumRequests(s); invocation.setHandlerIndex(currentHandler); // for retry invocation.setEndpoint(server.getEndpoint()); invocation.next(resp -> { if (isFailedResponse(resp)) { LOGGER.error("service {}, call error, msg is {}, server is {} ", invocation.getInvocationQualifiedName(), ((Throwable) resp.getResult()).getMessage(), s); chosenLB.getLoadBalancerStats().incrementSuccessiveConnectionFailureCount(s); ServiceCombLoadBalancerStats.INSTANCE.markFailure(server); f.onError(resp.getResult()); } else { chosenLB.getLoadBalancerStats().incrementActiveRequestsCount(s); chosenLB.getLoadBalancerStats().noteResponseTime(s, (System.currentTimeMillis() - time)); ServiceCombLoadBalancerStats.INSTANCE.markSuccess(server); f.onNext(resp); f.onCompleted(); } }); } catch (Exception e) { LOGGER.error("execution error, msg is " + e.getMessage()); f.onError(e); } }); } }); observable.subscribe(response -> { }, error -> { }, () -> { }); }
From source file:io.selendroid.ServerInstrumentation.java
private Executor provideMainThreadExecutor(Looper mainLooper) { final Handler handler = new Handler(mainLooper); return new Executor() { @Override//from w w w . ja v a2s . com public void execute(Runnable runnable) { handler.post(runnable); } }; }
From source file:co.cask.cdap.security.server.ExternalAuthenticationServer.java
@Override protected Executor executor(State state) { final AtomicInteger id = new AtomicInteger(); //noinspection NullableProblems final Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() { @Override/*from w w w . jav a 2s. c o m*/ public void uncaughtException(Thread t, Throwable e) { } }; return new Executor() { @Override public void execute(Runnable runnable) { Thread t = new Thread(runnable, String.format("ExternalAuthenticationServer-%d", id.incrementAndGet())); t.setUncaughtExceptionHandler(h); t.start(); } }; }
From source file:jenkins.model.Jenkins.java
/** * Called to shut down the system./* w ww . java 2 s . co m*/ */ @edu.umd.cs.findbugs.annotations.SuppressWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD") public void cleanUp() { for (ItemListener l : ItemListener.all()) l.onBeforeShutdown(); try { final TerminatorFinder tf = new TerminatorFinder(pluginManager != null ? pluginManager.uberClassLoader : Thread.currentThread().getContextClassLoader()); new Reactor(tf).execute(new Executor() { @Override public void execute(Runnable command) { command.run(); } }); } catch (InterruptedException e) { LOGGER.log(SEVERE, "Failed to execute termination", e); e.printStackTrace(); } catch (ReactorException e) { LOGGER.log(SEVERE, "Failed to execute termination", e); } catch (IOException e) { LOGGER.log(SEVERE, "Failed to execute termination", e); } final Set<Future<?>> pending = new HashSet<Future<?>>(); terminating = true; // JENKINS-28840 we know we will be interrupting all the Computers so get the Queue lock once for all Queue.withLock(new Runnable() { @Override public void run() { for (Computer c : computers.values()) { c.interrupt(); killComputer(c); pending.add(c.disconnect(null)); } } }); if (udpBroadcastThread != null) udpBroadcastThread.shutdown(); if (dnsMultiCast != null) dnsMultiCast.close(); interruptReloadThread(); java.util.Timer timer = Trigger.timer; if (timer != null) { timer.cancel(); } // TODO: how to wait for the completion of the last job? Trigger.timer = null; Timer.shutdown(); if (tcpSlaveAgentListener != null) tcpSlaveAgentListener.shutdown(); if (pluginManager != null) // be defensive. there could be some ugly timing related issues pluginManager.stop(); if (getRootDir().exists()) // if we are aborting because we failed to create JENKINS_HOME, // don't try to save. Issue #536 getQueue().save(); threadPoolForLoad.shutdown(); for (Future<?> f : pending) try { f.get(10, TimeUnit.SECONDS); // if clean up operation didn't complete in time, we fail the test } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; // someone wants us to die now. quick! } catch (ExecutionException e) { LOGGER.log(Level.WARNING, "Failed to shut down properly", e); } catch (TimeoutException e) { LOGGER.log(Level.WARNING, "Failed to shut down properly", e); } LogFactory.releaseAll(); theInstance = null; }