Example usage for java.lang Thread join

List of usage examples for java.lang Thread join

Introduction

In this page you can find the example usage for java.lang Thread join.

Prototype

public final void join() throws InterruptedException 

Source Link

Document

Waits for this thread to die.

Usage

From source file:com.thoughtworks.go.agent.bootstrapper.AgentBootstrapperTest.java

@Test
public void shouldNotDieWhenInvocationOfLauncherRaisesException_butCreationOfLauncherWentThrough()
        throws InterruptedException {
    final Semaphore waitForLauncherInvocation = new Semaphore(1);
    waitForLauncherInvocation.acquire();
    final AgentBootstrapper bootstrapper = new AgentBootstrapper() {
        @Override/*from   w ww  . jav  a  2  s  .  c  o m*/
        AgentLauncherCreator getLauncherCreator() {
            return new AgentLauncherCreator() {
                public AgentLauncher createLauncher() {
                    return new AgentLauncher() {
                        public int launch(AgentLaunchDescriptor descriptor) {
                            try {
                                throw new RuntimeException("fail!!! i say.");
                            } finally {
                                if (waitForLauncherInvocation.availablePermits() == 0) {
                                    waitForLauncherInvocation.release();
                                }
                            }
                        }

                    };
                }

                @Override
                public void close() {
                }
            };
        }
    };

    final AgentBootstrapper spyBootstrapper = stubJVMExit(bootstrapper);

    Thread stopLoopThd = new Thread(new Runnable() {
        public void run() {
            try {
                waitForLauncherInvocation.acquire();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            ReflectionUtil.setField(spyBootstrapper, "loop", false);
        }
    });
    stopLoopThd.start();
    try {
        spyBootstrapper.go(true,
                new AgentBootstrapperArgs(new URL("http://" + "ghost-name" + ":" + 3518 + "/go"), null,
                        AgentBootstrapperArgs.SslMode.NONE));
        stopLoopThd.join();
    } catch (Exception e) {
        fail("should not have propagated exception thrown while invoking the launcher");
    }
}

From source file:com.thoughtworks.go.agent.bootstrapper.AgentBootstrapperTest.java

@Test
public void shouldNotDieWhenCreationOfLauncherRaisesException() throws InterruptedException {
    final Semaphore waitForLauncherCreation = new Semaphore(1);
    waitForLauncherCreation.acquire();//from  w  w w.j  a  va 2  s. c  o  m
    final boolean[] reLaunchWaitIsCalled = new boolean[1];
    final AgentBootstrapper bootstrapper = new AgentBootstrapper() {
        @Override
        void waitForRelaunchTime() {
            assertThat(waitTimeBeforeRelaunch, is(0));
            reLaunchWaitIsCalled[0] = true;
            super.waitForRelaunchTime();
        }

        @Override
        AgentLauncherCreator getLauncherCreator() {
            return new AgentLauncherCreator() {
                public AgentLauncher createLauncher() {
                    try {
                        throw new RuntimeException("i bombed");
                    } finally {
                        if (waitForLauncherCreation.availablePermits() == 0) {
                            waitForLauncherCreation.release();
                        }
                    }
                }

                @Override
                public void close() {
                }
            };
        }
    };

    final AgentBootstrapper spyBootstrapper = stubJVMExit(bootstrapper);

    Thread stopLoopThd = new Thread(new Runnable() {
        public void run() {
            try {
                waitForLauncherCreation.acquire();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            ReflectionUtil.setField(spyBootstrapper, "loop", false);
        }
    });
    stopLoopThd.start();
    try {
        spyBootstrapper.go(true,
                new AgentBootstrapperArgs(new URL("http://" + "ghost-name" + ":" + 3518 + "/go"), null,
                        AgentBootstrapperArgs.SslMode.NONE));
        stopLoopThd.join();
    } catch (Exception e) {
        fail("should not have propagated exception thrown while creating launcher");
    }
    assertThat(reLaunchWaitIsCalled[0], is(true));
}

From source file:com.thoughtworks.go.server.service.BackupServiceIntegrationTest.java

@Test
public void shouldExecutePostBackupScriptAndReturnResultOnSuccess() throws InterruptedException {
    final Semaphore waitForBackupToComplete = new Semaphore(1);
    GoConfigService configService = mock(GoConfigService.class);
    ServerConfig serverConfig = new ServerConfig();
    serverConfig.setBackupConfig(new BackupConfig(null, "jcmd", false, false));
    when(configService.serverConfig()).thenReturn(serverConfig);
    GoMailSender goMailSender = mock(GoMailSender.class);
    when(configService.getMailSender()).thenReturn(goMailSender);
    when(configService.adminEmail()).thenReturn("mail@admin.com");
    when(configService.isUserAdmin(admin)).thenReturn(true);
    TimeProvider timeProvider = mock(TimeProvider.class);
    DateTime now = new DateTime();
    when(timeProvider.currentDateTime()).thenReturn(now);

    final MessageCollectingBackupUpdateListener backupUpdateListener = new MessageCollectingBackupUpdateListener(
            waitForBackupToComplete);//w ww .j a  v a  2s .  c  om

    waitForBackupToComplete.acquire();
    backupService = new BackupService(artifactsDirHolder, configService, timeProvider, backupInfoRepository,
            systemEnvironment, configRepository, databaseStrategy, backupQueue);
    Thread backupThd = new Thread(() -> backupService.startBackup(admin, backupUpdateListener));

    backupThd.start();
    waitForBackupToComplete.acquire();
    assertThat(backupUpdateListener.getMessages()
            .contains(BackupProgressStatus.POST_BACKUP_SCRIPT_COMPLETE.getMessage()), is(true));
    backupThd.join();
}

From source file:ste.web.http.api.BugFreeApiHandlerExec.java

@Test
public void running_multiple_thread_in_different_contexts() throws Exception {
    final HttpSessionContext CTX1 = new HttpSessionContext();
    final HttpSessionContext CTX2 = new HttpSessionContext();
    CTX1.setAttribute(HttpCoreContext.HTTP_CONNECTION, getConnection());
    CTX2.setAttribute(HttpCoreContext.HTTP_CONNECTION, getConnection());
    Thread t1 = new Thread(new Runnable() {
        @Override/*from ww  w .  j av  a 2 s.  c  o m*/
        public void run() {
            try {
                handler.handle(request("/api/app/get/multithreading"), response, CTX1);
            } catch (Exception x) {
                x.printStackTrace();
            }
        }
    });
    Thread t2 = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                handler.handle(request("/api/app/get/multithreading"), response, CTX2);
            } catch (Exception x) {
                x.printStackTrace();
            }
        }
    });
    t1.start();
    t2.start();
    t1.join();
    t2.join();
    then(CTX1.get("view")).isEqualTo(t1.getName());
    then(CTX2.get("view")).isEqualTo(t2.getName());
}

From source file:com.thoughtworks.go.server.service.BackupServiceIntegrationTest.java

@Test
public void shouldReturnIfBackupIsInProgress() throws InterruptedException {
    final Semaphore waitForBackupToBegin = new Semaphore(1);
    final Semaphore waitForAssertion_whichHasToHappen_whileBackupIsRunning = new Semaphore(1);

    Database databaseStrategyMock = mock(Database.class);
    doAnswer((Answer<Object>) invocationOnMock -> {
        waitForBackupToBegin.release();//from   w  ww  . ja v  a  2 s .co  m
        waitForAssertion_whichHasToHappen_whileBackupIsRunning.acquire();
        return null;
    }).when(databaseStrategyMock).backup(any(File.class));

    final BackupService backupService = new BackupService(artifactsDirHolder, goConfigService,
            new TimeProvider(), backupInfoRepository, systemEnvironment, configRepository, databaseStrategyMock,
            null);

    waitForBackupToBegin.acquire();
    Thread thd = new Thread(() -> backupService.startBackup(admin));
    thd.start();

    waitForAssertion_whichHasToHappen_whileBackupIsRunning.acquire();
    waitForBackupToBegin.acquire();
    assertThat(backupService.isBackingUp(), is(true));
    waitForAssertion_whichHasToHappen_whileBackupIsRunning.release();

    thd.join();
}

From source file:org.apigw.authserver.svc.impl.TokenServicesImplTest.java

@Test
@DirtiesContext//from w w w. j av a 2  s  .com
@Ignore
public void testConcurrentTokenUpdate() throws InterruptedException {
    //        ExpiringOAuth2RefreshToken expectedExpiringRefreshToken = new ExpiringOAuth2RefreshToken("testToken", new Date(
    //                System.currentTimeMillis() + 100000));
    final OAuth2Authentication authentication = new OAuth2Authentication(
            createAuthorizationRequest(CLIENT, Collections.singleton(READ_SCOPE)),
            new TestAuthentication(false));

    final OAuth2AccessToken[] accessTokens = new OAuth2AccessToken[10];
    for (int i = 0; i < 10; i++) {
        accessTokens[i] = services.createAccessToken(authentication);
    }

    int numberOfConcurrent = 1000;
    List<Thread> executors = new ArrayList<Thread>();
    for (int i = 0; i < numberOfConcurrent; i++) {
        Thread concurrentUpdater = new Thread() {

            //                private OAuth2Authentication innerAuthentication = authentication;
            //                private TransactionalAuthServerTokenServicesDelegatorImpl innerServices = services;

            @Override
            public void run() {
                System.out.println("To run createAccessToken");
                try {
                    if (Math.random() > 0.8) {
                        services.createAccessToken(authentication);
                    } else {
                        OAuth2AccessToken tk = accessTokens[(int) Math.floor(Math.random() * 10)];
                        AuthorizationRequest request = createAuthorizationRequest(CLIENT, tk.getScope());
                        services.refreshAccessToken(tk.getValue(), request);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //                        Thread.currentThread().interrupt();
                    //                        Assert.fail("Got exception: " + e.getMessage());
                    throw new RuntimeException("failed");

                }

                System.out.println("Ran createAccessToken");
            }
        };
        executors.add(concurrentUpdater);
    }
    for (Thread executor : executors) {
        executor.start();
    }
    for (Thread executor : executors) {
        executor.join();
    }
    Assert.assertEquals(1, authorizationGrantRepository.count());
}

From source file:ste.web.http.beanshell.BugFreeBeanShellHandler.java

@Test
public void runningMultipleThreadInDifferentContexts() throws Exception {
    final HttpSessionContext CTX1 = new HttpSessionContext();
    final HttpSessionContext CTX2 = new HttpSessionContext();
    CTX1.setAttribute(HttpCoreContext.HTTP_CONNECTION, getConnection());
    CTX2.setAttribute(HttpCoreContext.HTTP_CONNECTION, getConnection());
    Thread t1 = new Thread(new Runnable() {
        @Override//  w  w  w . j a  v a 2s .  com
        public void run() {
            try {
                handler.handle(get("/multithreading.bsh"), response, CTX1);
            } catch (Exception x) {
                x.printStackTrace();
            }
        }
    });
    Thread t2 = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                handler.handle(get("/multithreading.bsh"), response, CTX2);
            } catch (Exception x) {
                x.printStackTrace();
            }
        }
    });
    t1.start();
    t2.start();
    t1.join();
    t2.join();
    then(CTX1.get("view")).isEqualTo(t1.getName());
    then(CTX2.get("view")).isEqualTo(t2.getName());
}

From source file:com.meltmedia.dropwizard.etcd.json.EtcdWatchServiceIT.java

@SuppressWarnings("unchecked")
@Test/*from   w ww  .  java  2  s  .  c  om*/
public void shouldWatchSingleFile() throws InterruptedException {
    int eventsCount = 100;
    // add a directory watch.
    WatchService service = serviceRule.getService();

    EtcdEventHandler<NodeData> handler = mock(EtcdEventHandler.class);

    EtcdDirectoryDao<NodeData> dirDao = new EtcdDirectoryDao<NodeData>(clientRule::getClient,
            BASE_PATH + "/dir", mapper, NODE_DATA_TYPE);
    Thread events = startNodeDataThread(dirDao, eventsCount);

    try {
        service.registerValueWatch("/dir", "10", new TypeReference<NodeData>() {
        }, handler);

        verify(handler, timeout(10000)).handle(atAnyIndex(EtcdEvent.<NodeData>builder().withKey("10")
                .withType(EtcdEvent.Type.added).withValue(new NodeData().withName("10")).build()));

        verify(handler, times(1)).handle(any(EtcdEvent.class));

    } finally {
        events.join();
    }
}

From source file:com.google.code.jahath.common.io.SwappableInputStreamTest.java

@Test
public void test() throws Throwable {
    final SwappableInputStream swappableInputStream = new SwappableInputStream("test");
    final CRC actualCRC = new CRC();
    final AtomicReference<Throwable> thrown = new AtomicReference<Throwable>();
    Thread thread = new Thread(new Runnable() {
        public void run() {
            try {
                actualCRC.update(swappableInputStream);
            } catch (Throwable ex) {
                thrown.set(ex);//  w  w w  .j a v a2 s  .c om
            }
        }
    });
    thread.start();
    Random random = new Random();
    CRC expectedCRC = new CRC();
    for (int i = 0; i < 100; i++) {
        int len = 2048 + random.nextInt(4096);
        byte[] data = new byte[len];
        random.nextBytes(data);
        expectedCRC.update(data);
        CountingInputStream in = new CountingInputStream(new ByteArrayInputStream(data));
        swappableInputStream.swap(in);
        // Check that the stream has been consumed entirely
        Assert.assertEquals(len, in.getCount());
    }
    swappableInputStream.sendEndOfStream();
    thread.join();
    if (thrown.get() != null) {
        throw thrown.get();
    }
    Assert.assertEquals(expectedCRC.getValue(), actualCRC.getValue());
}

From source file:com.meltmedia.dropwizard.etcd.json.EtcdWatchServiceIT.java

@SuppressWarnings("unchecked")
@Test//from  w ww  .  ja va 2 s. c o  m
public void shouldWatchSingleFileWithNoise() throws InterruptedException {
    int eventsCount = 100;
    // add a directory watch.
    WatchService service = serviceRule.getService();

    EtcdEventHandler<NodeData> handler = mock(EtcdEventHandler.class);

    EtcdDirectoryDao<NodeData> dirDao = new EtcdDirectoryDao<NodeData>(clientRule::getClient,
            BASE_PATH + "/dir", mapper, NODE_DATA_TYPE);

    startNoiseThread(externalNoiseDao, 4000).join();

    Thread events = startNodeDataThread(dirDao, eventsCount);

    try {
        service.registerValueWatch("/dir", "10", new TypeReference<NodeData>() {
        }, handler);

        verify(handler, timeout(10000)).handle(atAnyIndex(EtcdEvent.<NodeData>builder().withKey("10")
                .withType(EtcdEvent.Type.added).withValue(new NodeData().withName("10")).build()));

        verify(handler, times(1)).handle(any(EtcdEvent.class));

    } finally {
        events.join();
    }
}