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._4dconcept.springframework.data.marklogic.datasource.DatabaseConnectorJtaTransactionTest.java

@Test
public void testJtaTransactionWithConnectionHolderStillBound() throws Exception {
    @SuppressWarnings("serial")
    JtaTransactionManager ptm = new JtaTransactionManager(userTransaction) {

        @Override/*  w  w  w.jav  a2  s  .  co m*/
        protected void doRegisterAfterCompletionWithJtaTransaction(JtaTransactionObject txObject,
                final List<TransactionSynchronization> synchronizations)
                throws RollbackException, SystemException {
            Thread async = new Thread() {
                @Override
                public void run() {
                    invokeAfterCompletion(synchronizations, TransactionSynchronization.STATUS_COMMITTED);
                }
            };
            async.start();
            try {
                async.join();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    };
    TransactionTemplate tt = new TransactionTemplate(ptm);
    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(contentSource));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

    given(userTransaction.getStatus()).willReturn(Status.STATUS_ACTIVE);
    for (int i = 0; i < 3; i++) {
        final boolean releaseCon = (i != 1);

        tt.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
                assertTrue("JTA synchronizations active",
                        TransactionSynchronizationManager.isSynchronizationActive());
                assertTrue("Is existing transaction", !status.isNewTransaction());

                Session c = ContentSourceUtils.getSession(contentSource);
                assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(contentSource));
                ContentSourceUtils.releaseSession(c, contentSource);

                c = ContentSourceUtils.getSession(contentSource);
                assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(contentSource));
                if (releaseCon) {
                    ContentSourceUtils.releaseSession(c, contentSource);
                }
            }
        });

        if (!releaseCon) {
            assertTrue("Still has session holder",
                    TransactionSynchronizationManager.hasResource(contentSource));
        } else {
            assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(contentSource));
        }
        assertTrue("JTA synchronizations not active",
                !TransactionSynchronizationManager.isSynchronizationActive());
    }
    verify(session, times(3)).close();
}

From source file:com.espertech.esper.regression.nwtable.TestTableMTUngroupedAccessReadInotTableWriteIterate.java

private void tryMT(int numReadThreads, int numSeconds) throws Exception {
    String eplCreateVariable = "create table vartotal (s0 sum(int), s1 sum(double), s2 sum(long))";
    epService.getEPAdministrator().createEPL(eplCreateVariable);

    String eplInto = "into table vartotal select sum(intPrimitive) as s0, "
            + "sum(doublePrimitive) as s1, sum(longPrimitive) as s2 from SupportBean";
    epService.getEPAdministrator().createEPL(eplInto);
    epService.getEPRuntime().sendEvent(makeSupportBean("E", 1, 1, 1));

    EPStatement iterateStatement = epService.getEPAdministrator().createEPL(
            "select vartotal.s0 as c0, vartotal.s1 as c1, vartotal.s2 as c2 from SupportBean_S0.std:lastevent()");
    epService.getEPRuntime().sendEvent(new SupportBean_S0(0));

    // setup writer
    WriteRunnable writeRunnable = new WriteRunnable(epService);
    Thread writeThread = new Thread(writeRunnable);

    // setup readers
    Thread[] readThreads = new Thread[numReadThreads];
    ReadRunnable[] readRunnables = new ReadRunnable[numReadThreads];
    for (int i = 0; i < readThreads.length; i++) {
        readRunnables[i] = new ReadRunnable(iterateStatement);
        readThreads[i] = new Thread(readRunnables[i]);
    }/* w ww.ja v  a2s .  c  om*/

    // start
    for (Thread readThread : readThreads) {
        readThread.start();
    }
    writeThread.start();

    // wait
    Thread.sleep(numSeconds * 1000);

    // shutdown
    writeRunnable.setShutdown(true);
    for (ReadRunnable readRunnable : readRunnables) {
        readRunnable.setShutdown(true);
    }

    // join
    log.info("Waiting for completion");
    writeThread.join();
    for (Thread readThread : readThreads) {
        readThread.join();
    }

    // assert
    assertNull(writeRunnable.getException());
    assertTrue(writeRunnable.numEvents > 100);
    for (ReadRunnable readRunnable : readRunnables) {
        assertNull(readRunnable.getException());
        assertTrue(readRunnable.numQueries > 100);
    }
}

From source file:com.limegroup.gnutella.RouterService.java

/**
 * Runs all shutdown items.//from  w  ww.  j  av  a 2s  . c om
 */
private static void runShutdownItems() {
    if (!isShuttingDown())
        return;

    // Start each shutdown item.
    for (Iterator i = SHUTDOWN_ITEMS.iterator(); i.hasNext();) {
        Thread t = (Thread) i.next();
        t.start();
    }

    // Now that we started them all, iterate back and wait for each one to finish.
    for (Iterator i = SHUTDOWN_ITEMS.iterator(); i.hasNext();) {
        Thread t = (Thread) i.next();
        try {
            t.join();
        } catch (InterruptedException ie) {
        }
    }
}

From source file:com.thoughtworks.studios.shine.cruise.stage.details.LazyStageGraphLoaderTest.java

@Test
public void shouldNotReuseTransformerAcrossConcurrentInvocations() throws InterruptedException {
    final StageIdentifier stageId = new StageIdentifier("pipeline-foo", 23, "stage-1", "1");

    final Semaphore invocationBlocker = new Semaphore(1);
    final DummyStageResourceImporter realLoader = new DummyStageResourceImporter(realGraph(), stageId,
            invocationBlocker);/*from w  w  w. j ava 2 s  . c o  m*/

    final LazyStageGraphLoader loader = new LazyStageGraphLoader(realLoader, stageStorage, 2);

    final XSLTTransformerRegistry[] transformerRegistryUsed = new XSLTTransformerRegistry[2];

    invocationBlocker.acquire();

    Thread firstThd = new Thread(new Runnable() {
        public void run() {
            loader.load(stageId);
            invocationBlocker.release();
        }
    });

    firstThd.start();

    while (invocationBlocker.getQueueLength() == 0) {
        Thread.sleep(10);
    }
    transformerRegistryUsed[0] = realLoader.transformerRegistry;

    Thread secondThd = new Thread(new Runnable() {
        public void run() {
            stageStorage.clear();
            loader.load(stageId);
        }
    });

    secondThd.start();

    while (invocationBlocker.getQueueLength() == 1) {
        Thread.sleep(10);
    }
    transformerRegistryUsed[1] = realLoader.transformerRegistry;

    invocationBlocker.release();

    firstThd.join();
    secondThd.join();

    assertThat(transformerRegistryUsed[0], not(sameInstance(transformerRegistryUsed[1])));
}

From source file:eu.stratosphere.pact.runtime.task.DataSinkTaskTest.java

@Test
public void testCancelDataSinkTask() {

    super.initEnvironment(MEMORY_MANAGER_SIZE, NETWORK_BUFFER_SIZE);
    super.addInput(new InfiniteInputIterator(), 0);

    final DataSinkTask<Record> testTask = new DataSinkTask<Record>();
    Configuration stubParams = new Configuration();
    super.getTaskConfig().setStubParameters(stubParams);

    super.registerFileOutputTask(testTask, MockOutputFormat.class, new File(tempTestPath).toURI().toString());

    Thread taskRunner = new Thread() {
        @Override//www .  ja  va  2s.co  m
        public void run() {
            try {
                testTask.invoke();
            } catch (Exception ie) {
                ie.printStackTrace();
                Assert.fail("Task threw exception although it was properly canceled");
            }
        }
    };
    taskRunner.start();

    TaskCancelThread tct = new TaskCancelThread(1, taskRunner, testTask);
    tct.start();

    try {
        tct.join();
        taskRunner.join();
    } catch (InterruptedException ie) {
        Assert.fail("Joining threads failed");
    }

    // assert that temp file was created
    File tempTestFile = new File(this.tempTestPath);
    Assert.assertTrue("Temp output file does not exist", tempTestFile.exists());

}

From source file:eu.stratosphere.pact.runtime.task.DataSinkTaskTest.java

@Test
@SuppressWarnings("unchecked")
public void testCancelSortingDataSinkTask() {

    super.initEnvironment(MEMORY_MANAGER_SIZE * 4, NETWORK_BUFFER_SIZE);
    super.addInput(new InfiniteInputIterator(), 0);

    final DataSinkTask<Record> testTask = new DataSinkTask<Record>();
    Configuration stubParams = new Configuration();
    super.getTaskConfig().setStubParameters(stubParams);

    // set sorting
    super.getTaskConfig().setInputLocalStrategy(0, LocalStrategy.SORT);
    super.getTaskConfig().setInputComparator(new RecordComparatorFactory(new int[] { 1 },
            ((Class<? extends Key<?>>[]) new Class[] { IntValue.class })), 0);
    super.getTaskConfig().setMemoryInput(0, 4 * 1024 * 1024);
    super.getTaskConfig().setFilehandlesInput(0, 8);
    super.getTaskConfig().setSpillingThresholdInput(0, 0.8f);

    super.registerFileOutputTask(testTask, MockOutputFormat.class, new File(tempTestPath).toURI().toString());

    Thread taskRunner = new Thread() {
        @Override/*from ww  w .  j av  a  2s.c om*/
        public void run() {
            try {
                testTask.invoke();
            } catch (Exception ie) {
                ie.printStackTrace();
                Assert.fail("Task threw exception although it was properly canceled");
            }
        }
    };
    taskRunner.start();

    TaskCancelThread tct = new TaskCancelThread(2, taskRunner, testTask);
    tct.start();

    try {
        tct.join();
        taskRunner.join();
    } catch (InterruptedException ie) {
        Assert.fail("Joining threads failed");
    }

}

From source file:com.thoughtworks.go.server.dao.PipelineSqlMapDao.java

private void waitForLoaderThreadsToJoin(Thread[] loaderThreads) {
    for (Thread loaderThread : loaderThreads) {
        try {//from w  w w. ja v a 2s  .c  om
            loaderThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.eclipse.aether.transport.http.HttpTransporterTest.java

@Test(timeout = 20000L)
public void testConcurrency() throws Exception {
    httpServer.setAuthentication("testuser", "testpass");
    auth = new AuthenticationBuilder().addUsername("testuser").addPassword("testpass").build();
    newTransporter(httpServer.getHttpUrl());
    final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
    Thread threads[] = new Thread[20];
    for (int i = 0; i < threads.length; i++) {
        final String path = "repo/file.txt?i=" + i;
        threads[i] = new Thread() {
            @Override/*w  ww .j  ava2 s .  c o m*/
            public void run() {
                try {
                    for (int j = 0; j < 100; j++) {
                        GetTask task = new GetTask(URI.create(path));
                        transporter.get(task);
                        assertEquals("test", task.getDataString());
                    }
                } catch (Throwable t) {
                    error.compareAndSet(null, t);
                    System.err.println(path);
                    t.printStackTrace();
                }
            }
        };
        threads[i].setName("Task-" + i);
    }
    for (Thread thread : threads) {
        thread.start();
    }
    for (Thread thread : threads) {
        thread.join();
    }
    assertNull(String.valueOf(error.get()), error.get());
}

From source file:diet.gridr.g5k.gui.GanttChart.java

/**
 * Method returning the card panel/*  ww  w .  j av a  2  s  .com*/
 *
 * @return the card panel
 */
private JPanel getCardPanel() {
    cardPanel = new JPanel();
    ganttChartLayout = new CardLayout();
    cardPanel.setLayout(ganttChartLayout);
    final WaitingFrame waiting = new WaitingFrame("Waiting frame",
            "Creating the gantt charts for this cluster ...", durationsStringArray.length + 1, true);
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            Thread thread = new Thread(new Runnable() {
                public void run() {
                    waiting.setStatusText("Operation : ");
                    waiting.launch("running oar stat history command ...");
                    OarHistoryRunnable historyRunnable = null;
                    chartPanels = new JPanel[durationsStringArray.length];
                    for (int i = 0; i < durationsStringArray.length; i++) {
                        waiting.setStatusText("retrieving OAR history for " + durationsStringArray[i]);
                        waiting.incrementProgressBar();
                        Date startDate = GregorianCalendar.getInstance().getTime();
                        Date endDate = new Date(startDate.getTime() + HistoryUtil.durationsTimesArray[i]);
                        historyRunnable = new OarHistoryRunnable(connection, jobsList.get(i),
                                Config.getBatchScheduler(G5kSite.getIndexForSite(siteName)),
                                G5kSite.getInternalFrontalForSite(siteName), startDate, endDate);
                        Thread th = new Thread(historyRunnable);
                        th.start();
                        try {
                            th.join();
                        } catch (Exception e) {
                            LoggingManager.log(Level.WARNING, LoggingManager.RESOURCESTOOL,
                                    this.getClass().getName(), "run", e);
                        }
                        jobsList.set(i, historyRunnable.getJobsList());
                        //                            Iterator<String> iter = historyLines.iterator();
                        //                            /*
                        //                             * The history is separated into three parts:
                        //                             *
                        //                             *  - the first is the free nodes written as follows :
                        //                             *  'node1' 'weightOfNode1' 'node2' 'weightOfNode2' ...
                        //                             *   eg :
                        //                             *  'sagittaire-12.lyon.grid5000.fr' '2' 'sagittaire-13.lyon.grid5000.fr' '2'
                        //                             *
                        //                             *  - the second is a list of jobs :
                        //                             *  'job id' 'type' 'user' 'state' 'command' 'properties' 'start time' 'queue' 'submission time' 'end time' 'node1' 'weightOfNode1' 'node2' 'weightOfNode2' ...
                        //                             *   e.g. :
                        //                             *   '20081' 'PASSIVE' 'ssoudan' 'Running' '/bin/sleep 72000' '(p.deploy = "YES") AND p.deploy = "YES" ' '2007-03-23 10:18:48' 'deploy' '2007-03-23 10:19:03' '2007-03-24 06:18:48' 'sagittaire-19.lyon.grid5000.fr' '2' 'sagittaire-24.lyon.grid5000.fr' '2'
                        //                             *
                        //                             *  - the last one is a list of dead jobs :
                        //                             *  the last part as the same pattern as the jobs
                        //                             *  '0' 'Dead' 'oar' 'null' 'null' 'null' '0000-00-00 00:00:00' 'default' '2007-03-22 19:30:02' '2007-03-24 14:00:00' 'sagittaire-60.lyon.grid5000.fr' '2'
                        //                             *
                        //                             */
                        //                            // for all jobs
                        //                            while(iter.hasNext()){
                        //                                String historyLine = iter.next();
                        //                                historyLine = historyLine.replace("''","' '");
                        //                                StringTokenizer tokenizer = new StringTokenizer(historyLine,"'");
                        //                                ArrayList<String> information = new ArrayList<String>();
                        //                                while(tokenizer.hasMoreTokens()){
                        //                                    information.add(tokenizer.nextToken());
                        //                                }
                        //                                int jobNumber=-1;
                        //                                try{
                        //                                    // if no exception is thrown then it means that we are no! in the first
                        //                                    // part of the history
                        //                                    jobNumber = Integer.parseInt(information.get(0));
                        //                                }
                        //                                catch(Exception e){
                        //                                    LoggingManager.log(Level.FINE, LoggingManager.RESOURCESTOOL, this.getClass().getName(), "run", e);
                        //                                }
                        //                                if(jobNumber == 0){
                        //                                    // this is a dead of absent node
                        //                                    GridJob aJob = new Oar1Job();
                        //                                    aJob.setParameterValue(GridJob.KEY_GRID_JOB_HOSTS, information.get(20));
                        //                                    aJob.setParameterValue(GridJob.KEY_GRID_JOB_ID, "0");
                        //                                    aJob.setParameterValue(GridJob.KEY_GRID_JOB_OWNER, "");
                        //                                    aJob.setParameterValue(GridJob.KEY_GRID_JOB_QUEUE, "");
                        //                                    aJob.setParameterValue(GridJob.KEY_GRID_JOB_STATE, "");
                        //                                    aJob.setParameterValue(GridJob.KEY_GRID_JOB_RESOURCES_COUNT, "1");
                        //                                    aJob.setParameterValue(GridJob.KEY_GRID_JOB_SCHEDTIME,
                        //                                            GanttChart.getOARDateFromDate(Calendar.getInstance().getTime()));//information.get(12);
                        //                                    aJob.setParameterValue(GridJob.KEY_GRID_JOB_WALLTIME,
                        //                                            getWallTimeFromDate(HistoryUtil.durationsTimesArray[i]));//ntheWallTime;
                        //                                    jobsList.get(i).add(aJob);
                        //                                }
                        //                                else if (jobNumber != -1){
                        //                                    // this is not a dead or absent or suspected job but a classical job
                        //                                    GridJob aJob = null;
                        //                                    //searching the job
                        //                                    for(int j = 0 ;j < jobsList.get(i).size() ; j++){
                        //                                        aJob = jobsList.get(i).get(j);
                        //                                        String firstParam = aJob.getParameterValue(GridJob.KEY_GRID_JOB_ID);
                        //                                        if(jobNumber == Integer.parseInt(firstParam)){
                        //                                            j=jobsList.get(i).size();
                        //                                        }
                        //                                    }
                        //                                    // if the job is waiting
                        //                                    if(aJob.getParameterValue(GridJob.KEY_GRID_JOB_STATE).substring(0, 1).equalsIgnoreCase("w")){
                        //                                        ArrayList<String> theNodes = new ArrayList<String>();
                        //                                        for(int index = 20 ; index < information.size() ; index +=4){
                        //                                            theNodes.add(information.get(index));
                        //                                        }
                        //
                        //                                        if(theNodes.size() >= 1){
                        ////                                            String nodesOfTheJob = theNodes.get(0);
                        ////                                            for(int anIndex = 1 ; anIndex < theNodes.size(); anIndex ++){
                        ////                                                nodesOfTheJob += "+" + theNodes.get(anIndex);
                        ////                                            }
                        //                                            // TODO: check this operation (don't understand how use it)
                        //                                            aJob.setHostsFromArray(theNodes.toArray(new String[0]));
                        //                                        }
                        //                                    }
                        //                                }
                        //                            }

                        waiting.setStatusText("creating chart for " + durationsStringArray[i]);
                        visualizationDuration = i;
                        chartPanels[i] = new ChartPanel(createChart(createDataset()));
                        chartPanels[i].setPreferredSize(new java.awt.Dimension(800, 600));
                        chartPanels[i].setBorder(BorderFactory.createEmptyBorder(5, 10, 10, 10));
                        cardPanel.add(durationsStringArray[i], chartPanels[i]);
                    }
                    visualizationDuration = ONE_DAY;
                    ganttChartLayout.show(cardPanel, durationsStringArray[visualizationDuration]);
                    waiting.dispose();
                    GanttChart.this.pack();
                    GanttChart.this.setVisible(true);
                    LoggingManager.log(Level.CONFIG, LoggingManager.RESOURCESTOOL, this.getClass().getName(),
                            "run", "GanttChart initialized");
                }
            });
            thread.start();
        }
    });
    LoggingManager.log(Level.CONFIG, LoggingManager.RESOURCESTOOL, this.getClass().getName(), "getCardPanel",
            "CardPanel initialized");
    return cardPanel;
}

From source file:com.runwaysdk.dataaccess.database.general.ProcessReader.java

private void _start(boolean async) {
    Thread t = new Thread(new Runnable() {

        @Override// ww  w . j a  v  a 2  s.  c  o  m
        public void run() {
            try {
                ProcessReader.this.process = ProcessReader.this.builder.start();

                consumeOutput(process.getInputStream(), ProcessReader.this.output);
                consumeError(process.getErrorStream(), ProcessReader.this.errorOut);

                ProcessReader.this.process.waitFor();
            } catch (Throwable ex) {
                throw new ProgrammingErrorException(ProcessReader.this.toString(), ex);
            }
        }
    }, PROCESS_THREAD);

    t.setUncaughtExceptionHandler(this);
    t.start();

    if (!async) {
        // block this thread until everything is done
        try {
            t.join();
        } catch (InterruptedException e) {
            log.error(e);
        }
    }
}