Search in sources :

Example 26 with ScheduledExecutorService

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));
}
Also used : InstanceId(org.neo4j.cluster.InstanceId) StoreId(org.neo4j.kernel.impl.store.StoreId) ScheduledFuture(java.util.concurrent.ScheduledFuture) NeoStoreDataSource(org.neo4j.kernel.NeoStoreDataSource) SwitchToMaster(org.neo4j.kernel.ha.cluster.SwitchToMaster) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TO_SLAVE(org.neo4j.kernel.ha.cluster.HighAvailabilityMemberState.TO_SLAVE) Callable(java.util.concurrent.Callable) LifeSupport(org.neo4j.kernel.lifecycle.LifeSupport) NullLogProvider(org.neo4j.logging.NullLogProvider) Supplier(java.util.function.Supplier) Mockito.verifyZeroInteractions(org.mockito.Mockito.verifyZeroInteractions) Answer(org.mockito.stubbing.Answer) Mockito.doThrow(org.mockito.Mockito.doThrow) Future(java.util.concurrent.Future) PENDING(org.neo4j.kernel.ha.cluster.HighAvailabilityMemberState.PENDING) AssertableLogProvider(org.neo4j.logging.AssertableLogProvider) Matchers.eq(org.mockito.Matchers.eq) CancellationRequest(org.neo4j.helpers.CancellationRequest) Mockito.doAnswer(org.mockito.Mockito.doAnswer) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Matchers.anyLong(org.mockito.Matchers.anyLong) URI(java.net.URI) MismatchingStoreIdException(org.neo4j.kernel.impl.store.MismatchingStoreIdException) ExecutorService(java.util.concurrent.ExecutorService) HighAvailabilityMemberState(org.neo4j.kernel.ha.cluster.HighAvailabilityMemberState) InOrder(org.mockito.InOrder) ComException(org.neo4j.com.ComException) SwitchToSlaveCopyThenBranch(org.neo4j.kernel.ha.cluster.SwitchToSlaveCopyThenBranch) Test(org.junit.Test) Mockito.times(org.mockito.Mockito.times) AssertableLogProvider.inLog(org.neo4j.logging.AssertableLogProvider.inLog) Election(org.neo4j.cluster.protocol.election.Election) Mockito.when(org.mockito.Mockito.when) DataSourceManager(org.neo4j.kernel.impl.transaction.state.DataSourceManager) Executors(java.util.concurrent.Executors) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Matchers.any(org.mockito.Matchers.any) CountDownLatch(java.util.concurrent.CountDownLatch) NullLogService(org.neo4j.kernel.impl.logging.NullLogService) ClusterMemberAvailability(org.neo4j.cluster.member.ClusterMemberAvailability) Mockito.inOrder(org.mockito.Mockito.inOrder) SimpleLogService(org.neo4j.kernel.impl.logging.SimpleLogService) ClusterClient(org.neo4j.cluster.client.ClusterClient) HighAvailabilityMemberChangeEvent(org.neo4j.kernel.ha.cluster.HighAvailabilityMemberChangeEvent) Mockito.reset(org.mockito.Mockito.reset) Mockito.mock(org.mockito.Mockito.mock) ComException(org.neo4j.com.ComException) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) InstanceId(org.neo4j.cluster.InstanceId) ClusterMemberAvailability(org.neo4j.cluster.member.ClusterMemberAvailability) CountDownLatch(java.util.concurrent.CountDownLatch) Election(org.neo4j.cluster.protocol.election.Election) URI(java.net.URI) Callable(java.util.concurrent.Callable) ScheduledFuture(java.util.concurrent.ScheduledFuture) ClusterClient(org.neo4j.cluster.client.ClusterClient) SwitchToSlaveCopyThenBranch(org.neo4j.kernel.ha.cluster.SwitchToSlaveCopyThenBranch) HighAvailabilityMemberChangeEvent(org.neo4j.kernel.ha.cluster.HighAvailabilityMemberChangeEvent) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ExecutorService(java.util.concurrent.ExecutorService) ScheduledFuture(java.util.concurrent.ScheduledFuture) Future(java.util.concurrent.Future) TimeUnit(java.util.concurrent.TimeUnit) LifeSupport(org.neo4j.kernel.lifecycle.LifeSupport) Supplier(java.util.function.Supplier) SwitchToMaster(org.neo4j.kernel.ha.cluster.SwitchToMaster) CancellationRequest(org.neo4j.helpers.CancellationRequest) Test(org.junit.Test)

Example 27 with ScheduledExecutorService

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);
    }
}
Also used : Named(javax.inject.Named) ScheduledExecutorServiceProvider(org.glassfish.jersey.spi.ScheduledExecutorServiceProvider) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Annotation(java.lang.annotation.Annotation) ExecutorServiceProvider(org.glassfish.jersey.spi.ExecutorServiceProvider) ScheduledExecutorServiceProvider(org.glassfish.jersey.spi.ScheduledExecutorServiceProvider) Singleton(javax.inject.Singleton) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ExecutorService(java.util.concurrent.ExecutorService) List(java.util.List) LinkedList(java.util.LinkedList) HashMap(java.util.HashMap) Map(java.util.Map)

Example 28 with ScheduledExecutorService

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());
}
Also used : Response(javax.ws.rs.core.Response) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) WebTarget(javax.ws.rs.client.WebTarget) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test) JerseyTest(org.glassfish.jersey.test.JerseyTest)

Example 29 with ScheduledExecutorService

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();
    }
}
Also used : Bitmap(android.graphics.Bitmap) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Canvas(android.graphics.Canvas) Handler(android.os.Handler) Activity(android.app.Activity) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) View(android.view.View)

Example 30 with ScheduledExecutorService

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;
}
Also used : GroupMember(org.apache.curator.framework.recipes.nodes.GroupMember) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService)

Aggregations

ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)821 Test (org.junit.Test)267 CountDownLatch (java.util.concurrent.CountDownLatch)79 ArrayList (java.util.ArrayList)72 Test (org.testng.annotations.Test)72 IOException (java.io.IOException)71 ExecutorService (java.util.concurrent.ExecutorService)70 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)65 HashMap (java.util.HashMap)57 ScheduledThreadPoolExecutor (java.util.concurrent.ScheduledThreadPoolExecutor)53 List (java.util.List)51 Map (java.util.Map)51 TimeUnit (java.util.concurrent.TimeUnit)44 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)43 ThreadFactory (java.util.concurrent.ThreadFactory)40 CompletableFuture (java.util.concurrent.CompletableFuture)35 UUID (java.util.UUID)34 Cleanup (lombok.Cleanup)31 ExecutionException (java.util.concurrent.ExecutionException)30 HashSet (java.util.HashSet)25