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:ubc.pavlab.aspiredb.cli.AbstractCLI.java

/**
 * Wait for completion./*from www.j av  a2  s . c om*/
 */
protected void waitForThreadPoolCompletion(Collection<Thread> threads) {

    while (true) {
        boolean anyAlive = false;
        for (Thread k : threads) {
            if (k.isAlive()) {
                anyAlive = true;
            }
        }
        if (!anyAlive) {
            break;
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.jenkinsci.plugins.compress_artifacts.ZipStorageTest.java

@Test
public void avoidZipExceptionWhileWriting() throws Exception {
    FileUtils.writeStringToFile(new File(content, "file"), "content");

    final Entry<String, String> validArtifact = Collections.singletonMap("file", "file").entrySet().iterator()
            .next();//from   w w  w . java  2  s.c  o  m

    // Simulate archiving that takes forever serving valid artifact and then block forever on the next.
    final Map<String, String> artifacts = new HashMap<String, String>() {
        @Override
        public Set<Map.Entry<String, String>> entrySet() {
            return new HashSet<Map.Entry<String, String>>() {
                @Override
                public Iterator<Map.Entry<String, String>> iterator() {
                    return new Iterator<Map.Entry<String, String>>() {
                        private boolean block = false;

                        public boolean hasNext() {
                            return true;
                        }

                        public Map.Entry<String, String> next() {
                            if (!block) {
                                block = true;
                                return validArtifact;
                            }

                            synchronized (this) {
                                try {
                                    this.wait(); // Block forever
                                    throw new AssertionError();
                                } catch (InterruptedException ex) {
                                    // Expected at cleanup time
                                }
                            }

                            return validArtifact;
                        }

                        public void remove() {
                            throw new UnsupportedOperationException();
                        }
                    };
                }
            };
        }
    };

    // start archiving
    Thread compressor = new Thread("compressing-thread") {
        @Override
        public void run() {
            try {
                archive(artifacts);
            } catch (Exception ex) {
                throw new Error(ex);
            }
        }
    };

    compressor.start();
    try {
        Thread.sleep(1000);

        assertTrue(compressor.isAlive());

        assertArrayEquals(new String[0], zs.list());
        assertArrayEquals(new VirtualFile[0], zs.list("*"));
    } finally {
        compressor.stop();
    }
}

From source file:uk.ac.ucl.cs.cmic.giftcloud.uploadapp.QueryRetrieveController.java

public synchronized void query(final QueryParams queryParams) throws GiftCloudException, DicomException {

    // Report an error if a previous thread has not yet completed
    if (activeThread != null && activeThread.isAlive()) {
        throw new GiftCloudException(GiftCloudUploaderError.QUERY_RETRIEVE_STILL_IN_PROGRESS);
    }/* ww  w  . j ava 2 s.co m*/

    currentRemoteQueryInformationModel = Optional.of(createRemoteQueryInformationModel());
    Optional<QueryRetrieveRemoteView> remoteView = dialogController.getQueryRetrieveRemoteView();
    if (!remoteView.isPresent()) {
        throw new IllegalStateException(
                "query() was called but no QueryRetrieveRemoteView was found for storing the results");
    }
    remoteView.get().removeAll();
    remoteView.get().validate();
    AttributeList filter = queryParams.build();
    Thread activeThread = new Thread(new QueryWorker(remoteView.get(), currentRemoteQueryInformationModel.get(),
            filter, uploaderStatusModel, reporter));
    activeThread.start();
}

From source file:gui.accessories.DownloadProgressWork.java

@Override
public Void doInBackground() throws FileNotFoundException {
    setProgress(0);//from w ww  . j a  va 2  s  . co  m
    try {
        Thread.sleep(1000);
        downloadFile = new File(new File(portraitsFolder), portraitsFileName);
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    downloadFile = portraitsService.downloadPortraisFile(portraitsFileName, portraitsFolder);
                    filesCount = doUncompressZip(downloadFile);
                } catch (FileNotFoundException ex) {
                    LOG.error("Qu mal todo. " + ex.getMessage());
                } catch (ZipException ex) {
                    LOG.error("Qu mal todo descomprimiendo. " + ex.getMessage());
                }
            }
        });
        t.start();
        while (t.isAlive()) {
            Float progreso = downloadFile.length() / (float) fileSize;
            progreso *= 100;
            int progress = progreso.intValue();

            setProgress(progress);
        }

    } catch (InterruptedException ignore) {
    }
    return null;
}

From source file:org.drftpd.tests.ConnectionStressTest.java

public void testStress() {
    int i = 0;//w  ww  .j  av a  2s  . c o  m
    for (; i < 200; i++) {
        Thread t = new Thread(new DummyClient(this));

        list.add(t);

        t.start();
        t.setName("DummyClient-" + i);
        logger.debug("Launching DummyClient #" + i);

        try {
            Thread.sleep(100); //give the daemon some time.   
        } catch (InterruptedException e) {
            logger.fatal(e, e);
        }
    }

    assertTrue(success == i); // means that every attemp was successful when connecting

    Collections.reverse(list); // must reverse the order in order to iterate thru the first client firstly.

    int dead = 0;
    for (Thread t : list) {
        while (t.isAlive()) {
            // shotdown gracefully.
        }
        dead += 1;
    }

    assertTrue(dead == success); // all threads were finalized.
}

From source file:org.dataconservancy.packaging.tool.impl.IPMServiceImpl.java

@Override
public Node createTreeFromFileSystem(Path path) throws IOException {

    visitedFiles.clear();//from  w w  w  .  jav  a 2  s . c  o m
    fileUris.clear();
    fileToNode.clear();

    Walker walker = new Walker();

    Thread walkerThread = new Thread(() -> {
        try {
            walker.doWalk(path.toFile(), visitedFiles);
        } catch (IOException e) {
            walker.cancel();
        }
    });

    walkerThread.start();

    while (walkerThread.isAlive()) {
        if (Thread.currentThread().isInterrupted()) {
            walker.cancel();
        }
        try {
            walkerThread.join(1000 * 5);
        } catch (InterruptedException e) {
            // ignore
        }
    }

    visitedFiles.parallelStream().forEach(visitedNode -> {
        final File file = fileUris.get(visitedNode.getIdentifier());
        final FileInfo fi;
        try {
            fi = new FileInfo(file.toPath().toRealPath());
            visitedNode.setFileInfo(fi);
        } catch (IOException e) {
            log.warn("Unable to resolve file path '{}': {}", file.toPath(), e.getMessage(), e);
        }
    });

    return walker.getRoot();
}

From source file:net.greghaines.jesque.worker.WorkerImpl.java

/**
 * {@inheritDoc}//w w  w  .j a v  a2 s.  c om
 */
@Override
public void join(final long millis) throws InterruptedException {
    final Thread workerThread = this.threadRef.get();
    if (workerThread != null && workerThread.isAlive()) {
        workerThread.join(millis);
    }
}

From source file:org.silverpeas.core.util.DBUtilIntegrationTest.java

@Test
public void nextUniqueIdUpdateForAnExistingTableShouldWorkAndConcurrency()
        throws SQLException, InterruptedException {
    int nextIdBeforeTesting = actualMaxIdInUniqueIdFor("User");
    assertThat(nextIdBeforeTesting, is(1));
    int nbThreads = 2 + (int) (Math.random() * 10);
    Logger.getAnonymousLogger()/*ww  w  . j  a v a 2 s.  c  om*/
            .info("Start at " + System.currentTimeMillis() + " with " + nbThreads + " threads");
    final Thread[] threads = new Thread[nbThreads];
    for (int i = 0; i < nbThreads; i++) {
        threads[i] = new Thread(() -> {
            try {
                int nextId = DBUtil.getNextId("User", "id");
                Logger.getAnonymousLogger().info("Next id is " + nextId + " at " + System.currentTimeMillis());
                Thread.sleep(10);
            } catch (InterruptedException | SQLException e) {
                throw new RuntimeException(e);
            }
        });
    }

    try {
        for (Thread thread : threads) {
            thread.start();
        }
        for (Thread thread : threads) {
            thread.join();
        }
        int expectedNextId = nextIdBeforeTesting + nbThreads;
        Logger.getAnonymousLogger()
                .info("Verifying nextId is " + expectedNextId + " at " + System.currentTimeMillis());
        assertThat(actualMaxIdInUniqueIdFor("User"), is(expectedNextId));
    } finally {
        for (Thread thread : threads) {
            if (thread.isAlive()) {
                thread.interrupt();
            }
        }
    }
}

From source file:org.silverpeas.core.util.DBUtilIT.java

@Test
public void nextUniqueIdUpdateForAnExistingTableShouldWorkAndConcurrency()
        throws SQLException, InterruptedException {
    int nextIdBeforeTesting = actualMaxIdInUniqueIdFor("User");
    assertThat(nextIdBeforeTesting, is(1));
    int nbThreads = 2 + (int) (Math.random() * 10);
    Logger.getAnonymousLogger()//from   w w  w.  j a v a 2 s.  c o m
            .info("Start at " + System.currentTimeMillis() + " with " + nbThreads + " threads");
    final Thread[] threads = new Thread[nbThreads];
    for (int i = 0; i < nbThreads; i++) {
        threads[i] = new Thread(() -> {
            try {
                int nextId = DBUtil.getNextId("User", "id");
                Logger.getAnonymousLogger().info("Next id is " + nextId + " at " + System.currentTimeMillis());
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
    }

    try {
        for (Thread thread : threads) {
            thread.start();
        }
        for (Thread thread : threads) {
            thread.join();
        }
        int expectedNextId = nextIdBeforeTesting + nbThreads;
        Logger.getAnonymousLogger()
                .info("Verifying nextId is " + expectedNextId + " at " + System.currentTimeMillis());
        assertThat(actualMaxIdInUniqueIdFor("User"), is(expectedNextId));
    } finally {
        for (Thread thread : threads) {
            if (thread.isAlive()) {
                thread.interrupt();
            }
        }
    }
}

From source file:org.efaps.esjp.common.jasperreport.StandartReport_Base.java

/**
 * Gets the file.// www.j a  v a2  s  .c  o  m
 *
 * @param _parameter Parameter as passed by the eFasp API
 * @return file created
 * @throws EFapsException on error
 */
public File getFile(final Parameter _parameter) throws EFapsException {
    File ret = null;

    final String dataSourceClass = getDataSourceClass(_parameter);

    add2ReportParameter(_parameter);

    final Instance jasperInst = getJasperReportInstance(_parameter);
    if (jasperInst != null && jasperInst.isValid()) {
        final Checkout checkout = new Checkout(jasperInst);
        final InputStream iin = checkout.execute();
        try {
            DefaultJasperReportsContext.getInstance().setProperty(
                    "net.sf.jasperreports.query.executer.factory.eFaps",
                    EQLQueryExecuterFactory.class.getName());
            final LocalJasperReportsContext ctx = new LocalJasperReportsContext(
                    DefaultJasperReportsContext.getInstance());
            ctx.setFileResolver(new JasperFileResolver());
            ctx.setClassLoader(EFapsClassLoader.getInstance());

            ctx.setProperty("net.sf.jasperreports.subreport.runner.factory",
                    SubReportRunnerFactory.class.getName());
            ctx.setProperty("net.sf.jasperreports.query.executer.factory.eFaps",
                    EQLQueryExecuterFactory.class.getName());

            final JasperReport jasperReport = (JasperReport) JRLoader.loadObject(iin);
            iin.close();

            IeFapsDataSource dataSource = null;
            if (dataSourceClass != null) {
                final Class<?> clazz = Class.forName(dataSourceClass);
                final Method method = clazz.getMethod("init",
                        new Class[] { JasperReport.class, Parameter.class, JRDataSource.class, Map.class });
                dataSource = (IeFapsDataSource) clazz.newInstance();
                method.invoke(dataSource, jasperReport, _parameter, null, this.jrParameters);
            }
            if (dataSource != null) {
                this.jrParameters.put("EFAPS_SUBREPORT",
                        new SubReportContainer(_parameter, dataSource, this.jrParameters));
            }
            final ReportRunner runner = new ReportRunner(ctx, jasperReport, this.jrParameters, dataSource);
            final Thread t = new Thread(runner);
            t.setContextClassLoader(EFapsClassLoader.getInstance());
            t.start();

            while (t.isAlive()) {
                // add an abort criteria
            }

            // check for a file name, if null search in the properties
            if (getFileName() == null) {
                setFileName(getProperty(_parameter, "FileName"));
                // last chance search in the jasper Parameters
                if (getFileName() == null) {
                    setFileName((String) this.jrParameters.get("FileName"));
                }
            }
            final JasperPrint print = runner.getJasperPrint();
            LOG.debug("print created: '{}'", print);
            if (print != null) {
                ret = getFile(print, getMime(_parameter));
            }

        } catch (final ClassNotFoundException e) {
            throw new EFapsException(StandartReport_Base.class, "execute.ClassNotFoundException", e);
        } catch (final SecurityException e) {
            throw new EFapsException(StandartReport_Base.class, "execute.SecurityException", e);
        } catch (final NoSuchMethodException e) {
            throw new EFapsException(StandartReport_Base.class, "execute.NoSuchMethodException", e);
        } catch (final InstantiationException e) {
            throw new EFapsException(StandartReport_Base.class, "execute.InstantiationException", e);
        } catch (final IllegalAccessException e) {
            throw new EFapsException(StandartReport_Base.class, "execute.IllegalAccessException", e);
        } catch (final IllegalArgumentException e) {
            throw new EFapsException(StandartReport_Base.class, "execute.IllegalArgumentException", e);
        } catch (final InvocationTargetException e) {
            throw new EFapsException(StandartReport_Base.class, "execute.InvocationTargetException", e);
        } catch (final JRException e) {
            throw new EFapsException(StandartReport_Base.class, "execute.JRException", e);
        } catch (final IOException e) {
            throw new EFapsException(StandartReport_Base.class, "execute.IOException", e);
        }
    }
    return ret;
}