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 synchronized void join(final long millis) throws InterruptedException 

Source Link

Document

Waits at most millis milliseconds for this thread to die.

Usage

From source file:edu.unc.lib.deposit.fcrepo3.IngestDepositTest.java

@Test
public void testResume() throws Exception {

    when(depositStatusFactory.isResumedDeposit(anyString())).thenReturn(true);
    when(depositStatusFactory.getUnconfirmedUploads(anyString())).thenReturn(new HashSet<String>());
    when(depositStatusFactory.getConfirmedUploads(anyString())).thenReturn(Sets
            .newSet("uuid:2a5d0363-899b-402d-981b-392a553e17a1", "uuid:7dd57979-084c-4b5a-acc0-a0eed25d2b33"));

    Thread jobThread = new Thread(job);
    Thread finishThread = new Thread(jmsListener);

    jobThread.start();/*w  w w.j  a va  2  s  .  c o m*/
    finishThread.start();

    // Start processing with a timelimit to prevent infinite wait in case of failure
    jobThread.join(5000L);
    finishThread.join(5000L);

    assertTrue("Job must have been registered", jmsListener.registeredJob);
    assertTrue("Job must be unregistered", jmsListener.unregisteredJob);

    assertEquals("All ingest pids should have been removed", 0, job.getIngestPids().size());

    assertEquals("Ingest count must exclude the already completed items", 7, job.getIngestObjectCount());

    // Clicks should have been registered
    verify(jobStatusFactory, times(job.getIngestObjectCount() + 1)).incrCompletion(eq(job.getJobUUID()), eq(1));

    verify(client, times(job.getTopLevelPids().size())).addObjectRelationship(any(PID.class), anyString(),
            any(PID.class));

    verify(client, times(job.getIngestObjectCount() + 1)).ingestRaw(any(byte[].class), any(Format.class),
            anyString());

}

From source file:edu.unc.lib.deposit.fcrepo3.IngestDepositTest.java

@Test
public void testResumeUnconfirmed() throws Exception {

    when(accessClient.getObjectProfile(any(PID.class), anyString())).thenReturn(mock(ObjectProfile.class))
            .thenThrow(new FedoraException(""));

    when(depositStatusFactory.isResumedDeposit(anyString())).thenReturn(true);
    when(depositStatusFactory.getUnconfirmedUploads(anyString())).thenReturn(Sets
            .newSet("uuid:3a8650f6-5de6-41b5-8ea1-42ac5e9a9687", "uuid:0a83ed37-6179-4fef-90cb-6e2374179d13"));
    when(depositStatusFactory.getConfirmedUploads(anyString())).thenReturn(Sets
            .newSet("uuid:2a5d0363-899b-402d-981b-392a553e17a1", "uuid:7dd57979-084c-4b5a-acc0-a0eed25d2b33"));

    Thread jobThread = new Thread(job);
    Thread finishThread = new Thread(jmsListener);

    jobThread.start();// w ww  . j  a  v a2 s.  com
    finishThread.start();

    // Start processing with a timelimit to prevent infinite wait in case of failure
    jobThread.join(5000L);
    finishThread.join(5000L);

    assertTrue("Job must have been registered", jmsListener.registeredJob);
    assertTrue("Job must be unregistered", jmsListener.unregisteredJob);

    assertEquals("All ingest pids should have been removed", 0, job.getIngestPids().size());

    assertEquals("Ingest count must exclude the already completed items", 6, job.getIngestObjectCount());

    // Click for newly run ingests and the one unregistered previously completed ingest
    verify(jobStatusFactory, times(job.getIngestObjectCount() + 2)).incrCompletion(eq(job.getJobUUID()), eq(1));

    verify(client, times(job.getTopLevelPids().size())).addObjectRelationship(any(PID.class), anyString(),
            any(PID.class));

}

From source file:edu.unc.lib.deposit.fcrepo3.IngestDepositTest.java

@Test
public void testRunValidStructure() throws Exception {

    Thread jobThread = new Thread(job);
    Thread finishThread = new Thread(jmsListener);

    jobThread.start();/*  w  w w. j  a va 2s. co m*/
    finishThread.start();

    // Start processing with a timelimit to prevent infinite wait in case of failure
    jobThread.join(5000L);
    finishThread.join(5000L);

    assertTrue("Job must have been registered", jmsListener.registeredJob);
    assertTrue("Job must be unregistered", jmsListener.unregisteredJob);

    assertEquals("All ingest pids should have been removed", 0, job.getIngestPids().size());
    assertEquals("Top level pids should be present", 2, job.getTopLevelPids().size());

    assertEquals("Incorrect number of objects extracted", 9, job.getIngestObjectCount());

    // Clicks should have been registered
    verify(jobStatusFactory, times(job.getIngestObjectCount() + 1)).incrCompletion(eq(job.getJobUUID()), eq(1));

    verify(client, times(job.getTopLevelPids().size())).addObjectRelationship(any(PID.class), anyString(),
            any(PID.class));

    verify(client, times(job.getIngestObjectCount() + 1)).ingestRaw(any(byte[].class), any(Format.class),
            anyString());

    // Two of the objects are containers with no data
    verify(client, times(job.getIngestObjectCount() - 2)).upload(any(File.class));

    // PREMIS was written
    verify(client, times(1)).writePremisEventsToFedoraObject(any(PremisEventLogger.class),
            eq(new PID(depositStatus.get(DepositField.containerId.name()))));

}

From source file:edu.unc.lib.deposit.fcrepo3.IngestDepositTest.java

@Test
public void testRunExcludeDepositRecord() throws Exception {

    depositStatus.put(DepositField.excludeDepositRecord.name(), "true");

    Thread jobThread = new Thread(job);
    Thread finishThread = new Thread(jmsListener);

    jobThread.start();//  w ww. j a va  2  s .c  om
    finishThread.start();

    // Start processing with a timelimit to prevent infinite wait in case of failure
    jobThread.join(5000L);
    finishThread.join(5000L);

    assertTrue("Job must have been registered", jmsListener.registeredJob);
    assertTrue("Job must be unregistered", jmsListener.unregisteredJob);

    assertEquals("All ingest pids should have been removed", 0, job.getIngestPids().size());
    assertEquals("Top level pids should be present", 2, job.getTopLevelPids().size());

    assertEquals("Incorrect number of objects extracted", 9, job.getIngestObjectCount());

    // Clicks should have been registered
    verify(jobStatusFactory, times(job.getIngestObjectCount())).incrCompletion(eq(job.getJobUUID()), eq(1));

    verify(client, times(job.getTopLevelPids().size())).addObjectRelationship(any(PID.class), anyString(),
            any(PID.class));

    verify(client, times(job.getIngestObjectCount())).ingestRaw(any(byte[].class), any(Format.class),
            anyString());

    // Two of the objects are containers with no data
    verify(client, times(job.getIngestObjectCount() - 2)).upload(any(File.class));

    // PREMIS was written
    verify(client, times(1)).writePremisEventsToFedoraObject(any(PremisEventLogger.class),
            eq(new PID(depositStatus.get(DepositField.containerId.name()))));

}

From source file:com.google.enterprise.adaptor.Daemon.java

@Override
public void start() throws Exception {
    final Application savedApp;
    final DaemonContext savedContext;
    // Save values so that there aren't any races with stop/destroy.
    synchronized (this) {
        savedApp = this.app;
        savedContext = this.context;
    }//from www  .ja v  a  2  s .c o  m
    // Run in a new thread so that stop() can be called before we complete
    // starting (since starting can take a long time if the Adaptor keeps
    // throwing an exception). However, we still try to wait for start to
    // complete normally to ease testing and improve the user experience in the
    // common case of starting being quick.
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                savedApp.daemonStart();
            } catch (InterruptedException ex) {
                // We must be shutting down.
                Thread.currentThread().interrupt();
            } catch (Exception ex) {
                savedContext.getController().fail("Failed to start service.", ex);
            }
        }
    });
    thread.start();
    thread.join(5 * 1000);
}

From source file:de.teambluebaer.patientix.helper.RestfulHelper.java

/**
 * Method which executes a request to the server.
 * It must be a new Thread to send the data, otherwise u'll get an NetworkAuthentication-Error
 * The join operation simulates a wait for main-thread, otherwise, the main will run up
 *
 * @param method       Is the End of the URL at which the request will be send
 * @param parameterMap ArrayList with parameters for the request
 * @return int of the responseCode/*  w  w w.j av  a2  s  .c o  m*/
 */
public int executeRequest(final String method, final ArrayList<NameValuePair> parameterMap) {

    Thread networkThread = new Thread() {
        public void run() {

            setURLForRequest(method);
            postDataToServer(method, parameterMap);
        }
    };
    try {
        networkThread.setDaemon(false);
        networkThread.start();
        //Join main-thread with Network-Thread to share Domain-Objects
        // The network-thread get an Timeout of 1 Second, otherwise, the application will hang
        networkThread.join(Constants.PING - 1);
        try {
            sleep(Constants.PING);
        } catch (Exception e) {
            Log.d("SleepExeption", e.toString());
        }
    } catch (InterruptedException e) {
        return 503;
    }
    return responseCode;
}

From source file:com.ricemap.spateDB.core.GridRecordWriter.java

/**
 * Close the whole writer. Finalize all cell files and concatenate them
 * into the output file.//from  w  w w.j  a va2s  . c om
 */
public synchronized void close(Progressable progressable) throws IOException {
    // Close all output files
    for (int cellIndex = 0; cellIndex < intermediateCellStreams.length; cellIndex++) {
        if (intermediateCellStreams[cellIndex] != null) {
            closeCell(cellIndex);
        }
        // Indicate progress. Useful if closing a single cell takes a long time
        if (progressable != null)
            progressable.progress();
    }

    while (!closingThreads.isEmpty()) {
        try {
            Thread t = closingThreads.get(0);
            switch (t.getState()) {
            case NEW:
                t.start();
                break;
            case TERMINATED:
                closingThreads.remove(0);
                break;
            default:
                t.join(10000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    if (masterFile != null)
        masterFile.close();
}

From source file:edu.unc.lib.deposit.fcrepo3.IngestDepositTest.java

@Test
public void testRunIngestTimeout() throws Exception {

    when(client.ingestRaw(any(byte[].class), any(Format.class), anyString())).thenReturn(new PID("pid"))
            .thenReturn(new PID("pid")).thenThrow(new FedoraTimeoutException(new Exception()))
            .thenReturn(new PID("pid"));

    Thread.UncaughtExceptionHandler jobFailedHandler = new Thread.UncaughtExceptionHandler() {
        @Override/*from w w w . java  2  s  .c o m*/
        public void uncaughtException(Thread th, Throwable ex) {
            fail("Uncaught exception, job should have completed.");
        }
    };

    Thread jobThread = new Thread(job);
    Thread finishThread = new Thread(jmsListener);

    jobThread.setUncaughtExceptionHandler(jobFailedHandler);

    jobThread.start();
    finishThread.start();

    // Start processing with a timelimit to prevent infinite wait in case of failure
    jobThread.join(5000L);
    finishThread.join(5000L);

    // All ingests, including the timed out object, should have registered as a click
    verify(jobStatusFactory, times(job.getIngestObjectCount() + 1)).incrCompletion(eq(job.getJobUUID()), eq(1));

    // All objects should have been ingested despite the timeout
    verify(client, times(job.getIngestObjectCount() + 1)).ingestRaw(any(byte[].class), any(Format.class),
            anyString());

    assertTrue("Job must have been registered", jmsListener.registeredJob);
    assertTrue("Job must have been unregistered", jmsListener.registeredJob);

}

From source file:edu.cmu.graphchi.toolkits.collaborative_filtering.yarn.ApplicationMaster.java

private void finish() {
    // Join all launched threads
    // needed for when we time out
    // and we need to release containers
    for (Thread launchThread : launchThreads) {
        try {/*from   ww  w  .j av  a  2  s.  co  m*/
            launchThread.join(10000);
        } catch (InterruptedException e) {
            LOG.info("Exception thrown in thread join: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // When the application completes, it should stop all running containers
    LOG.info("Application completed. Stopping running containers");
    nmClientAsync.stop();

    // When the application completes, it should send a finish application
    // signal to the RM
    LOG.info("Application completed. Signalling finish to RM");

    FinalApplicationStatus appStatus;
    String appMessage = null;
    success = true;
    if (numFailedContainers.get() == 0 && numCompletedContainers.get() == numTotalContainers) {
        appStatus = FinalApplicationStatus.SUCCEEDED;
    } else {
        appStatus = FinalApplicationStatus.FAILED;
        appMessage = "Diagnostics." + ", total=" + numTotalContainers + ", completed="
                + numCompletedContainers.get() + ", failed=" + numFailedContainers.get();
        success = false;
    }
    try {
        amRMClient.unregisterApplicationMaster(appStatus, appMessage, null);
    } catch (YarnException ex) {
        LOG.error("Failed to unregister application", ex);
    } catch (IOException e) {
        LOG.error("Failed to unregister application", e);
    }

    amRMClient.stop();
}

From source file:com.baidu.jprotobuf.mojo.PreCompileMojo.java

private void joinThread(Thread thread, long timeoutMsecs) {
    try {/*from   w  w  w . j  a  va 2s  .  c  om*/
        getLog().debug("joining on thread " + thread);
        thread.join(timeoutMsecs);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt(); // good practice if don't throw
        getLog().warn("interrupted while joining against thread " + thread, e); // not expected!
    }
    if (thread.isAlive()) // generally abnormal
    {
        getLog().warn("thread " + thread + " was interrupted but is still alive after waiting at least "
                + timeoutMsecs + "msecs");
    }
}