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:com.arpnetworking.metrics.impl.ApacheHttpSinkTest.java

@Test
public void testSafeSleep() throws InterruptedException {
    final AtomicBoolean value = new AtomicBoolean(false);
    final Thread thread = new Thread(() -> {
        // Value will not be set if safe sleep throws or is not interrupted.
        ApacheHttpSink.safeSleep(500);/*from   ww w.j av  a  2  s  .co m*/
        value.set(true);
    });

    thread.start();
    Thread.sleep(100);
    thread.interrupt();
    thread.join(600);

    Assert.assertFalse(thread.isAlive());
    Assert.assertTrue(value.get());
}

From source file:com.gist.twitter.TwitterClient.java

/**
 * Divides the ids among the credentials, and starts up a thread
 * for each set of credentials with a TwitterProcessor that
 * connects to twitter, and reconnects on exceptions, and
 * processes the stream.  After processForMillis, interrupt the
 * threads and return./*from   w w w. ja  va  2 s  .  com*/
 */
private void processForATime() {
    Collection<String> followIds = filterParameterFetcher.getFollowIds();
    Collection<Set<String>> followIdSets = createSets(followIds, maxFollowIdsPerCredentials);

    Collection<String> trackKeywords = filterParameterFetcher.getTrackKeywords();
    Collection<Set<String>> trackKeywordSets = createSets(trackKeywords, maxTrackKeywordsPerCredentials);

    Collection<Thread> threads = new ArrayList<Thread>();

    Iterator<UsernamePasswordCredentials> credentialsIterator = credentials.iterator();

    for (Set<String> ids : followIdSets) {
        for (Collection<String> keywords : trackKeywordSets) {
            if (credentialsIterator.hasNext()) {
                UsernamePasswordCredentials upc = credentialsIterator.next();
                Thread t = new Thread(new TwitterProcessor(upc, ids, keywords), "Twitter download as "
                        + upc.getUserName() + " (" + threadCount.getAndIncrement() + ")");
                threads.add(t);
                t.start();
            } else {
                logger.warning("Out of credentials, ignoring some ids/keywords.");
            }
        }
    }

    try {
        Thread.sleep(processForMillis);
    } catch (InterruptedException ex) {
        // Won't happen, ignore.
    }

    for (Thread t : threads) {
        t.interrupt();
    }

    // It doesn't matter so much whether the threads exit in a
    // timely manner.  We'll just get some IOExceptions or
    // something and retry.  This just makes the logs a little
    // nicer since we won't usually start a thread until the old
    // one has exited.
    for (Thread t : threads) {
        try {
            t.join(1000L);
        } catch (InterruptedException ex) {
            // Won't happen.
        }
    }
}

From source file:android.core.SSLSocketTest.java

public void testSSLHandshakeHangTimeout() {

    Thread thread = new Thread() {
        @Override//  w w  w. j av  a2  s. com
        public void run() {
            try {
                SSLSocket socket = (SSLSocket) clientFactory.createSocket("www.heise.de", 80);
                socket.setSoTimeout(5000);
                socket.startHandshake();
                socket.close();
            } catch (Exception ex) {
                handshakeException = ex;
            }
        }
    };

    thread.start();

    try {
        thread.join(10000);
    } catch (InterruptedException ex) {
        // Ignore.
    }

    if (handshakeException == null) {
        fail("SSL handshake should have failed.");
    }
}

From source file:de.fu_berlin.inf.dpp.Saros.java

/**
 * This method is called when the plug-in is stopped
 *///from   w w w  .ja va  2 s. co m
@Override
public void stop(BundleContext context) throws Exception {

    // TODO Devise a general way to stop and dispose our components
    saveGlobalPreferences();
    saveSecurePrefs();

    if (dotMonitor != null) {
        File file = ResourcesPlugin.getWorkspace().getRoot().getLocation().toFile();
        file = new File(file, ".metadata"); //$NON-NLS-1$
        file = new File(file, "saros-" + sarosFeatureID + ".dot"); //$NON-NLS-1$ //$NON-NLS-2$
        log.info("Saving Saros architecture diagram dot file: " + file.getAbsolutePath());
        dotMonitor.save(file);
    }

    try {
        Thread shutdownThread = ThreadUtils.runSafeAsync("ShutdownProcess", log, new Runnable() { //$NON-NLS-1$
            @Override
            public void run() {

                try {

                    sessionManager.stopSarosSession();
                    connectionHandler.disconnect();
                } finally {
                    /*
                     * Always shutdown the network to ensure a proper
                     * cleanup(currently only UPNP)
                     */

                    /*
                     * This will cause dispose() to be called on all
                     * components managed by PicoContainer which
                     * implement {@link Disposable}.
                     */
                    sarosContext.dispose();
                }
            }
        });

        shutdownThread.join(10000);
        if (shutdownThread.isAlive())
            log.error("could not shutdown Saros gracefully");

    } finally {
        super.stop(context);
    }

    isInitialized = false;
    setDefault(null);
}

From source file:eu.stratosphere.nephele.taskmanager.runtime.RuntimeTask.java

/**
 * Cancels or kills the task./*from ww  w  . j  ava2 s .  c om*/
 * 
 * @param cancel
 *        <code>true/code> if the task shall be canceled, <code>false</code> if it shall be killed
 */
private void cancelOrKillExecution(final boolean cancel) {

    final Thread executingThread = this.environment.getExecutingThread();

    if (executingThread == null) {
        return;
    }

    if (this.executionState != ExecutionState.RUNNING && this.executionState != ExecutionState.FINISHING) {
        return;
    }

    LOG.info((cancel ? "Canceling " : "Killing ") + this.environment.getTaskNameWithIndex());

    if (cancel) {
        this.isCanceled = true;
        // Change state
        executionStateChanged(ExecutionState.CANCELING, null);

        // Request user code to shut down
        try {
            final AbstractInvokable invokable = this.environment.getInvokable();
            if (invokable != null) {
                invokable.cancel();
            }
        } catch (Throwable e) {
            LOG.error(StringUtils.stringifyException(e));
        }
    }

    // Continuously interrupt the user thread until it changed to state CANCELED
    while (true) {

        executingThread.interrupt();

        if (!executingThread.isAlive()) {
            break;
        }

        try {
            executingThread.join(1000);
        } catch (InterruptedException e) {
        }

        if (!executingThread.isAlive()) {
            break;
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Sending repeated " + (cancel == true ? "canceling" : "killing") + " signal to "
                    + this.environment.getTaskName() + " with state " + this.executionState);
        }
    }
}

From source file:eu.stratosphere.nephele.taskmanager.Task.java

/**
 * Cancels or kills the task.//www .ja  v  a 2  s . c  o m
 *
 * @param cancel <code>true/code> if the task shall be canceled, <code>false</code> if it shall be killed
 */
private void cancelOrKillExecution(boolean cancel) {
    final Thread executingThread = this.environment.getExecutingThread();

    if (executingThread == null) {
        return;
    }

    if (this.executionState != ExecutionState.RUNNING && this.executionState != ExecutionState.FINISHING) {
        return;
    }

    LOG.info((cancel ? "Canceling " : "Killing ") + this.environment.getTaskNameWithIndex());

    if (cancel) {
        this.isCanceled = true;
        // Change state
        executionStateChanged(ExecutionState.CANCELING, null);

        // Request user code to shut down
        try {
            final AbstractInvokable invokable = this.environment.getInvokable();
            if (invokable != null) {
                invokable.cancel();
            }
        } catch (Throwable e) {
            LOG.error(StringUtils.stringifyException(e));
        }
    }

    // Continuously interrupt the user thread until it changed to state CANCELED
    while (true) {

        executingThread.interrupt();

        if (!executingThread.isAlive()) {
            break;
        }

        try {
            executingThread.join(1000);
        } catch (InterruptedException e) {
        }

        if (!executingThread.isAlive()) {
            break;
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Sending repeated " + (cancel == true ? "canceling" : "killing") + " signal to "
                    + this.environment.getTaskName() + " with state " + this.executionState);
        }
    }
}

From source file:android.core.SSLSocketTest.java

public void testSSLHandshakeHangClose() {

    Thread thread = new Thread() {
        @Override/*from www  .  j  a v  a  2  s  .co  m*/
        public void run() {
            try {
                handshakeSocket = (SSLSocket) clientFactory.createSocket("www.heise.de", 80);
                handshakeSocket.startHandshake();
            } catch (Exception ex) {
                handshakeException = ex;
            }
        }
    };

    thread.start();

    try {
        Thread.sleep(5000);
        try {
            handshakeSocket.close();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }

        thread.join(5000);
    } catch (InterruptedException ex) {
        // Ignore.
    }

    if (handshakeException == null) {
        fail("SSL handshake should have failed.");
    }
}

From source file:com.gargoylesoftware.htmlunit.javascript.JavaScriptEngineTest.java

/**
 * @throws Exception if the test fails/*w w  w.jav  a  2s.co  m*/
 */
@Test
public void timeout() throws Exception {
    final WebClient client = getWebClient();
    final long timeout = 2000;
    final long oldTimeout = client.getJavaScriptTimeout();
    client.setJavaScriptTimeout(timeout);

    try {
        client.setThrowExceptionOnScriptError(false);

        final String content = "<html><body><script>while(1) {}</script></body></html>";
        final MockWebConnection webConnection = new MockWebConnection();
        webConnection.setDefaultResponse(content);
        client.setWebConnection(webConnection);

        final Exception[] exceptions = { null };
        final Thread runner = new Thread() {
            @Override
            public void run() {
                try {
                    client.getPage(URL_FIRST);
                } catch (final Exception e) {
                    exceptions[0] = e;
                }
            }
        };

        runner.start();

        runner.join(timeout * 2);
        if (runner.isAlive()) {
            runner.interrupt();
            fail("Script was still running after timeout");
        }
        assertNull(exceptions[0]);
    } finally {
        client.setJavaScriptTimeout(oldTimeout);
    }
}

From source file:jp.ne.sakura.kkkon.java.net.socketimpl.testapp.android.SocketImplHookTestApp.java

/** Called when the activity is first created. */
@Override//ww  w .  j a va  2 s.  c  o  m
public void onCreate(Bundle savedInstanceState) {
    final Context context = this.getApplicationContext();

    {
        SocketImplHookFactory.initialize();
    }
    {
        ProxySelector proxySelector = ProxySelector.getDefault();
        Log.d(TAG, "proxySelector=" + proxySelector);
        if (null != proxySelector) {
            URI uri = null;
            try {
                uri = new URI("http://www.google.com/");
            } catch (URISyntaxException e) {
                Log.d(TAG, e.toString());
            }
            List<Proxy> proxies = proxySelector.select(uri);
            if (null != proxies) {
                for (final Proxy proxy : proxies) {
                    Log.d(TAG, " proxy=" + proxy);
                }
            }
        }
    }

    super.onCreate(savedInstanceState);

    /* Create a TextView and set its content.
     * the text is retrieved by calling a native
     * function.
     */
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);

    TextView tv = new TextView(this);
    tv.setText("ExceptionHandler");
    layout.addView(tv);

    Button btn1 = new Button(this);
    btn1.setText("invoke Exception");
    btn1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            final int count = 2;
            int[] array = new int[count];
            int value = array[count]; // invoke IndexOutOfBOundsException
        }
    });
    layout.addView(btn1);

    {
        Button btn = new Button(this);
        btn.setText("upload http AsyncTask");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() {

                    @Override
                    protected Boolean doInBackground(String... paramss) {
                        Boolean result = true;
                        Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid());
                        try {
                            //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS)
                            Log.d(TAG, "fng=" + Build.FINGERPRINT);
                            final List<NameValuePair> list = new ArrayList<NameValuePair>(16);
                            list.add(new BasicNameValuePair("fng", Build.FINGERPRINT));

                            HttpPost httpPost = new HttpPost(paramss[0]);
                            //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) );
                            httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
                            DefaultHttpClient httpClient = new DefaultHttpClient();
                            Log.d(TAG, "socket.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                            Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                                    new Integer(5 * 1000));
                            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                                    new Integer(5 * 1000));
                            Log.d(TAG, "socket.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                            Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                            // <uses-permission android:name="android.permission.INTERNET"/>
                            // got android.os.NetworkOnMainThreadException, run at UI Main Thread
                            HttpResponse response = httpClient.execute(httpPost);
                            Log.d(TAG, "response=" + response.getStatusLine().getStatusCode());
                        } catch (Exception e) {
                            Log.d(TAG, "got Exception. msg=" + e.getMessage(), e);
                            result = false;
                        }
                        Log.d(TAG, "upload finish");
                        return result;
                    }

                };

                asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug");
                asyncTask.isCancelled();
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(0.0.0.0)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            destHost = InetAddress.getByName("0.0.0.0");
                            if (null != destHost) {
                                try {
                                    if (destHost.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + destHost.toString() + " reachable");
                                    } else {
                                        Log.d(TAG, "destHost=" + destHost.toString() + " not reachable");
                                    }
                                } catch (IOException e) {

                                }
                            }
                        } catch (UnknownHostException e) {

                        }
                        Log.d(TAG, "destHost=" + destHost);
                    }
                });
                thread.start();
                try {
                    thread.join(1000);
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }
    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(www.google.com)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            InetAddress dest = InetAddress.getByName("www.google.com");
                            if (null == dest) {
                                dest = destHost;
                            }
                            if (null != dest) {
                                try {
                                    if (dest.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + dest.toString() + " reachable");
                                        isReachable = true;
                                    } else {
                                        Log.d(TAG, "destHost=" + dest.toString() + " not reachable");
                                    }
                                    destHost = dest;
                                } catch (IOException e) {

                                }
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(kkkon.sakura.ne.jp)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            InetAddress dest = InetAddress.getByName("kkkon.sakura.ne.jp");
                            if (null == dest) {
                                dest = destHost;
                            }
                            if (null != dest) {
                                try {
                                    if (dest.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + dest.toString() + " reachable");
                                        isReachable = true;
                                    } else {
                                        Log.d(TAG, "destHost=" + dest.toString() + " not reachable");
                                    }
                                    destHost = dest;
                                } catch (IOException e) {

                                }
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    setContentView(layout);
}

From source file:com.inmobi.grill.driver.hive.TestRemoteHiveDriver.java

@Test
public void testMultiThreadClient() throws Exception {
    LOG.info("@@ Starting multi thread test");
    // Launch two threads
    createTestTable("test_multithreads");
    HiveConf thConf = new HiveConf(conf, TestRemoteHiveDriver.class);
    thConf.setLong(HiveDriver.GRILL_CONNECTION_EXPIRY_DELAY, 10000);
    final HiveDriver thrDriver = new HiveDriver();
    thrDriver.configure(thConf);// w  ww.  j  a  v a 2  s  .c  o  m
    QueryContext ctx = new QueryContext("USE " + TestRemoteHiveDriver.class.getSimpleName(), null, conf);
    thrDriver.execute(ctx);

    // Launch a select query
    final int QUERIES = 5;
    int launchedQueries = 0;
    final int THREADS = 5;
    final long POLL_DELAY = 500;
    List<Thread> thrs = new ArrayList<Thread>();
    final AtomicInteger errCount = new AtomicInteger();
    for (int q = 0; q < QUERIES; q++) {
        final QueryContext qctx;
        try {
            qctx = new QueryContext("SELECT * FROM test_multithreads", null, conf);
            thrDriver.executeAsync(qctx);
        } catch (GrillException e) {
            errCount.incrementAndGet();
            LOG.info(q + " executeAsync error: " + e.getCause());
            continue;
        }
        LOG.info("@@ Launched query: " + q + " " + qctx.getQueryHandle());
        launchedQueries++;
        // Launch many threads to poll for status
        final QueryHandle handle = qctx.getQueryHandle();

        for (int i = 0; i < THREADS; i++) {
            int thid = q * THREADS + i;
            Thread th = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 1000; i++) {
                        try {
                            thrDriver.updateStatus(qctx);
                            if (qctx.getDriverStatus().isFinished()) {
                                LOG.info("@@ " + handle.getHandleId() + " >> "
                                        + qctx.getDriverStatus().getState());
                                thrDriver.closeQuery(handle);
                                break;
                            }
                            Thread.sleep(POLL_DELAY);
                        } catch (GrillException e) {
                            LOG.error("Got Exception", e.getCause());
                            e.printStackTrace();
                            errCount.incrementAndGet();
                            break;
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            break;
                        }
                    }
                }
            });
            thrs.add(th);
            th.setName("Poller#" + (thid));
            th.start();
        }
    }

    for (Thread th : thrs) {
        try {
            th.join(10000);
        } catch (InterruptedException e) {
            LOG.warn("Not ended yet: " + th.getName());
        }
    }
    Assert.assertEquals(0, thrDriver.getHiveHandleSize());
    LOG.info("@@ Completed all pollers. Total thrift errors: " + errCount.get());
    assertEquals(launchedQueries, QUERIES);
    assertEquals(thrs.size(), QUERIES * THREADS);
    assertEquals(errCount.get(), 0);
}