use of java.util.concurrent.ScheduledExecutorService in project neo4j by neo4j.
the class HighAvailabilityModeSwitcherTest method shouldRecognizeNewMasterIfNewMasterBecameAvailableDuringSwitch.
@Test
public void shouldRecognizeNewMasterIfNewMasterBecameAvailableDuringSwitch() throws Throwable {
// When messages coming in the following ordering, the slave should detect that the master id has changed
// M1: Get masterIsAvailable for instance 1 at PENDING state, changing PENDING -> TO_SLAVE
// M2: Get masterIsAvailable for instance 2 at TO_SLAVE state, changing TO_SLAVE -> TO_SLAVE
// Given
final CountDownLatch firstMasterAvailableHandled = new CountDownLatch(1);
final CountDownLatch secondMasterAvailableComes = new CountDownLatch(1);
final CountDownLatch secondMasterAvailableHandled = new CountDownLatch(1);
SwitchToSlaveCopyThenBranch switchToSlave = mock(SwitchToSlaveCopyThenBranch.class);
HighAvailabilityModeSwitcher modeSwitcher = new HighAvailabilityModeSwitcher(switchToSlave, mock(SwitchToMaster.class), mock(Election.class), mock(ClusterMemberAvailability.class), mock(ClusterClient.class), mock(Supplier.class), new InstanceId(4), new ComponentSwitcherContainer(), neoStoreDataSourceSupplierMock(), NullLogService.getInstance()) {
@Override
ScheduledExecutorService createExecutor() {
final ScheduledExecutorService executor = mock(ScheduledExecutorService.class);
final ExecutorService realExecutor = Executors.newSingleThreadExecutor();
when(executor.submit(any(Runnable.class))).thenAnswer((Answer<Future<?>>) invocation -> realExecutor.submit((Runnable) () -> ((Runnable) invocation.getArguments()[0]).run()));
when(executor.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))).thenAnswer((Answer<Future<?>>) invocation -> {
realExecutor.submit((Callable<Void>) () -> {
firstMasterAvailableHandled.countDown();
secondMasterAvailableComes.await();
((Runnable) invocation.getArguments()[0]).run();
secondMasterAvailableHandled.countDown();
return null;
});
return mock(ScheduledFuture.class);
});
return executor;
}
};
modeSwitcher.init();
modeSwitcher.start();
modeSwitcher.listeningAt(URI.create("ha://server3?serverId=3"));
// When
// masterIsAvailable for instance 1
URI uri1 = URI.create("ha://server1");
// The first masterIsAvailable should fail so that the slave instance stops at TO_SLAVE state
doThrow(new ComException("Fail to switch to slave and reschedule to retry")).when(switchToSlave).switchToSlave(any(LifeSupport.class), any(URI.class), eq(uri1), any(CancellationRequest.class));
modeSwitcher.masterIsAvailable(new HighAvailabilityMemberChangeEvent(PENDING, TO_SLAVE, new InstanceId(1), uri1));
// wait until the first masterIsAvailable triggers the exception handling
firstMasterAvailableHandled.await();
verify(switchToSlave).switchToSlave(any(LifeSupport.class), any(URI.class), eq(uri1), any(CancellationRequest.class));
// masterIsAvailable for instance 2
URI uri2 = URI.create("ha://server2");
modeSwitcher.masterIsAvailable(new HighAvailabilityMemberChangeEvent(TO_SLAVE, TO_SLAVE, new InstanceId(2), uri2));
secondMasterAvailableComes.countDown();
// wait until switchToSlave method is invoked again
secondMasterAvailableHandled.await();
// Then
// switchToSlave should be retried with new master id
verify(switchToSlave).switchToSlave(any(LifeSupport.class), any(URI.class), eq(uri2), any(CancellationRequest.class));
}
use of java.util.concurrent.ScheduledExecutorService in project jersey by jersey.
the class ExecutorProviders method createInjectionBindings.
/**
* Create qualified {@link java.util.concurrent.ExecutorService} and {@link java.util.concurrent.ScheduledExecutorService}
* injection bindings based on the registered providers implementing the
* {@link org.glassfish.jersey.spi.ExecutorServiceProvider} and/or
* {@link org.glassfish.jersey.spi.ScheduledExecutorServiceProvider} SPI.
* <p>
* This method supports creation of qualified injection bindings based on custom
* {@link javax.inject.Qualifier qualifier annotations} attached to the registered provider implementation classes
* as well as named injection bindings based on the {@link javax.inject.Named} qualifier annotation attached to the
* registered provider implementation classes.
* </p>
*
* @param injectionManager application's injection manager.
*/
public static void createInjectionBindings(InjectionManager injectionManager) {
/*
* Add ExecutorService into DI framework.
*/
Map<Class<? extends Annotation>, List<ExecutorServiceProvider>> executorProviderMap = getQualifierToProviderMap(injectionManager, ExecutorServiceProvider.class);
for (Map.Entry<Class<? extends Annotation>, List<ExecutorServiceProvider>> qualifierToProviders : executorProviderMap.entrySet()) {
Class<? extends Annotation> qualifierAnnotationClass = qualifierToProviders.getKey();
Iterator<ExecutorServiceProvider> bucketProviderIterator = qualifierToProviders.getValue().iterator();
ExecutorServiceProvider executorProvider = bucketProviderIterator.next();
logExecutorServiceProvider(qualifierAnnotationClass, bucketProviderIterator, executorProvider);
SupplierInstanceBinding<ExecutorService> descriptor = Bindings.supplier(new ExecutorServiceSupplier(executorProvider)).in(Singleton.class).to(ExecutorService.class);
Annotation qualifier = executorProvider.getClass().getAnnotation(qualifierAnnotationClass);
if (qualifier instanceof Named) {
descriptor.named(((Named) qualifier).value());
} else {
descriptor.qualifiedBy(qualifier);
}
injectionManager.register(descriptor);
}
/*
* Add ScheduledExecutorService into DI framework.
*/
Map<Class<? extends Annotation>, List<ScheduledExecutorServiceProvider>> schedulerProviderMap = getQualifierToProviderMap(injectionManager, ScheduledExecutorServiceProvider.class);
for (Map.Entry<Class<? extends Annotation>, List<ScheduledExecutorServiceProvider>> qualifierToProviders : schedulerProviderMap.entrySet()) {
Class<? extends Annotation> qualifierAnnotationClass = qualifierToProviders.getKey();
Iterator<ScheduledExecutorServiceProvider> bucketProviderIterator = qualifierToProviders.getValue().iterator();
ScheduledExecutorServiceProvider executorProvider = bucketProviderIterator.next();
logScheduledExecutorProvider(qualifierAnnotationClass, bucketProviderIterator, executorProvider);
SupplierInstanceBinding<ScheduledExecutorService> descriptor = Bindings.supplier(new ScheduledExecutorServiceSupplier(executorProvider)).in(Singleton.class).to(ScheduledExecutorService.class);
if (!executorProviderMap.containsKey(qualifierAnnotationClass)) {
// it is safe to register binding for ExecutorService too...
descriptor.to(ExecutorService.class);
}
Annotation qualifier = executorProvider.getClass().getAnnotation(qualifierAnnotationClass);
if (qualifier instanceof Named) {
descriptor.named(((Named) qualifier).value());
} else {
descriptor.qualifiedBy(qualifier);
}
injectionManager.register(descriptor);
}
}
use of java.util.concurrent.ScheduledExecutorService in project jersey by jersey.
the class SseEventSinkCloseTest method testClose.
/**
* The test test that SSE connection is really closed when SseEventSource.close() is called.
* <p/>
* This test is very HttpURLConnection and Grizzly server specific, so it will probably fail, if other client and server
* transport are used.
*/
@Test
public void testClose() throws InterruptedException {
WebTarget sseTarget = target("sse");
final CountDownLatch eventLatch = new CountDownLatch(3);
javax.ws.rs.sse.SseEventSource eventSource = javax.ws.rs.sse.SseEventSource.target(sseTarget).build();
eventSource.subscribe((event) -> eventLatch.countDown());
eventSource.open();
// Tell server to send us 3 events
for (int i = 0; i < 3; i++) {
final String response = target("sse/send").request().get().readEntity(String.class);
assertEquals("OK", response);
}
// ... and wait for the events to be processed by the client side, then close the eventSource
assertTrue(eventLatch.await(5, TimeUnit.SECONDS));
eventSource.close();
assertEquals("SseEventSource should have been already closed", false, eventSource.isOpen());
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
CountDownLatch closeLatch = new CountDownLatch(100);
executor.scheduleAtFixedRate(() -> {
if (output.isClosed()) {
// countdown to zero
for (int i = 0; i < closeLatch.getCount(); i++) {
closeLatch.countDown();
return;
}
}
final Response response = target("sse/send").request().get();
LOGGER.info(200 == response.getStatus() ? "Still alive" : "Error received");
closeLatch.countDown();
}, 0, 100, TimeUnit.MILLISECONDS);
assertTrue(closeLatch.await(10000, TimeUnit.MILLISECONDS));
executor.shutdown();
assertTrue("SseEventOutput should have been already closed.", output.isClosed());
}
use of java.util.concurrent.ScheduledExecutorService in project UltimateAndroid by cymcsg.
the class IntentUtils method startPreviewActivity.
/**
* start screen capture after "delay" milliseconds, so the previous activity's
* state recover to normal state, such as button click, list item click,wait
* them to normal state so we can make a good screen capture
*
* @param context
* @param intent
* @param delay time in milliseconds
*/
public static void startPreviewActivity(final Context context, final Intent intent, long delay) {
final Handler mainThread = new Handler(Looper.getMainLooper());
final Runnable postAction = new Runnable() {
@Override
public void run() {
context.startActivity(intent);
}
};
/** process screen capture on background thread */
Runnable action = new Runnable() {
@Override
public void run() {
/**
* activity's root layout id, you can change the android.R.id.content to your root
* layout id
*/
final View contentView = ((Activity) context).findViewById(android.R.id.content);
ByteArrayOutputStream baos = null;
Bitmap bitmap = null;
try {
bitmap = Bitmap.createBitmap(contentView.getWidth(), contentView.getHeight(), Bitmap.Config.ARGB_8888);
contentView.draw(new Canvas(bitmap));
baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, baos);
intent.putExtra(KEY_PREVIEW_IMAGE, baos.toByteArray());
} finally {
try {
/** no need to close, actually do nothing */
if (null != baos)
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
if (null != bitmap && !bitmap.isRecycled()) {
bitmap.recycle();
bitmap = null;
}
}
mainThread.post(postAction);
}
};
if (delay > 0) {
ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
worker.schedule(action, delay, TimeUnit.MILLISECONDS);
} else {
action.run();
}
}
use of java.util.concurrent.ScheduledExecutorService in project zipkin by openzipkin.
the class ZooKeeperCollectorSampler method storeRateGroup.
static GroupMember storeRateGroup(CuratorFramework client, Builder builder, Closer closer, AtomicInteger spanCount, AtomicInteger storeRate) {
String storeRatePath = ensureExists(client, builder.basePath + "/storeRates");
GroupMember storeRateGroup = closer.register(new GroupMember(client, storeRatePath, builder.id));
log.debug("{} is to join the group {}", builder.id, storeRatePath);
storeRateGroup.start();
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
closer.register(executor::shutdown);
ScheduledFuture<?> future = executor.scheduleAtFixedRate(() -> {
int oldValue = storeRate.get();
int newValue = (int) (1.0 * spanCount.getAndSet(0) * 60 / builder.updateFrequency);
log.debug("Store rates was: {} now {}", oldValue, newValue);
if (oldValue != newValue) {
storeRate.set(newValue);
storeRateGroup.setThisData(Integer.valueOf(newValue).toString().getBytes(UTF_8));
}
}, 0, builder.updateFrequency, TimeUnit.SECONDS);
closer.register(() -> future.cancel(true));
return storeRateGroup;
}
Aggregations