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:nz.govt.natlib.ndha.manualdeposit.jobmanagement.JobQueueManagement.java

private void checkJobQueue() {
    LOG.debug("Start checkJobQueue");
    boolean itemsMoved = checkAndMoveJobs(jobQueueRunning) || checkAndMoveJobs(jobQueuePending)
            || checkAndMoveJobs(jobQueueFailed) || checkAndMoveJobs(jobQueueDeposited)
            || checkAndMoveJobs(jobQueueInPermanent) || checkAndMoveJobs(jobQueueAwaitingCleanup);
    while ((!jobQueuePending.isEmpty())
            && (jobQueueRunning.size() < theAppProperties.getApplicationData().getMaximumJobsRunning())) {
        UploadJob job;//from  w w w  . j a v a 2 s.c om
        // need to take either the first or last depending on whether the
        // queue is sorted Asc or Desc
        int jobNumber;
        if (personalSettings.isSortPendingAscending()) {
            jobNumber = 0;
        } else {
            jobNumber = jobQueuePending.size() - 1;
        }
        job = jobQueuePending.get(jobNumber);
        while (job.isCreatingCopy() && jobNumber >= 0 && jobNumber < jobQueuePending.size()) {
            if (personalSettings.isSortPendingAscending()) {
                jobNumber++;
            } else {
                jobNumber--;
            }
            if (jobNumber >= 0 && jobNumber < jobQueuePending.size()) {
                job = jobQueuePending.get(jobNumber);
            }
        }
        if (job.isCreatingCopy()) {
            break;
        }
        if (job.lock()) {
            jobQueuePending.remove(job);
            jobQueueRunning.add(job);
            itemsMoved = true;
            Thread t = new Thread(job);
            t.start();
            job.unlock();
        } else {
            LOG.debug("Couldn't lock job " + job.getJobDetail().get(0).getEntityName());
            try {
                Thread.sleep(100);
            } catch (Exception ex) {
            }
        }
    }
    if (itemsMoved) {
        refreshJobQueue();
    }
    if (theJobQueuePendingTable != null) {
        theJobQueuePendingTable.repaint();
    }
    if (theJobQueueRunningTable != null) {
        theJobQueueRunningTable.repaint();
    }
    if (theJobQueueFailedTable != null) {
        theJobQueueFailedTable.repaint();
    }
    if (theJobQueueDepositedTable != null) {
        theJobQueueDepositedTable.repaint();
    }
    if (theJobQueueInPermanentTable != null) {
        theJobQueueInPermanentTable.repaint();
    }
    final Action checkJobQueueAction = new AbstractAction() {
        private static final long serialVersionUID = 5562669711772031634L;

        public void actionPerformed(final ActionEvent e) {
            Timer t = (Timer) e.getSource();
            t.stop();
            checkJobQueue();
        }
    };
    new Timer(theAppProperties.getApplicationData().getJobQueueRefreshInterval(), checkJobQueueAction).start();
    LOG.debug("End checkJobQueue");
}

From source file:edu.wisc.commons.httpclient.CleanShutdownPoolingClientConnectionManager.java

@Override
public void shutdown() {
    if (shutdownComplete.get() || !this.shutdownLock.tryLock()) {
        //Already shutdown or shutdown in progress
        return;/* w  w w .j  ava2  s.  com*/
    }

    try {
        //Create Thread to call shutdown
        final Thread shutdownThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    logger.info("PoolingClientConnectionManager shutdown started");
                    CleanShutdownPoolingClientConnectionManager.super.shutdown();
                } finally {
                    shutdownComplete.set(true);
                    logger.info("PoolingClientConnectionManager shutdown complete");
                }
            }
        });
        shutdownThread.setName("PoolingClientConnectionManager Shutdown Monitor");
        shutdownThread.setDaemon(true);

        //start shutdown thread
        shutdownThread.start();

        //track initial shutdown start time and time spent by the shutdown thread waiting or blocked
        final long shutdownStart = System.nanoTime();
        long waitStart = shutdownStart;

        //Monitor the shutdown thread
        while (!shutdownComplete.get()) {
            final long now = System.nanoTime();
            final long shutdownTime = TimeUnit.NANOSECONDS.toMillis(now - shutdownStart);

            //if time spent shutting down is greater than kill time forcibly stop the shutdown thread
            if (shutdownTime > this.shutdownThreadKillTime) {
                final String stackTrace = getStackTrace(shutdownThread);
                logger.error("Shutdown thread " + shutdownThread.getName() + " has been stopping for "
                        + shutdownTime + "ms, killing it. THIS IS BAD. \n" + stackTrace);
                shutdownThread.stop();

                //break out of the monitoring loop
                break;
            }
            //if time spent shutting down is greater than max time immediately interrupt the thread
            else if (shutdownTime > this.shutdownThreadMaxTime) {
                logger.warn("Shutdown thread " + shutdownThread.getName() + " has been stopping for "
                        + shutdownTime + "ms, interrupting immediately");
                shutdownThread.interrupt();
            }
            //otherwise check the state of the thread
            else {
                //If the thread is blocked or waiting and has been for longer than the max wait time
                //interrupt the thread. If not in blocked or waiting state update the wait-start time
                final State state = shutdownThread.getState();
                switch (state) {
                case BLOCKED:
                case TIMED_WAITING:
                case WAITING: {
                    final long waitTime = TimeUnit.NANOSECONDS.toMillis(now - waitStart);
                    if (waitTime > shutdownThreadMaxWaitTime) {
                        logger.info("Shutdown thread " + shutdownThread.getName() + " has been waiting for "
                                + waitTime + "ms, interrupting");
                        shutdownThread.interrupt();
                    } else {
                        break;
                    }
                }

                default: {
                    waitStart = now;
                    break;
                }
                }
            }

            //Sleep between state checks, don't want to overload anything
            try {
                Thread.sleep(shutdownThreadPollRate);
            } catch (InterruptedException e) {
                //ignore
            }
        }
    } finally {
        this.shutdownLock.unlock();
    }
}

From source file:org.botlibre.sdk.activity.ChatActivity.java

public Thread microphoneThread(Thread thread) {
    //make sure its on if it didn't turn off by the user. if 'sleep' is called it will turn the mic off.
    if (MainActivity.listenInBackground && threadIsOn) {
        return thread;
    }/* ww  w .j  av  a 2s  .  co m*/
    //if the user clicked on the Mic while its ON it will turn off and turn the thread off as well.
    if (threadIsOn) {
        threadIsOn = false;
        active = false;
        try {
            thread.stop();
        } catch (Exception ignore) {
        }
        return thread;
    }
    //if the user clicked on the Mic while its off it will turn ON the thread.
    if (!threadIsOn) {
        threadIsOn = true;
        active = true;
        thread = new Thread() {
            @Override
            public void run() {
                Log.e("Thread", "RUNNING");
                while (active) {
                    Log.e("Thread", "ACTIVE");
                    if (!isRecording && isListening && (System.currentTimeMillis() - lastReply) > 5000) {
                        lastReply = System.currentTimeMillis();
                        debug("speech death restart");
                        restartListening();
                    }
                    try {
                        Thread.sleep(1500);
                    } catch (Exception exception) {
                    }
                }
            }
        };
        thread.start();
    }

    return thread;
}

From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java

/**
 * Deregister shutdown hook and execute it immediately
 *///from   w  w  w.  j ava 2s  .com
@SuppressWarnings("deprecation")
protected void removeShutdownHook(Thread shutdownHook) {
    final String displayString = "'" + shutdownHook + "' of type " + shutdownHook.getClass().getName();
    error("Removing shutdown hook: " + displayString);
    Runtime.getRuntime().removeShutdownHook(shutdownHook);

    if (executeShutdownHooks) { // Shutdown hooks should be executed

        info("Executing shutdown hook now: " + displayString);
        // Make sure it's from this web app instance
        shutdownHook.start(); // Run cleanup immediately

        if (shutdownHookWaitMs > 0) { // Wait for shutdown hook to finish
            try {
                shutdownHook.join(shutdownHookWaitMs); // Wait for thread to run
            } catch (InterruptedException e) {
                // Do nothing
            }
            if (shutdownHook.isAlive()) {
                warn(shutdownHook + "still running after " + shutdownHookWaitMs + " ms - Stopping!");
                shutdownHook.stop();
            }
        }
    }
}

From source file:JVMSimulator.java

void ExecuteNextInstruction() {

    int a, b, result, i, operand0, operand1, operand2, offset;
    float fa, fb, fresult;
    Float f;/*from   www  .  j  a  va2s  .  c o m*/

    int nextOpCode = methodAreaMemorySection.getAtAddress(pcRegister);

    switch (nextOpCode) {

    case OpCode.AALOAD:
        executeAaload();
        break;

    case OpCode.ALOAD_0:
        executeAload_n(0);
        break;

    case OpCode.ASTORE_0:
        executeAstore_n(0);
        break;

    case OpCode.BIPUSH:
        operand0 = methodAreaMemorySection.getAtAddress(pcRegister + 1);
        stackMemorySection.setAtAddress(optopRegister, operand0);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, Integer.toString(operand0));
        optopRegister += 4;
        pcRegister += 2;
        break;

    // The BREAKPOINT opcode will serve as a stop sign for a running simulation.
    case OpCode.BREAKPOINT:
        stopButton.disable();
        runButton.disable();
        stepButton.disable();
        resetButton.enable();
        if (runner != null) {
            // If runner is not null, then this is probably the thread that
            // we want to stop. Therefore, as soon as stop has been executed,
            // nothing else will happen. So we must set runner to null before
            // we call runner.stop(). Therefore I copy runner to temp, assign
            // null to runner, and call stop() on temp.
            Thread temp = runner;
            runner = null;
            temp.stop();
        }
        break;

    case OpCode.FCONST_0:
        stackMemorySection.setAtAddress(optopRegister, Float.floatToIntBits((float) 0));
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "0");
        optopRegister += 4;
        ++pcRegister;
        break;

    case OpCode.FCONST_2:
        stackMemorySection.setAtAddress(optopRegister, Float.floatToIntBits((float) 2));
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "2");
        optopRegister += 4;
        ++pcRegister;
        break;

    case OpCode.FLOAD_0:
        a = stackMemorySection.getAtAddress(varsRegister);
        stackMemorySection.setAtAddress(optopRegister, a);
        fa = Float.intBitsToFloat(a);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, Float.toString(fa));
        optopRegister += 4;
        ++pcRegister;
        break;

    case OpCode.FMUL:
        optopRegister -= 4;
        a = stackMemorySection.getAtAddress(optopRegister);
        fa = Float.intBitsToFloat(a);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "");
        optopRegister -= 4;
        b = stackMemorySection.getAtAddress(optopRegister);
        fb = Float.intBitsToFloat(b);
        fresult = fa * fb;
        result = Float.floatToIntBits(fresult);
        stackMemorySection.setAtAddress(optopRegister, result);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, Float.toString(fresult));
        optopRegister += 4;
        ++pcRegister;
        break;

    case OpCode.FSTORE_0:
        optopRegister -= 4;
        a = stackMemorySection.getAtAddress(optopRegister);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "");
        stackMemorySection.setAtAddress(varsRegister, a);
        fa = Float.intBitsToFloat(a);
        stackMemorySection.setLogicalValueAtAddress(varsRegister, Float.toString(fa));
        ++pcRegister;
        break;

    case OpCode.FSUB:
        optopRegister -= 4;
        a = stackMemorySection.getAtAddress(optopRegister);
        fa = Float.intBitsToFloat(a);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "");
        optopRegister -= 4;
        b = stackMemorySection.getAtAddress(optopRegister);
        fb = Float.intBitsToFloat(b);
        fresult = fb - fa;
        result = Float.floatToIntBits(fresult);
        stackMemorySection.setAtAddress(optopRegister, result);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, Float.toString(fresult));
        optopRegister += 4;
        ++pcRegister;
        break;

    case OpCode.GOTO:
        operand1 = methodAreaMemorySection.getAtAddress(pcRegister + 1);
        operand0 = methodAreaMemorySection.getAtAddress(pcRegister + 2);

        offset = (operand1 << 8) | (operand0 & 0xff);

        pcRegister += offset;
        break;

    case OpCode.IADD:
        optopRegister -= 4;
        a = stackMemorySection.getAtAddress(optopRegister);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "");
        optopRegister -= 4;
        b = stackMemorySection.getAtAddress(optopRegister);
        result = a + b;
        stackMemorySection.setAtAddress(optopRegister, result);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, Integer.toString(result));
        optopRegister += 4;
        ++pcRegister;
        break;

    case OpCode.IAND:
        optopRegister -= 4;
        a = stackMemorySection.getAtAddress(optopRegister);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "");
        optopRegister -= 4;
        b = stackMemorySection.getAtAddress(optopRegister);
        result = a & b;
        stackMemorySection.setAtAddress(optopRegister, result);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, Integer.toString(result));
        optopRegister += 4;
        ++pcRegister;
        break;

    case OpCode.IASTORE:
        executeIastore();
        break;

    case OpCode.ICONST_M1:
        stackMemorySection.setAtAddress(optopRegister, -1);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "-1");
        optopRegister += 4;
        ++pcRegister;
        break;

    case OpCode.ICONST_0:
        stackMemorySection.setAtAddress(optopRegister, 0);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "0");
        optopRegister += 4;
        ++pcRegister;
        break;

    case OpCode.ICONST_1:
        stackMemorySection.setAtAddress(optopRegister, 1);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "1");
        optopRegister += 4;
        ++pcRegister;
        break;

    case OpCode.ICONST_2:
        stackMemorySection.setAtAddress(optopRegister, 2);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "2");
        optopRegister += 4;
        ++pcRegister;
        break;

    case OpCode.ICONST_3:
        stackMemorySection.setAtAddress(optopRegister, 3);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "3");
        optopRegister += 4;
        ++pcRegister;
        break;

    case OpCode.ICONST_4:
        stackMemorySection.setAtAddress(optopRegister, 4);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "4");
        optopRegister += 4;
        ++pcRegister;
        break;

    case OpCode.ICONST_5:
        stackMemorySection.setAtAddress(optopRegister, 5);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "5");
        optopRegister += 4;
        ++pcRegister;
        break;

    case OpCode.IFNE:
        optopRegister -= 4;
        a = stackMemorySection.getAtAddress(optopRegister);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "");
        // If a != 0 jump, else go on
        if (a != 0) {
            operand1 = methodAreaMemorySection.getAtAddress(pcRegister + 1);
            operand0 = methodAreaMemorySection.getAtAddress(pcRegister + 2);
            offset = (operand1 << 8) | (operand0 & 0xff);
            pcRegister += offset;
        } else {
            pcRegister += 3;
        }
        break;

    case OpCode.IF_ICMPLT:
        optopRegister -= 4;
        a = stackMemorySection.getAtAddress(optopRegister);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "");
        optopRegister -= 4;
        b = stackMemorySection.getAtAddress(optopRegister);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "");
        // If b < a jump, else go on
        if (b < a) {
            operand1 = methodAreaMemorySection.getAtAddress(pcRegister + 1);
            operand0 = methodAreaMemorySection.getAtAddress(pcRegister + 2);
            offset = (operand1 << 8) | (operand0 & 0xff);
            pcRegister += offset;
        } else {
            pcRegister += 3;
        }
        break;

    case OpCode.IINC:
        operand0 = methodAreaMemorySection.getAtAddress(pcRegister + 1);
        operand1 = methodAreaMemorySection.getAtAddress(pcRegister + 2);
        a = stackMemorySection.getAtAddress(varsRegister + (operand0 * 4));
        a += operand1;
        stackMemorySection.setAtAddress(varsRegister + (operand0 * 4), a);
        stackMemorySection.setLogicalValueAtAddress(varsRegister + (operand0 * 4), Integer.toString(a));
        pcRegister += 3;
        break;

    case OpCode.ILOAD_0:
        a = stackMemorySection.getAtAddress(varsRegister);
        stackMemorySection.setAtAddress(optopRegister, a);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, Integer.toString(a));
        optopRegister += 4;
        ++pcRegister;
        break;

    case OpCode.ILOAD_1:
        a = stackMemorySection.getAtAddress(varsRegister + 4);
        stackMemorySection.setAtAddress(optopRegister, a);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, Integer.toString(a));
        optopRegister += 4;
        ++pcRegister;
        break;

    case OpCode.ILOAD_2:
        a = stackMemorySection.getAtAddress(varsRegister + 8);
        stackMemorySection.setAtAddress(optopRegister, a);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, Integer.toString(a));
        optopRegister += 4;
        ++pcRegister;
        break;

    case OpCode.ILOAD_3:
        a = stackMemorySection.getAtAddress(varsRegister + 12);
        stackMemorySection.setAtAddress(optopRegister, a);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, Integer.toString(a));
        optopRegister += 4;
        ++pcRegister;
        break;

    case OpCode.IMUL:
        optopRegister -= 4;
        a = stackMemorySection.getAtAddress(optopRegister);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "");
        optopRegister -= 4;
        b = stackMemorySection.getAtAddress(optopRegister);
        result = a * b;
        stackMemorySection.setAtAddress(optopRegister, result);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, Integer.toString(result));
        optopRegister += 4;
        ++pcRegister;
        break;

    case OpCode.INT2BYTE:
        a = stackMemorySection.getAtAddress(optopRegister - 4);
        a = (byte) a;
        stackMemorySection.setAtAddress(optopRegister - 4, a);
        stackMemorySection.setLogicalValueAtAddress(optopRegister - 4, Integer.toString(a));
        ++pcRegister;
        break;

    case OpCode.IOR:
        optopRegister -= 4;
        a = stackMemorySection.getAtAddress(optopRegister);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "");
        optopRegister -= 4;
        b = stackMemorySection.getAtAddress(optopRegister);
        result = a | b;
        stackMemorySection.setAtAddress(optopRegister, result);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, Integer.toString(result));
        optopRegister += 4;
        ++pcRegister;
        break;

    case OpCode.ISHL:
        optopRegister -= 4;
        a = stackMemorySection.getAtAddress(optopRegister);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "");
        optopRegister -= 4;
        b = stackMemorySection.getAtAddress(optopRegister);
        result = b << (a & 0x1f);
        stackMemorySection.setAtAddress(optopRegister, result);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, Integer.toString(result));
        optopRegister += 4;
        ++pcRegister;
        break;

    case OpCode.ISTORE_0:
        optopRegister -= 4;
        a = stackMemorySection.getAtAddress(optopRegister);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "");
        stackMemorySection.setAtAddress(varsRegister, a);
        stackMemorySection.setLogicalValueAtAddress(varsRegister, Integer.toString(a));
        ++pcRegister;
        break;

    case OpCode.ISTORE_1:
        optopRegister -= 4;
        a = stackMemorySection.getAtAddress(optopRegister);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "");
        stackMemorySection.setAtAddress(varsRegister + 4, a);
        stackMemorySection.setLogicalValueAtAddress(varsRegister + 4, Integer.toString(a));
        ++pcRegister;
        break;

    case OpCode.ISTORE_2:
        optopRegister -= 4;
        a = stackMemorySection.getAtAddress(optopRegister);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "");
        stackMemorySection.setAtAddress(varsRegister + 8, a);
        stackMemorySection.setLogicalValueAtAddress(varsRegister + 8, Integer.toString(a));
        ++pcRegister;
        break;

    case OpCode.ISTORE_3:
        optopRegister -= 4;
        a = stackMemorySection.getAtAddress(optopRegister);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "");
        stackMemorySection.setAtAddress(varsRegister + 12, a);
        stackMemorySection.setLogicalValueAtAddress(varsRegister + 12, Integer.toString(a));
        ++pcRegister;
        break;

    case OpCode.IXOR:
        optopRegister -= 4;
        a = stackMemorySection.getAtAddress(optopRegister);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, "");
        optopRegister -= 4;
        b = stackMemorySection.getAtAddress(optopRegister);
        result = a ^ b;
        stackMemorySection.setAtAddress(optopRegister, result);
        stackMemorySection.setLogicalValueAtAddress(optopRegister, Integer.toString(result));
        optopRegister += 4;
        ++pcRegister;
        break;

    case OpCode.MULTIANEWARRAY:
        executeMultianewarray();
        pcRegister += 4;
        break;
    }
}

From source file:com.gigaspaces.internal.utils.ClassLoaderCleaner.java

@SuppressWarnings("deprecation")
private static void clearReferencesThreads(ClassLoader classLoader) {
    Thread[] threads = getThreads();

    // Iterate over the set of threads
    for (Thread thread : threads) {
        if (thread != null) {
            ClassLoader ccl = thread.getContextClassLoader();
            if (ccl != null && ccl == classLoader) {
                // Don't warn about this thread
                if (thread == Thread.currentThread()) {
                    continue;
                }// www  .j  a  v a 2  s .  c  o  m

                // Skip threads that have already died
                if (!thread.isAlive()) {
                    continue;
                }

                // Don't warn about JVM controlled threads
                ThreadGroup tg = thread.getThreadGroup();
                if (tg != null && JVM_THREAD_GROUP_NAMES.contains(tg.getName())) {
                    continue;
                }

                // TimerThread is not normally visible
                if (thread.getClass().getName().equals("java.util.TimerThread")) {
                    clearReferencesStopTimerThread(thread);
                    continue;
                }

                if (logger.isLoggable(Level.FINE))
                    logger.fine("A thread named [" + thread.getName()
                            + "] started but has failed to stop it. This is very likely to create a memory leak.");

                // Don't try an stop the threads unless explicitly
                // configured to do so
                if (!clearReferencesStopThreads) {
                    continue;
                }

                // If the thread has been started via an executor, try
                // shutting down the executor
                try {
                    Field targetField = thread.getClass().getDeclaredField("target");
                    targetField.setAccessible(true);
                    Object target = targetField.get(thread);

                    if (target != null && target.getClass().getCanonicalName()
                            .equals("java.util.concurrent.ThreadPoolExecutor.Worker")) {
                        Field executorField = target.getClass().getDeclaredField("this$0");
                        executorField.setAccessible(true);
                        Object executor = executorField.get(target);
                        if (executor instanceof ThreadPoolExecutor) {
                            ((ThreadPoolExecutor) executor).shutdownNow();
                        }
                    }
                } catch (Exception e) {
                    logger.log(Level.WARNING, "Failed to terminate thread named [" + thread.getName() + "]", e);
                }

                // This method is deprecated and for good reason. This is
                // very risky code but is the only option at this point.
                // A *very* good reason for apps to do this clean-up
                // themselves.
                thread.stop();
            }
        }
    }
}

From source file:mServer.search.MserverSearch.java

@SuppressWarnings("deprecation")
public boolean filmeSuchen(MserverSearchTask aktSearchTask) {
    boolean ret = true;
    try {/*from ww w .  j ava  2 s.c  om*/
        // ===========================================
        // den nchsten Suchlauf starten
        MserverLog.systemMeldung("");
        MserverLog.systemMeldung("-----------------------------------");
        MserverLog.systemMeldung("Filmsuche starten");
        crawler = new Crawler();

        // was und wie
        CrawlerConfig.senderLoadHow = aktSearchTask.loadHow();
        CrawlerConfig.updateFilmliste = aktSearchTask.updateFilmliste();
        CrawlerConfig.nurSenderLaden = arrLesen(aktSearchTask.arr[MserverSearchTask.SUCHEN_SENDER_NR].trim());
        CrawlerConfig.orgFilmlisteErstellen = aktSearchTask.orgListeAnlegen();
        CrawlerConfig.orgFilmliste = MserverDaten.system[MserverKonstanten.SYSTEM_FILMLISTE_ORG_NR];

        // live-steams
        CrawlerConfig.importLive = MserverDaten.system[MserverKonstanten.SYSTEM_IMPORT_LIVE_NR];

        // und noch evtl. ein paar Imports von Filmlisten anderer Server
        CrawlerConfig.importUrl_1__anhaengen = MserverDaten.system[MserverKonstanten.SYSTEM_IMPORT_URL_1_NR];
        CrawlerConfig.importUrl_2__anhaengen = MserverDaten.system[MserverKonstanten.SYSTEM_IMPORT_URL_2_NR];

        // fr die alte Filmliste
        CrawlerConfig.importOld = MserverDaten.system[MserverKonstanten.SYSTEM_IMPORT_OLD_NR];
        CrawlerConfig.importAkt = MserverDatumZeit
                .getNameAkt(MserverDaten.system[MserverKonstanten.SYSTEM_IMPORT_AKT_NR]);

        // Rest
        Config.setUserAgent(MserverDaten.getUserAgent());
        CrawlerConfig.proxyUrl = MserverDaten.system[MserverKonstanten.SYSTEM_PROXY_URL_NR];
        CrawlerConfig.proxyPort = MserverDaten.getProxyPort();
        Config.debug = MserverDaten.debug;

        Log.setLogfile(MserverDaten.getLogDatei(MserverKonstanten.LOG_FILE_NAME_MSEARCH));

        Thread t = new Thread(crawler);
        t.setName("Crawler");
        t.start();
        MserverLog.systemMeldung("Filme suchen gestartet");
        // ===========================================
        // warten auf das Ende
        //int warten = aktSearchTask.allesLaden() == true ? MvSKonstanten.WARTEZEIT_ALLES_LADEN : MvSKonstanten.WARTEZEIT_UPDATE_LADEN;
        int warten = aktSearchTask.getWaitTime()/*Minuten*/;
        MserverLog.systemMeldung("Max Laufzeit[Min]: " + warten);
        MserverLog.systemMeldung("-----------------------------------");

        TimeUnit.MINUTES.timedJoin(t, warten);

        // ===========================================
        // erst mal schauen ob noch was luft
        if (t != null) {
            if (t.isAlive()) {
                MserverLog.fehlerMeldung(915147623, MserverSearch.class.getName(),
                        "Der letzte Suchlauf luft noch");
                if (crawler != null) {
                    MserverLog.systemMeldung("");
                    MserverLog.systemMeldung("");
                    MserverLog.systemMeldung("================================");
                    MserverLog.systemMeldung("================================");
                    MserverLog.systemMeldung("und wird jetzt gestoppt");
                    MserverLog.systemMeldung(
                            "Zeit: " + FastDateFormat.getInstance("dd.MM.yyyy HH:mm:ss").format(new Date()));
                    MserverLog.systemMeldung("================================");
                    MserverLog.systemMeldung("================================");
                    MserverLog.systemMeldung("");
                    //und jetzt STOPPEN!!!!!!!!
                    crawler.stop();
                }

                int w;
                if (loadLongMax())
                    w = 30; // 30 Minuten bei langen Lufen
                else
                    w = 20;// 20 Minuten warten, das Erstellen/Komprimieren der Liste dauert
                TimeUnit.MINUTES.timedJoin(t, w);

                if (t.isAlive()) {
                    MserverLog.systemMeldung("");
                    MserverLog.systemMeldung("");
                    MserverLog.systemMeldung("================================");
                    MserverLog.systemMeldung("================================");
                    MserverLog.systemMeldung("und noch gekillt");
                    MserverLog.systemMeldung(
                            "Zeit: " + FastDateFormat.getInstance("dd.MM.yyyy HH:mm:ss").format(new Date()));
                    MserverLog.systemMeldung("================================");
                    MserverLog.systemMeldung("================================");
                    MserverLog.systemMeldung("");
                    ret = false;
                }
                //jetzt ist Schicht im Schacht
                t.stop();
            }
        }
    } catch (Exception ex) {
        MserverLog.fehlerMeldung(636987308, MserverSearch.class.getName(), "filmeSuchen", ex);
    }
    int l = crawler.getListeFilme().size();
    MserverLog.systemMeldung("");
    MserverLog.systemMeldung("");
    MserverLog.systemMeldung("================================");
    MserverLog.systemMeldung("Filmliste Anzahl Filme: " + l);
    if (l < 10_000) {
        //dann hat was nicht gepasst
        MserverLog.systemMeldung("   Fehler!!");
        MserverLog.systemMeldung("================================");
        ret = false;
    } else {
        MserverLog.systemMeldung("   dann ist alles OK");
        MserverLog.systemMeldung("================================");

    }
    MserverLog.systemMeldung("filmeSuchen beendet");
    crawler = null;
    return ret;
}

From source file:gov.noaa.pfel.erddap.util.EDStatic.java

/** This interrupts the thread and waits up to maxSeconds for it to finish.
 * If it still isn't finished, it is stopped.
 * //from w  ww  .j a  va 2 s . com
 */
public static void stopThread(Thread thread, int maxSeconds) {
    try {
        if (thread == null)
            return;
        String name = thread.getName();
        if (verbose)
            String2.log("stopThread(" + name + ")...");
        if (!thread.isAlive()) {
            if (verbose)
                String2.log("thread=" + name + " was already not alive.");
            return;
        }
        thread.interrupt();
        int waitSeconds = 0;
        while (thread.isAlive() && waitSeconds < maxSeconds) {
            waitSeconds += 2;
            Math2.sleep(2000);
        }
        if (thread.isAlive()) {
            if (verbose)
                String2.log("!!!Stopping thread=" + name + " after " + waitSeconds + " s");
            thread.stop();
        } else {
            if (verbose)
                String2.log("thread=" + name + " noticed interrupt in " + waitSeconds + " s");
        }
    } catch (Throwable t) {
        String2.log(MustBe.throwableToString(t));
    }
}

From source file:gov.noaa.pfel.erddap.util.EDStatic.java

/** This interrupts/kill all of the thredds in runningThreads. 
 *  Erddap.destroy calls this when tomcat is stopped.
 *///from   w  ww.j  a  v a  2s.  co  m
public static void destroy() {
    long time = System.currentTimeMillis();
    try {
        String names[] = String2.toStringArray(runningThreads.keySet().toArray());
        String2.log("\nEDStatic.destroy will try to interrupt nThreads=" + names.length + "\n  threadNames="
                + String2.toCSSVString(names));

        //shutdown Cassandra clusters/sessions
        EDDTableFromCassandra.shutdown();

        //interrupt all of them
        for (int i = 0; i < names.length; i++) {
            try {
                Thread thread = (Thread) runningThreads.get(names[i]);
                if (thread != null && thread.isAlive())
                    thread.interrupt();
                else
                    runningThreads.remove(names[i]);
            } catch (Throwable t) {
                String2.log(MustBe.throwableToString(t));
            }
        }

        //wait for threads to finish
        int waitedSeconds = 0;
        int maxSeconds = 600; //10 minutes
        while (true) {
            boolean allDone = true;
            for (int i = 0; i < names.length; i++) {
                try {
                    if (names[i] == null)
                        continue; //it has already stopped
                    Thread thread = (Thread) runningThreads.get(names[i]);
                    if (thread != null && thread.isAlive()) {
                        allDone = false;
                        if (waitedSeconds > maxSeconds) {
                            String2.log("  " + names[i] + " thread is being stop()ped!!!");
                            thread.stop();
                            runningThreads.remove(names[i]);
                            names[i] = null;
                        }
                    } else {
                        String2.log("  " + names[i] + " thread recognized the interrupt in " + waitedSeconds
                                + " s");
                        runningThreads.remove(names[i]);
                        names[i] = null;
                    }
                } catch (Throwable t) {
                    String2.log(MustBe.throwableToString(t));
                    allDone = false;
                }
            }
            if (allDone) {
                String2.log("EDStatic.destroy successfully interrupted all threads in " + waitedSeconds + " s");
                break;
            }
            if (waitedSeconds > maxSeconds) {
                String2.log("!!! EDStatic.destroy is done, but it had to stop() some threads.");
                break;
            }
            Math2.sleep(2000);
            waitedSeconds += 2;
        }

        //finally
        if (useLuceneSearchEngine)
            String2.log("stopping lucene...");

        try {
            if (luceneIndexSearcher != null)
                luceneIndexSearcher.close();
        } catch (Throwable t) {
        }
        luceneIndexSearcher = null;

        try {
            if (luceneIndexReader != null)
                luceneIndexReader.close();
        } catch (Throwable t) {
        }
        luceneIndexReader = null;
        luceneDatasetIDFieldCache = null;

        try {
            if (luceneIndexWriter != null)
                //indices will be thrown away, so don't make pending changes
                luceneIndexWriter.close(false);
        } catch (Throwable t) {
        }
        luceneIndexWriter = null;

    } catch (Throwable t) {
        String2.log(MustBe.throwableToString(t));
    }
}

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

@SuppressWarnings({ "unchecked", "deprecation" })
protected void initWebRtc(final WebRtcConfigurer webRtcConfigurer, final WebRtcChannel channel,
        final WebRtcMode mode, final WebRtcCandidateType candidateType, boolean useDataChannels)
        throws InterruptedException {
    // ICE candidates
    Thread t1 = new Thread() {
        @Override//from   w  w w  .  ja  va 2s .  c  om
        public void run() {
            JsonParser parser = new JsonParser();
            int numCandidate = 0;
            while (true) {
                try {
                    ArrayList<Object> iceCandidates = (ArrayList<Object>) browser
                            .executeScript("return iceCandidates;");

                    for (int i = numCandidate; i < iceCandidates.size(); i++) {
                        JsonObject jsonCandidate = (JsonObject) parser.parse(iceCandidates.get(i).toString());
                        IceCandidate candidate = new IceCandidate(jsonCandidate.get("candidate").getAsString(),
                                jsonCandidate.get("sdpMid").getAsString(),
                                jsonCandidate.get("sdpMLineIndex").getAsInt());
                        // log.debug("Adding candidate {}: {}", i, jsonCandidate);
                        webRtcConfigurer.addIceCandidate(candidate);
                        numCandidate++;
                    }

                    // Poll 300 ms
                    Thread.sleep(300);

                } catch (Throwable e) {
                    log.debug("Exiting gather candidates thread");
                    break;
                }
            }
        }
    };
    t1.start();

    // Append WebRTC mode (send/receive and audio/video) to identify test
    addTestName(KurentoTest.getTestClassName() + "." + KurentoTest.getTestMethodName());
    appendStringToTitle(mode.toString());
    appendStringToTitle(channel.toString());

    // Setting custom audio stream (if necessary)
    String audio = browser.getAudio();
    if (audio != null) {
        browser.executeScript("setCustomAudio('" + audio + "');");
    }

    // Create peerConnection for using dataChannels (if necessary)
    if (useDataChannels) {
        browser.executeScript("useDataChannels()");
    }

    // Setting IceServer (if necessary)
    String iceServerJsFunction = candidateType.getJsFunction();
    log.debug("Setting IceServer: {}", iceServerJsFunction);
    if (iceServerJsFunction != null) {
        browser.executeScript(iceServerJsFunction);
    }

    // Setting MediaConstraints (if necessary)
    String channelJsFunction = channel.getJsFunction();
    if (channelJsFunction != null) {
        browser.executeScript(channelJsFunction);
    }

    // Execute JavaScript kurentoUtils.WebRtcPeer
    browser.executeScript(mode.getJsFunction());

    // SDP offer/answer
    final CountDownLatch latch = new CountDownLatch(1);
    Thread t2 = new Thread() {
        @Override
        public void run() {
            // Wait to valid sdpOffer
            String sdpOffer = (String) browser.executeScriptAndWaitOutput("return sdpOffer;");

            log.debug("SDP offer: {}", sdpOffer);
            String sdpAnswer = webRtcConfigurer.processOffer(sdpOffer);
            log.debug("SDP answer: {}", sdpAnswer);

            // Encoding in Base64 to avoid parsing errors in JavaScript
            sdpAnswer = new String(Base64.encodeBase64(sdpAnswer.getBytes()));

            // Process sdpAnswer
            browser.executeScript("processSdpAnswer('" + sdpAnswer + "');");

            latch.countDown();
        }
    };
    t2.start();

    if (!latch.await(browser.getTimeout(), TimeUnit.SECONDS)) {
        t1.interrupt();
        t1.stop();
        t2.interrupt();
        t2.stop();
        throw new KurentoException("ICE negotiation not finished in " + browser.getTimeout() + " seconds");
    }
}