Example usage for java.lang Thread isAlive

List of usage examples for java.lang Thread isAlive

Introduction

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

Prototype

public final native boolean isAlive();

Source Link

Document

Tests if this thread is alive.

Usage

From source file:com.datatorrent.stram.engine.StreamingContainer.java

public void processHeartbeatResponse(ContainerHeartbeatResponse rsp) {
    if (rsp.nodeRequests != null) {
        nodeRequests = rsp.nodeRequests;
    }//from  w ww . j  av a  2 s  .  co  m

    if (rsp.committedWindowId != lastCommittedWindowId) {
        lastCommittedWindowId = rsp.committedWindowId;
        OperatorRequest nr = null;
        for (Entry<Integer, Node<?>> e : nodes.entrySet()) {
            final Thread thread = e.getValue().context.getThread();
            if (thread == null || !thread.isAlive()) {
                continue;
            }

            if (e.getValue().getOperator() instanceof Operator.CheckpointListener) {
                if (nr == null) {
                    nr = new OperatorRequest() {
                        @Override
                        public StatsListener.OperatorResponse execute(Operator operator, int operatorId,
                                long windowId) throws IOException {
                            ((Operator.CheckpointListener) operator).committed(lastCommittedWindowId);
                            return null;
                        }

                    };
                }
                e.getValue().context.request(nr);
            }
        }
    }

    if (rsp.undeployRequest != null) {
        logger.info("Undeploy request: {}", rsp.undeployRequest);
        processNodeRequests(false);
        undeploy(rsp.undeployRequest);
    }

    if (rsp.shutdown) {
        logger.info("Received shutdown request");
        processNodeRequests(false);
        this.exitHeartbeatLoop = true;
        return;
    }

    if (rsp.deployRequest != null) {
        logger.info("Deploy request: {}", rsp.deployRequest);
        try {
            deploy(rsp.deployRequest);
        } catch (Exception e) {
            logger.error("deploy request failed", e);
            try {
                umbilical.log(this.containerId,
                        "deploy request failed: " + rsp.deployRequest + " " + ExceptionUtils.getStackTrace(e));
            } catch (IOException ioe) {
                // ignore
            }
            this.exitHeartbeatLoop = true;
            throw new IllegalStateException("Deploy request failed: " + rsp.deployRequest, e);
        }
    }

    processNodeRequests(true);
}

From source file:org.kalypso.util.net.URLGetter.java

/**
 * @see org.kalypso.contribs.eclipse.jface.operation.ICoreRunnableWithProgress#execute(org.eclipse.core.runtime.IProgressMonitor)
 *///from   w  w w.  jav a 2  s.  c  o m
@Override
public IStatus execute(final IProgressMonitor monitor) {
    final String urlAsString = m_url.toString();
    final HttpMethod method = new GetMethod(urlAsString);
    // do not forget the next line!
    method.setDoAuthentication(true);

    final Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                final HttpClient httpClient = getHttpClient();
                httpClient.executeMethod(method);
                setResult(method.getResponseBodyAsStream());
            } catch (final IOException e) {
                final IStatus status;

                String responseBodyAsString = Messages.getString("org.kalypso.util.net.URLGetter.1"); //$NON-NLS-1$
                try {
                    responseBodyAsString = method.getResponseBodyAsString();
                } catch (final IOException e1) {
                    final IStatus status2 = StatusUtilities.statusFromThrowable(e1);
                    KalypsoGisPlugin.getDefault().getLog().log(status2);
                }

                String message = Messages.getString("org.kalypso.util.net.URLGetter.2") + urlAsString; //$NON-NLS-1$
                if (responseBodyAsString != null && !responseBodyAsString.isEmpty())
                    message += "\n" + responseBodyAsString; //$NON-NLS-1$

                status = new Status(IStatus.ERROR, KalypsoGisPlugin.getId(), 0, message, e);
                setStatus(status);
            }
        }
    };

    monitor.beginTask(urlAsString, IProgressMonitor.UNKNOWN);
    monitor.subTask(Messages.getString("org.kalypso.util.net.URLGetter.4")); //$NON-NLS-1$
    thread.start();
    while (thread.isAlive()) {
        try {
            Thread.sleep(100);
        } catch (final InterruptedException e1) {
            // should never happen, ignore
            e1.printStackTrace();
        }

        final String statusText;
        final StatusLine statusLine = method.getStatusLine();
        if (statusLine == null)
            statusText = Messages.getString("org.kalypso.util.net.URLGetter.5"); //$NON-NLS-1$
        else
            statusText = method.getStatusText();

        monitor.subTask(statusText);
        monitor.worked(1);
        if (monitor.isCanceled()) {
            // TODO: this does not stop the thread!
            thread.interrupt();

            monitor.done();
            return Status.CANCEL_STATUS;
        }
    }

    monitor.done();
    return m_status;
}

From source file:gda.device.detector.mythen.MythenDetectorImpl.java

@Override
public void collectData() throws DeviceException {
    beforeCollectData();/*from   ww w. j  a va2s  . com*/
    Thread mythenAcquire = new Thread(new Runnable() {

        @Override
        public void run() {
            // do data acquisition into the file
            AcquisitionParameters params = new AcquisitionParameters.Builder()
                    .filename(rawFile.getAbsolutePath()).frames(1).exposureTime(exposureTime).trigger(NONE)
                    .build();
            try {
                logger.debug("starting acquire, expecting to collect for " + exposureTime + "s");
                mythenClient.acquire(params);
                logger.debug("finished acquire");
                afterCollectData();
                logger.debug("finished after collect data");
            } catch (DeviceException e) {
                logger.error("{}: error text client acquisition failed.", e);
                throw new RuntimeException("Unable to collect data", e);
            } finally {
                status = IDLE;
            }
        }
    });
    while (mythenAcquire.isAlive()) {
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    mythenAcquire.start();
}

From source file:org.apache.hadoop.hdfs.notifier.server.ServerCore.java

@Override
public void run() {
    LOG.info("Starting server ...");
    LOG.info("Max heap size: " + Runtime.getRuntime().maxMemory());

    // Setup the Thrift server
    TProtocolFactory protocolFactory = new TBinaryProtocol.Factory();
    TTransportFactory transportFactory = new TFramedTransport.Factory();
    TNonblockingServerTransport serverTransport;
    ServerHandler.Processor<ServerHandler.Iface> processor = new ServerHandler.Processor<ServerHandler.Iface>(
            handler);/*from   w  w w .  j  a  v  a  2 s.c om*/
    try {
        serverTransport = new TNonblockingServerSocket(listeningPort);
    } catch (TTransportException e) {
        LOG.error("Failed to setup the Thrift server.", e);
        return;
    }
    TNonblockingServer.Args serverArgs = new TNonblockingServer.Args(serverTransport);
    serverArgs.processor(processor).transportFactory(transportFactory).protocolFactory(protocolFactory);
    tserver = new TNonblockingServer(serverArgs);

    // Start the worker threads
    threads.add(new Thread(serverHistory, "Thread-ServerHistory"));
    threads.add(new Thread(dispatcher, "Thread-Dispatcher"));
    threads.add(new Thread(logReader, "Thread-LogReader"));
    threads.add(new Thread(new ThriftServerRunnable(), "Thread-ThriftServer"));
    LOG.info("Starting thrift server on port " + listeningPort);
    for (Thread t : threads) {
        t.start();
    }

    started = true;
    try {
        while (!shutdownPending()) {
            // Read a notification
            NamespaceNotification notification = logReader.getNamespaceNotification();
            if (notification != null) {
                handleNotification(notification);
                continue;
            }
        }
    } catch (Exception e) {
        LOG.error("Failed fetching transaction log data", e);
    } finally {
        shutdown();
    }

    long shuttingDownStart = System.currentTimeMillis();
    for (Thread t : threads) {
        long remaining = SHUTDOWN_TIMEOUT + System.currentTimeMillis() - shuttingDownStart;
        try {
            if (remaining > 0) {
                t.join(remaining);
            }
        } catch (InterruptedException e) {
            LOG.error("Interrupted when closing threads at the end");
        }
        if (t.isAlive()) {
            t.interrupt();
        }
    }
    LOG.info("Shutdown");
}

From source file:com.intuit.tank.harness.APITestHarness.java

/**
 * check the agent threads if simulation time has been met.
 *//*from w  ww  . j a  v a  2  s  .  c o  m*/
public void checkAgentThreads() {
    int activeCount = threadGroup.activeCount();
    Thread[] threads = new Thread[activeCount];
    threadGroup.enumerate(threads);
    int activeThreads = 0;
    for (Thread t : threads) {
        if (t != null) {
            if (t.getState() == Thread.State.TIMED_WAITING || t.getState() == Thread.State.WAITING) {
                activeThreads++;
            }
        }
    }
    LOG.info(LogUtil.getLogMessage("Have " + activeThreads + " of " + activeCount
            + " active Threads in thread group " + threadGroup.getName(), LogEventType.System));
    if (agentRunData.getSimulationTime() != 0 && hasMetSimulationTime() && doneSignal.getCount() != 0) {
        boolean exceededTimeLimit = System.currentTimeMillis() > getMaxSimulationEndTimeMillis();
        if (exceededTimeLimit) {
            LOG.info(LogUtil.getLogMessage("Max simulation time has been met and there are "
                    + doneSignal.getCount() + " threads not reporting done."));
            for (Thread t : sessionThreads) {
                if (t.isAlive()) {
                    if (exceededTimeLimit) {
                        LOG.warn(
                                LogUtil.getLogMessage(
                                        "thread " + t.getName() + '-' + t.getId()
                                                + " is still running with a State of " + t.getState().name(),
                                        LogEventType.System));
                        t.interrupt();
                        doneSignal.countDown();
                    }
                }
            }
        }
    }
}

From source file:org.apache.tajo.cli.tsql.TestTajoCli.java

License:asdf

@Test
public void testRunWhenError() throws Exception {
    Thread t = new Thread() {
        public void run() {
            try {
                PipedOutputStream po = new PipedOutputStream();
                InputStream is = new PipedInputStream(po);
                ByteArrayOutputStream out = new ByteArrayOutputStream();

                TajoConf tajoConf = new TajoConf();
                setVar(tajoCli, SessionVars.CLI_FORMATTER_CLASS, TajoCliOutputTestFormatter.class.getName());
                Properties connParams = new Properties();
                connParams.setProperty(ClientParameters.RETRY, "3");
                TajoCli tc = new TajoCli(tajoConf, new String[] {}, connParams, is, out, err);

                tc.executeMetaCommand("\\set ON_ERROR_STOP false");
                assertSessionVar(tc, SessionVars.ON_ERROR_STOP.keyname(), "false");

                po.write(new String("asdf;\nqwe;\nzxcv;\n").getBytes());

                tc.runShell();/*w w w  .j  a  v a  2s .co m*/
            } catch (Exception e) {
                throw new RuntimeException("Cannot run thread in testRunWhenError", e);
            }
        }
    };

    t.start();
    Thread.sleep(1000);
    if (!t.isAlive()) {
        fail("TSQL should be alive");
    } else {
        t.interrupt();
        t.join();
    }
}

From source file:sce.RESTJobThread.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    setContext(context); //set context

    //JobKey key = context.getJobDetail().getKey();
    //JobDataMap jobDataMap = getContext().getJobDetail().getJobDataMap();
    Thread t = new Thread() {
        @Override//from   w w w . ja  v a  2 s.c  om
        public void run() {
            try {
                URL url = new URL(getContext().getJobDetail().getJobDataMap().getString("#url"));
                setURLConnection(url.openConnection());

                setResult(getUrlContents(getURLConnection()));

                //set the result to the job execution context, to be able to retrieve it later (e.g., with a job listener)
                getContext().setResult(result);

                //if notificationEmail is defined in the job data map, then send a notification email to it
                if (getContext().getJobDetail().getJobDataMap().containsKey("#notificationEmail")) {
                    sendEmail(getContext(),
                            getContext().getJobDetail().getJobDataMap().getString("#notificationEmail"));
                }

                //trigger the linked jobs of the finished job, depending on the job result [true, false]
                jobChain(getContext());

                //Mail.sendMail("prova", "disdsit@gmail.com", "prova di email", "", "");
                System.out.println("Instance " + getContext().getJobDetail().getKey() + " of REST Job returns: "
                        + truncateResult(result));
            } catch (MalformedURLException e) {
            } catch (IOException e) {
            }
        }
    };
    this.thread = t; //set thread
    t.start();

    while (!this.interrupted && t.isAlive()) {
        try {
            t.join();
        } catch (InterruptedException e) {
            break;
        }
    }

    if (t.isAlive()) {
        // might want to log something here since the call is still
        // running but the quartz job is finishing
    }
}

From source file:uk.co.gidley.jmxmonitor.services.ThreadManager.java

public void initialise() throws InitialisationException {
    // Start shutdown socket service
    ShutdownRunner shutdownRunner = null;
    try {// w  ww .j a v a 2  s  .c  o  m
        shutdownRunner = new ShutdownRunner(mainConfiguration.getConfiguration());
    } catch (IOException e) {
        logger.error("{}", e);
        throw new InitialisationException(e);
    }
    Thread shutdownThread = new Thread(shutdownRunner, SHUTDOWN_MONITOR_THREAD);

    try {

        shutdownThread.start();

        // Configure Monitoring Group instances
        List<String> monitoringGroupNames = mainConfiguration.getConfiguration()
                .getList(PROPERTY_PREFIX + "groups");

        for (String groupName : monitoringGroupNames) {
            if (!StringUtils.isEmpty(groupName)) {
                logger.debug("Started initialising {}", groupName);
                initialiseMonitoringGroup(groupName, mainConfiguration.getConfiguration());
                logger.debug("Completed initialising {}", groupName);
            }
        }

        // Start threads to begin monitoring
        logger.info("Configuration complete starting all monitors");
        for (String groupName : monitoringGroups.keySet()) {
            Thread thread = monitoringGroups.get(groupName).getThread();
            thread.start();
        }

        // Continue to monitor for failures or stop message. On failure stop group, restart it if possible
        while (threadManagerRunning) {
            for (String groupName : monitoringGroups.keySet()) {
                MonitoringGroup monitoringGroup = monitoringGroups.get(groupName).getMonitoringGroup();
                if (!monitoringGroup.isAlive()) {
                    restartMonitoringGroup(groupName, mainConfiguration.getConfiguration());
                }
            }

            // Stop if the shutdown thread has triggered. 
            if (!shutdownThread.isAlive()) {
                threadManagerRunning = false;
                for (String groupName : monitoringGroups.keySet()) {
                    logger.debug("Stopping {}", groupName);
                    MonitoringGroup monitoringGroup = monitoringGroups.get(groupName).getMonitoringGroup();
                    monitoringGroup.stop();
                }
                for (String groupName : monitoringGroups.keySet()) {
                    Thread monitoringGroup = monitoringGroups.get(groupName).getThread();
                    monitoringGroup.join();
                    logger.debug("Stopped {}", groupName);
                }
            }

            Thread.sleep(5000);
        }

    } catch (NoSuchElementException e) {
        logger.error("{}", e);
        throw new InitialisationException(e);
    } catch (InterruptedException e) {
        logger.error("{}", e);
        throw new RuntimeException(e);
    } finally {
        // Must shutdown the shutdown thread
        shutdownThread.interrupt();

    }

}

From source file:org.proteomecommons.tranche.proxy.UploadThread.java

public void run() {
    try {// w ww  . j a  v a 2  s . c om
        ServerUtil.waitForStartup();

        // set the password of the user zip file
        uzf.setPassphrase(uzfPassphrase);

        // register the bouncy castle code
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        aft = new AddFileTool(uzf.getCertificate(), uzf.getPrivateKey());

        // should it upload as a directory as a single file?
        aft.setExplodeBeforeUpload(uploadAsDirectory);

        // set the parameters
        aft.setTitle(title);
        aft.setDescription(description);
        aft.setUseRemoteReplication(useRemoteRep);
        aft.setSkipExistingChunk(skipExistingChunks);

        if (passphrase != null && !passphrase.equals("")) {
            aft.setPassphrase(passphrase);
        }

        if (servers != null && servers.size() > 0) {
            for (String server : servers) {
                aft.addServerURL(server);
            }
        }

        status = STATUS_UPLOADING;

        // there should only be one file - either a file or a directory
        hash = aft.addFile(uploadedFile);

        // register the upload with proteomecommons if desired
        if (register) {
            status = STATUS_REGISTERING;
            try {
                // flag for registered
                boolean registered = false;
                // try to register
                for (int registerAttempt = 0; registerAttempt < 3; registerAttempt++) {
                    // keep track of the status code
                    final int[] statusCode = new int[1];

                    // spawn registration in a thread so it can be timed out
                    Thread t = new Thread() {

                        public void run() {
                            try {
                                // if the passphrase is null, save it as ""
                                String p = passphrase;
                                if (p == null) {
                                    p = ""; // make a new client
                                }
                                HttpClient c = new HttpClient();

                                // make a post method
                                PostMethod pm = new PostMethod(
                                        "http://www.proteomecommons.org/dev/tranche/register.jsp");
                                NameValuePair b = new NameValuePair("hash", hash.toString());
                                NameValuePair a = new NameValuePair("passphrase", p);
                                // set the values
                                pm.setRequestBody(new NameValuePair[] { a, b });

                                // execute the method
                                statusCode[0] = c.executeMethod(pm);

                                // release the connection
                                pm.releaseConnection();
                            } catch (Exception e) {
                                // do nothing
                            }
                        }
                    };
                    t.start();

                    // wait for up to 45 seconds
                    t.join(45 * 1000);
                    // pitch an exception
                    if (t.isAlive() || statusCode[0] != 200) {
                        throw new Exception("Can't register upload on ProteomeCommons.org");
                    }
                    break;
                }
            } catch (Exception e) {
                // do nothing
            }
        }

        status = STATUS_COMPLETED;
    } catch (Exception e) {
        exception = e;
        status = STATUS_FAILED;
    }
}

From source file:org.apache.usergrid.tools.ExportAdmins.java

/**
 * Export admin users using multiple threads.
 * <p/>/*from www .j  ava 2s. c  o  m*/
 * How it works:
 * In main thread we query for IDs of all admin users, add each ID to read queue.
 * Read-queue workers read admin user data, add data to write queue.
 * One write-queue worker reads data writes to file.
 */
@Override
public void runTool(CommandLine line) throws Exception {
    startSpring();

    setVerbose(line);

    applyOrgId(line);
    prepareBaseOutputFileName(line);
    outputDir = createOutputParentDir();
    logger.info("Export directory: " + outputDir.getAbsolutePath());

    if (StringUtils.isNotEmpty(line.getOptionValue(READ_THREAD_COUNT))) {
        try {
            readThreadCount = Integer.parseInt(line.getOptionValue(READ_THREAD_COUNT));
        } catch (NumberFormatException nfe) {
            logger.error("-" + READ_THREAD_COUNT + " must be specified as an integer. Aborting...");
            return;
        }
    } else {
        readThreadCount = 20;
    }

    buildOrgMap();

    // start write queue worker

    BlockingQueue<AdminUserWriteTask> writeQueue = new LinkedBlockingQueue<AdminUserWriteTask>();
    AdminUserWriter adminUserWriter = new AdminUserWriter(writeQueue);
    Thread writeThread = new Thread(adminUserWriter);
    writeThread.start();
    logger.debug("Write thread started");

    // start read queue workers

    BlockingQueue<UUID> readQueue = new LinkedBlockingQueue<UUID>();
    for (int i = 0; i < readThreadCount; i++) {
        AdminUserReader worker = new AdminUserReader(readQueue, writeQueue);
        Thread readerThread = new Thread(worker, "AdminUserReader-" + i);
        readerThread.start();
    }
    logger.debug(readThreadCount + " read worker threads started");

    // query for IDs, add each to read queue

    Query query = new Query();
    query.setLimit(MAX_ENTITY_FETCH);
    query.setResultsLevel(Query.Level.IDS);
    EntityManager em = emf.getEntityManager(CpNamingUtils.MANAGEMENT_APPLICATION_ID);
    Results ids = em.searchCollection(em.getApplicationRef(), "users", query);

    while (ids.size() > 0) {
        for (UUID uuid : ids.getIds()) {
            readQueue.add(uuid);
            //logger.debug( "Added uuid to readQueue: " + uuid );
        }
        if (ids.getCursor() == null) {
            break;
        }
        query.setCursor(ids.getCursor());
        ids = em.searchCollection(em.getApplicationRef(), "users", query);
    }

    logger.debug("Waiting for write thread to complete");

    boolean done = false;
    while (!done) {
        writeThread.join(10000, 0);
        done = !writeThread.isAlive();
        logger.info("Wrote {} users", userCount.get());
    }
}