Example usage for java.lang Thread stop

List of usage examples for java.lang Thread stop

Introduction

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

Prototype

@Deprecated(since = "1.2")
public final void stop() 

Source Link

Document

Forces the thread to stop executing.

Usage

From source file:org.openmrs.util.OpenmrsClassLoader.java

public static void onShutdown() {

    //Since we are shutting down, stop all threads that reference the openmrs class loader.
    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
    Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
    for (Thread thread : threadArray) {

        ClassLoader classLoader = thread.getContextClassLoader();

        //Threads like Finalizer, Reference Handler, etc have null class loader reference.
        if (classLoader == null) {
            continue;
        }/*from w  w  w  . java2 s  .c o m*/

        if (classLoader instanceof OpenmrsClassLoader) {
            try {
                //Set to WebappClassLoader just in case stopping fails.
                thread.setContextClassLoader(classLoader.getParent());

                //Stopping the current thread will halt all current cleanup.
                //So do not ever ever even attempt stopping it. :)
                if (thread == Thread.currentThread()) {
                    continue;
                }

                log.info("onShutdown Stopping thread: " + thread.getName());
                thread.stop();
            } catch (Exception ex) {
                log.error(ex.getMessage(), ex);
            }
        }
    }

    clearReferences();
}

From source file:br.com.uol.runas.classloader.ClassLoaderGC.java

@SuppressWarnings({ "unchecked", "deprecation" })
private void releaseFromShutdownHooks(WeakReference<ClassLoader> classLoader) {
    final Map<Thread, Thread> hooks = (Map<Thread, Thread>) Reflections
            .getStaticFieldValue("java.lang.ApplicationShutdownHooks", "hooks");

    if (hooks != null) {
        final List<Thread> shutdownHooks = new ArrayList<>(hooks.keySet());

        for (Thread shutdownHook : shutdownHooks) {
            if (Objects.equals(classLoader.get(), shutdownHook.getContextClassLoader())) {
                Runtime.getRuntime().removeShutdownHook(shutdownHook);
                shutdownHook.start();/*from w w  w . ja  v  a 2  s.  co m*/
                try {
                    shutdownHook.join(500);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    shutdownHook.stop();
                }
                shutdownHook.setContextClassLoader(null);
            }
        }
    }
}

From source file:org.kurento.test.client.TestClient.java

@SuppressWarnings("deprecation")
public long getLatency() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final long[] out = new long[1];
    Thread t = new Thread() {
        public void run() {
            Object latency = browserClient.executeScript("return kurentoTest.getLatency();");
            if (latency != null) {
                out[0] = (Long) latency;
            } else {
                out[0] = Long.MIN_VALUE;
            }/* w  ww.  j  a  v a  2 s  .co  m*/
            latch.countDown();
        }
    };
    t.start();
    if (!latch.await(browserClient.getTimeout(), TimeUnit.SECONDS)) {
        t.interrupt();
        t.stop();
        throw new LatencyException("Timeout getting latency (" + browserClient.getTimeout() + "  seconds)");
    }
    return out[0];
}

From source file:com.datatorrent.lib.appdata.query.QueryManagerAsynchronousTest.java

@Test
public void stressTest() throws Exception {
    final int totalTuples = 100000;
    final int batchSize = 100;
    final double waitMillisProb = .01;

    AppDataWindowEndQueueManager<MockQuery, Void> queueManager = new AppDataWindowEndQueueManager<MockQuery, Void>();

    DefaultOutputPort<String> outputPort = new DefaultOutputPort<String>();
    CollectorTestSink<MockResult> sink = new CollectorTestSink<MockResult>();
    TestUtils.setSink(outputPort, sink);

    MessageSerializerFactory msf = new MessageSerializerFactory(new ResultFormatter());

    QueryManagerAsynchronous<MockQuery, Void, MutableLong, MockResult> queryManagerAsynch = new QueryManagerAsynchronous<>(
            outputPort, queueManager, new NOPQueryExecutor(waitMillisProb), msf, Thread.currentThread());

    Thread producerThread = new Thread(
            new ProducerThread(queueManager, totalTuples, batchSize, waitMillisProb));
    producerThread.start();//  www .j  a  v a2 s.  c  o  m
    producerThread.setName("Producer Thread");

    long startTime = System.currentTimeMillis();

    queryManagerAsynch.setup(null);

    int numWindows = 0;

    for (; sink.collectedTuples.size() < totalTuples
            && ((System.currentTimeMillis() - startTime) < 60000); numWindows++) {
        queryManagerAsynch.beginWindow(numWindows);
        Thread.sleep(100);
        queryManagerAsynch.endWindow();
    }

    producerThread.stop();
    queryManagerAsynch.teardown();

    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        //Do Nothing
    }

    Assert.assertEquals(totalTuples, sink.collectedTuples.size());
}

From source file:org.kurento.test.client.KurentoTestClient.java

@SuppressWarnings("deprecation")
public void initWebRtc(final WebRtcEndpoint webRtcEndpoint, final WebRtcChannel channel, final WebRtcMode mode)
        throws InterruptedException {

    webRtcEndpoint.addOnIceCandidateListener(new EventListener<OnIceCandidateEvent>() {
        @Override//from ww  w .ja v a 2s .  c  om
        public void onEvent(OnIceCandidateEvent event) {
            browserClient
                    .executeScript("addIceCandidate('" + JsonUtils.toJsonObject(event.getCandidate()) + "');");
        }
    });

    final CountDownLatch latch = new CountDownLatch(1);
    Thread t = new Thread() {
        public void run() {
            initWebRtcSdpProcessor(new SdpOfferProcessor() {
                @Override
                public String processSdpOffer(String sdpOffer) {
                    return webRtcEndpoint.processOffer(sdpOffer);
                }
            }, channel, mode);
            latch.countDown();
        }
    };
    t.start();
    if (!latch.await(browserClient.getTimeout(), TimeUnit.SECONDS)) {
        t.interrupt();
        t.stop();
    }
    webRtcEndpoint.gatherCandidates();
}

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  .ja  v a 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:org.powertac.visualizer.services.VisualizerServiceTournament.java

@PreDestroy
private void cleanUp() throws Exception {
    System.out.print("\nCleaning up VisualizerServiceTournament (8) : ");

    // Shutdown the proxy if needed
    if (proxy != null) {
        proxy.shutDown();/*from   w ww.  j a v a  2  s.  co m*/
    }
    System.out.print("1 ");

    // Kill the tick timer
    // I have no idea why this loop is needed
    while (tickTimer == null) {
        try {
            Thread.sleep(100);
        } catch (Exception ignored) {
        }
    }
    System.out.print("2 ");

    tickTimer.cancel();
    tickTimer.purge();
    tickTimer = null;
    System.out.print("3 ");

    if (stateTask != null) {
        stateTask.cancel();
    }
    System.out.print("4 ");

    // Kill the message pump
    try {
        messageFeeder.interrupt();
        messageFeeder.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.print("5 ");

    // Kill the state machine from within
    eventQueue.clear();
    putEvent(Event.quit);
    while (runningStates) {
        try {
            Thread.sleep(100);
        } catch (Exception ignored) {
        }

        if (currentState == loginWait && stateRunner != null
                && stateRunner.getState() == Thread.State.TIMED_WAITING) {
            stateRunner.interrupt();
        }
    }
    System.out.print("6 ");

    try {
        stateRunner.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.print("7 ");

    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
    Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
    for (Thread t : threadArray) {
        if (t.getName().contains("Timer-") || t.getName().contains("ActiveMQ")) {
            synchronized (t) {
                t.stop();
            }
        }
    }

    System.out.println("8\n");
}

From source file:com.nextep.designer.sqlclient.ui.handlers.ProfileQueryHandler.java

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    IWorkbenchSite site = HandlerUtil.getActiveSite(event);
    ISelectionProvider provider = site.getSelectionProvider();
    final IGenerationConsole console = new GenerationConsole("SQL Profiling - " + new Date().toString(), true);
    ISelection sel = provider.getSelection();

    if (sel == null || sel.isEmpty())
        return null;

    if (sel instanceof ITextSelection) {
        ITextSelection textSel = (ITextSelection) sel;

        final String sql = textSel.getText().trim();
        if (sql.length() == 0) {
            return null;
        }//from  w  w  w . j  a va 2s .c o m
        final String[] sqls = sql.split(";"); //$NON-NLS-1$

        // Building profiler settings
        final IProfilerSettings settings = new ProfilerSettings();
        GUIWrapper wrapper = new GUIWrapper(new ProfilerSettingsGUI(settings), "Define profiling settings", 400,
                220);
        wrapper.invoke();
        console.start();
        final IConnection targetConn = DBGMUIHelper.getConnection(null);

        // Starting profiling
        Job profilingJob = new Job("Profiling SQL...") {

            @Override
            protected IStatus run(IProgressMonitor monitor) {
                console.log("Profiler started: " + settings.getThreadCount() + " thread(s)"
                        + ", ramp-up period " + (settings.getThreadCount() * settings.getThreadStepDuration())
                        + " seconds" + ", Fetching " + (settings.isFetching() ? "enabled" : "disabled")
                        + ", Random execution " + (settings.isRandomOrder() ? "enabled" : "disabled"));
                csvStats.clear();
                csvStats.add(
                        "time;threads count;Minimum time;Maximum time;Average Time;Total Time;Total Executions");

                final long startTime = new Date().getTime();
                long currentTime = new Date().getTime();
                long lastThreadTime = 0;
                List<SqlThread> threads = new ArrayList<SqlThread>();
                while (((currentTime - startTime) / 1000) < settings.getDuration() && !monitor.isCanceled()) {
                    printStatistics(threads, console);
                    if (threads.size() < settings.getThreadCount()) {
                        if ((currentTime - lastThreadTime) > (settings.getThreadStepDuration() * 1000)) {
                            SqlThread thread = new SqlThread(targetConn, settings.isFetching(),
                                    settings.isRandomOrder(), sqls);
                            threads.add(thread);
                            Thread t = new Thread(thread);
                            t.start();
                            lastThreadTime = new Date().getTime();
                        }
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        LOGGER.error("Interrupted profiling", e);
                        break;
                    }
                    currentTime = new Date().getTime();
                }
                printStatistics(threads, console);

                // Stopping everything
                for (SqlThread t : threads) {
                    t.stop();
                }
                console.log("Profiler stopped");
                console.log("Profiler CSV statistics : ");
                for (String s : csvStats) {
                    console.log(s);
                }

                return Status.OK_STATUS;
            }
        };

        profilingJob.schedule();
    }

    return null;
}

From source file:de.unisb.cs.st.javalanche.mutation.runtime.testDriver.MutationTestDriver.java

private void stopThreads(long[] preIds) {
    Set<Long> threadIds = getThreadIds(preIds);
    for (Long tid : threadIds) {
        Thread runningThread = ThreadUtilities.getThread(tid);
        if (runningThread != null) {
            logger.info("Stopping thread " + runningThread);
            runningThread.stop();
        }//from  w  w w . j  ava2  s  .  c  o m
    }
}

From source file:org.kurento.test.browser.WebPage.java

@SuppressWarnings("deprecation")
public long getLatency() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final long[] out = new long[1];
    Thread t = new Thread() {
        @Override//from ww w .  j  a  v a2 s  . co m
        public void run() {
            Object latency = browser.executeScript("return kurentoTest.getLatency();");
            if (latency != null) {
                out[0] = (Long) latency;
            } else {
                out[0] = Long.MIN_VALUE;
            }
            latch.countDown();
        }
    };
    t.start();
    if (!latch.await(browser.getTimeout(), TimeUnit.SECONDS)) {
        t.interrupt();
        t.stop();
        throw new LatencyException("Timeout getting latency (" + browser.getTimeout() + "  seconds)");
    }
    return out[0];
}