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.nextgis.woody.fragment.LoginFragment.java

private void signup() {
    if (!UiUtil.isEmailValid(mLogin.getText().toString())) {
        Toast.makeText(getActivity(), R.string.email_not_valid, Toast.LENGTH_SHORT).show();
        return;/*  w  w w.  j  a  v a 2s .c  o  m*/
    }
    mSignInButton.setEnabled(false);
    Runnable signUp = new Runnable() {
        @Override
        public void run() {
            final boolean[] result = new boolean[1];

            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    result[0] = NGWUtil.signUp(mUrlText, mLogin.getText().toString(),
                            mPassword.getText().toString(), null, null);
                }
            });
            t.start();

            while (t.isAlive()) {
                SystemClock.sleep(300);
            }

            if (result[0]) {
                getLoaderManager().restartLoader(R.id.auth_token_loader, null, LoginFragment.this);
            } else {
                Toast.makeText(getActivity(), R.string.error_sign_up, Toast.LENGTH_LONG).show();
            }

            if (mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
            }
        }
    };

    new Handler().post(signUp);
}

From source file:fr.lirmm.graphik.graal.bench.homomorphism.InfHomomorphismBench.java

private DefaultUnionOfConjunctiveQueries rewrite(ConjunctiveQuery q) {

    Rewriter r = new Rewriter(q, onto, rc);
    Thread thread = new Thread(r);
    thread.start();// w w  w.  j a  va 2  s. co m
    try {
        thread.join(3600000); // 60min
    } catch (InterruptedException e1) {

    }
    if (thread.isAlive()) {
        thread.stop();
        return null;
    } else {
        return r.getUCQ();
    }

}

From source file:org.socraticgrid.addrbookmgr.AddressBookImpl.java

/**
 * Return the addresses that match the query.
 * //from   ww w  .j a  v  a 2 s  . com
 * @param request
 * @return
 */
public org.socraticgrid.common.addrbook.GetSummariesResponseType searchAddr(
        org.socraticgrid.common.addrbook.SearchAddrRequestType request) {
    GetSummariesResponseType response = new GetSummariesResponseType();

    try {

        System.out.println("searchAddr(): Query=" + request.getUserId());

        AddrBookService dbService = new AddrBookService();
        AddressQueryParams query = new AddressQueryParams();
        query.setUserId(request.getUserId());
        List<AddressItem> addrs = dbService.addressQuery(query);

        log.debug("Starting address agents for query.");

        //Loop through all agents and ask them to return the contact ids
        List<Thread> threads = new LinkedList<Thread>();
        for (AddrBookAgent agent : agents) {
            agent.setAddressStart(addrs);
            Thread thread = new Thread(agent);
            thread.start();
            threads.add(thread);
        }

        //Wait for all threads to finish
        for (Thread thread : threads) {
            while (thread.isAlive()) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ie) {
                }
            }
        }

        log.debug("Processing agent retrieved contact info for query: " + request.getSearch());

        //Loop through get contacts
        ContactDAO contactDAO = LdapService.getContactDAO();
        List<String> lookups = new LinkedList<String>();
        for (AddrBookAgent agent : agents) {
            for (AddressItem addr : agent.getAddressFinish()) {

                //First check if the contact matches our search query
                if ((request.getSearch() != null) && !request.getSearch().isEmpty()
                        && !addr.getName().matches(request.getSearch())) {
                    continue;
                }

                //Check if we've already done this lookup
                if (lookups.contains(addr.getContactId())) {
                    continue;
                }
                lookups.add(addr.getContactId());

                log.debug("Looking up ldap contact: " + addr.getContactId());

                List<ContactDTO> contacts = contactDAO.findContact(addr.getContactId());
                for (ContactDTO contact : contacts) {
                    ContactSummary summary = new ContactSummary();
                    summary.setAddressId(addr.getAddressId().toString() + ADDR_ID_DELIM + addr.getName()
                            + ADDR_ID_DELIM + "cn=" + contact.getCommonName());
                    summary.setName(addr.getName());
                    summary.setLocation(contact.getLocality() == null ? "" : contact.getLocality());
                    summary.setDescription(contact.getDescription() == null ? "" : contact.getDescription());

                    response.getSummaryObjects().add(summary);
                }
            }
        }

        //Sort contacts
        Collections.sort(response.getSummaryObjects(), new SummaryComparator());
    } catch (Throwable t) {
        log.error("Error getting all addresses.", t);

        ServiceError error = new ServiceError();
        error.setCode(ERROR_ADDRBOOK);
        error.setText(t.getMessage() == null ? t.getClass().getName() : t.getMessage());
        response.getErrorList().add(error);
    }

    return response;
}

From source file:com.persinity.ndt.datamutator.DataMutator.java

/**
 * Will block calling thread until all loaders are done.
 *//*from  w w  w  .j av  a2s .  c om*/
public void waitToFinish() {
    log.info("Waiting to finish {} threads...", threads.size());

    view.start();
    startStatusDumpTask();

    while (true) {
        Thread aliveTh = null;
        synchronized (lock) {
            for (Thread th : threads) {
                if (th.isAlive()) {
                    aliveTh = th;
                    break;
                }
            }
        }

        if (aliveTh == null) {
            break;
        }

        try {
            aliveTh.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    scheduler.shutdown();
    entityFactory.close();

    log.info("All threads DONE.");
    view.logMsg("Load done");
}

From source file:org.openhab.binding.modbus.internal.SimultaneousReadWriteTestCase.java

@Test
public void testPoolBlocks() throws Exception {
    final KeyedObjectPool<ModbusSlaveEndpoint, ModbusSlaveConnection> pool = ModbusBinding
            .getReconstructedConnectionPoolForTesting();

    final ModbusTCPSlaveEndpoint endpoint = new ModbusTCPSlaveEndpoint(localAddress().getHostAddress(),
            this.tcpModbusPort);

    ModbusSlaveConnection borrowObject = pool.borrowObject(endpoint);
    Thread thread = new Thread() {
        @Override/*from w  ww. ja v  a  2  s.  co m*/
        public void run() {
            try {
                ModbusSlaveConnection borrowObject2 = pool.borrowObject(endpoint);
                pool.returnObject(endpoint, borrowObject2);
            } catch (Exception e) {
                e.printStackTrace(System.err);
            }
        }
    };
    thread.start();
    thread.join(500);
    if (!thread.isAlive()) {
        throw new AssertionError("Thread should still be alive -- blocking since no objects");
    } else {
        thread.interrupt();
    }

    pool.returnObject(endpoint, borrowObject);
    // Now that object has been returned, borrowing should work again
    ModbusSlaveConnection borrowObject2 = pool.borrowObject(endpoint);
    pool.returnObject(endpoint, borrowObject2);

}

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

private int nextUniqueIdUpdateForAnExistingTableShouldWorkAndConcurrency(final String tableName,
        final int nbThreads) throws SQLException, InterruptedException {
    Logger.getAnonymousLogger().info("Start at " + System.currentTimeMillis() + " with " + nbThreads
            + " threads for table " + tableName);
    final Thread[] threads = new Thread[nbThreads];
    for (int i = 0; i < nbThreads; i++) {
        threads[i] = new Thread(() -> {
            try {
                int nextId = DBUtil.getNextId(tableName, "id");
                Logger.getAnonymousLogger().info(
                        "Next id for " + tableName + " is " + nextId + " at " + System.currentTimeMillis());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }/*from  w w w  .j  ava 2s  . co  m*/
        });
    }

    try {
        for (Thread thread : threads) {
            thread.start();
            Thread.sleep(5);
        }
        for (Thread thread : threads) {
            thread.join();
        }
        return actualMaxIdInUniqueIdFor(tableName);
    } finally {
        for (Thread thread : threads) {
            if (thread.isAlive()) {
                thread.interrupt();
            }
        }
    }
}

From source file:no.eris.applet.AppletViewer.java

private void destroyThreadGroup() {
    if (threadGroup != null && !threadGroup.isDestroyed()) {
        LOGGER.debug("Threads not dead - killing them");
        Thread[] aliveThreads = null;
        boolean enumeratedAll = false;
        while (!enumeratedAll) {
            int countThreads = threadGroup.activeCount();
            aliveThreads = new Thread[countThreads + 2]; // take some margin
            int enumerated = threadGroup.enumerate(aliveThreads);
            enumeratedAll = enumerated < aliveThreads.length;
            if (!enumeratedAll)
                LOGGER.debug("Couldn't enumerate all threads");
        }/*from  ww  w .j  a  v  a2 s.co  m*/
        for (Thread aliveThread : aliveThreads) {
            if (aliveThread != null && aliveThread.isAlive()) {
                ThreadUtils.forceInterrupt(aliveThread);
            }
        }
        if (threadGroup.activeCount() == 0) {
            threadGroup.destroy();
        } else {
            LOGGER.debug("Couldn't destroy thread group: not empty !");
            ThreadUtils.printAliveThreadStack();
        }
        threadGroup = null;
    }
}

From source file:org.syncany.tests.integration.scenarios.Issue429ScenarioTest.java

@Ignore
public void testSameFileDifferentNameFuzzy() throws Exception {
    for (int seed = 0; seed < 1000; seed++) {
        LocalTransferSettings testConnection = (LocalTransferSettings) TestConfigUtil
                .createTestLocalConnection();

        TestClient clientA = new TestClient("A", testConnection);
        TestClient clientB = new TestClient("B", testConnection);

        Random randomA = new Random(2 * seed);
        Random randomB = new Random(2 * seed + 1);

        Queue<String> queue = new ConcurrentLinkedQueue<>();

        activeThread A = new activeThread(randomA, clientA, queue);
        activeThread B = new activeThread(randomB, clientB, queue);
        Thread AThread = new Thread(A, "A");
        Thread BThread = new Thread(B, "B");
        try {//from  ww  w  .j  a v  a  2 s. c o  m
            AThread.start();
            BThread.start();
            //            int actionsA = -1;
            //            int actionsB = -1;

            for (int i = 0; i < 50; i++) {
                TestClient clientC = new TestClient("C", testConnection);
                clientC.down();
                if (!AThread.isAlive() || !BThread.isAlive()) {
                    throw new RuntimeException("One of the threads died");
                }

                FileUtils.deleteDirectory(clientC.getLocalFile(""));
                Thread.sleep(2000);
            }

            AThread.interrupt();
            BThread.interrupt();
        } catch (Exception e) {
            logger.log(Level.INFO, "Queue:" + queue.toString());
            logger.log(Level.INFO, "Something went wrong at seed: " + seed);
            throw e;
        }
        clientA.deleteTestData();
        clientB.deleteTestData();
    }
}

From source file:org.apache.hadoop.hbase.zookeeper.TestZooKeeperNodeTracker.java

/**
 * Test that we can interrupt a node that is blocked on a wait.
 * @throws IOException/*ww w  .j  av  a  2 s.c o  m*/
 * @throws InterruptedException
 */
@Test
public void testInterruptible() throws IOException, InterruptedException {
    Abortable abortable = new StubAbortable();
    ZooKeeperWatcher zk = new ZooKeeperWatcher(TEST_UTIL.getConfiguration(), "testInterruptible", abortable);
    final TestTracker tracker = new TestTracker(zk, "/xyz", abortable);
    tracker.start();
    Thread t = new Thread() {
        @Override
        public void run() {
            try {
                tracker.blockUntilAvailable();
            } catch (InterruptedException e) {
                throw new RuntimeException("Interrupted", e);
            }
        }
    };
    t.start();
    while (!t.isAlive())
        Threads.sleep(1);
    tracker.stop();
    t.join();
    // If it wasn't interruptible, we'd never get to here.
}

From source file:edu.synth.SynthHelper.java

private void menu() {
    menuBar = new JMenuBar();
    setJMenuBar(menuBar);//ww w.  j av  a  2 s  .c om

    mnFile = new JMenu("File");
    menuBar.add(mnFile);

    mntmOpenWorkspace = new JMenuItem("Open Workspace...");
    mntmOpenWorkspace.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    clear();
                    String path = SyntHelper.getInstance().openDialogFileChooser(state.getWorkspacePath(), true,
                            "Choose Workspace", "Choose", null);
                    try {
                        state.setWorkspacePath(path);
                    } catch (IOException e) {
                        Messager.publish("Set Workspace", e);
                    }
                    initSettings();
                    setValues();
                }
            }).start();
        }
    });
    mnFile.add(mntmOpenWorkspace);

    mntmApplyChanges = new JMenuItem("Save Changes...");
    mntmApplyChanges.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        state.saveSettings();
                    } catch (IOException e) {
                        Messager.publish("Save Settings Files", e);
                    }
                }
            }).start();
        }
    });
    mnFile.add(mntmApplyChanges);

    mntmExportConfFiles = new JMenuItem("Export Settings Files to Workspace...");
    mntmExportConfFiles.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        state.saveSettings();
                    } catch (IOException e) {
                        Messager.publish("Save Settings Files", e);
                    }
                    if (!state.getWorkspacePath().isEmpty())
                        try {
                            state.copySettingsFilesToWorkspace();
                        } catch (IOException e) {
                            Messager.publish("Export Settings Files to Workspace", e);
                        }
                    else
                        Messager.publish("Export Settings Files to Workspace",
                                "Files have not been copied. Workspace has not been selected!");
                }
            }).start();
        }
    });
    mnFile.add(mntmExportConfFiles);

    mnFile.add(new JSeparator());
    mntmExit = new JMenuItem("Exit");
    mntmExit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            System.exit(0);
        }
    });
    mnFile.add(mntmExit);

    mnOperations = new JMenu("Operations");
    menuBar.add(mnOperations);

    mntmViewObs = new JMenuItem("View Observed Data (1.obs)");
    mntmViewObs.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        new DataViewWindow("Observed Data Viewer", new File(Constants.OBS_DATA));
                    } catch (IOException e) {
                        Messager.publish("Observed Data Viewer error", e);
                    }
                }
            }).start();
        }
    });
    mnOperations.add(mntmViewObs);

    mnOperations.add(new JSeparator());

    mntmRunSynth = new JMenuItem("Run Synth");
    mntmRunSynth.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            new Thread(new ExecuteSynthConvThread()).start();
        }
    });
    mnOperations.add(mntmRunSynth);

    mntmRunSynthForObs = new JMenuItem("Run Synth for Observed Data");
    mntmRunSynthForObs.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            final Thread main = new Thread(new ExecuteSynthConvDivThread());
            main.start();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (main.isAlive()) {
                    }
                    ;
                    try {
                        new SyntHelperChartWindow("Result of synthesis and dividing");
                    } catch (IOException e) {
                        Messager.publish("Charting result error", e);
                    }
                }
            }).start();
        }
    });
    mnOperations.add(mntmRunSynthForObs);

    mnHelp = new JMenu("Help");
    menuBar.add(mnHelp);

    mntmLogWindow = new JMenuItem("Log Window");
    mntmLogWindow.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            LogPublisher.getInstance().openWindow();
        }
    });
    mnHelp.add(mntmLogWindow);

    mnHelp.add(new JSeparator());

    mntmAbout = new JMenuItem("About SYNTHelper");
    mnHelp.add(mntmAbout);

    mntmHelp = new JMenuItem("Help Content");
    mnHelp.add(mntmHelp);
}