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.apparatus_templi.Coordinator.java

private static void stopDrivers() {
    Log.w(TAG, "Restarting all drivers");
    Log.d(TAG, "removing all event watchers");
    eventWatchers.clear();/* w w w  .  j a  v  a  2s.  c  o m*/

    for (String driverName : loadedDrivers.keySet()) {
        Driver d = loadedDrivers.get(driverName);
        Log.d(TAG, "terminating driver " + d.getName());
        d.terminate();

        // only wake sleeping drivers, not TERMINATED ones
        wakeDriver(d.getName(), false, false);
        // loadedDrivers.remove(driverName);
    }

    // Block for a few seconds to allow all drivers to finish their
    // termination procedure. Since the drivers may call methods in this
    // thread we need to do a non-blocking wait instead of using a call to
    // Thread.sleep()
    long sleepTime = System.currentTimeMillis() + (1000 * 5);
    while (sleepTime > System.currentTimeMillis()) {
    }

    int tryCount = 0;
    while (!driverThreads.isEmpty()) {
        for (Driver d : driverThreads.keySet()) {
            Thread t = driverThreads.get(d);
            if (t.getState() == Thread.State.TERMINATED) {
                Log.d(TAG, "driver " + d.getName() + " terminated");
                driverThreads.remove(d);
            } else {
                // we don't want to block forever waiting on a non-responsive driver thread
                if (tryCount == 20) {
                    Log.w(TAG, "driver " + d.getName() + " non-responsive, interrupting thread.");
                    t.interrupt();
                    // t.notifyAll();
                }

                // Something is seriously wrong if the driver has not stopped by now. We should
                // probably notify the user that the service is experiencing problems and should
                // be restarted
                if (tryCount == 30) {
                    Log.e(TAG, "driver " + d.getName() + " still non-responsive, force stopping");
                    t.stop();
                }

                Log.d(TAG, "waiting on driver " + d.getName() + " to terminate (state: "
                        + t.getState().toString() + ")");
                d.terminate();
                wakeDriver(d.getName(), false, false);
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        tryCount++;
    }
    scheduledWakeUps.clear();
    loadedDrivers.clear();

    assert driverThreads.isEmpty();
    assert loadedDrivers.isEmpty();
    Log.w(TAG, "all drivers stopped");
}

From source file:org.apache.sysml.debug.DMLDebugger.java

/**
 * Controls the communication between debugger CLI and DML runtime.  
 *//*from w ww .  j a v  a2s .c  om*/
@SuppressWarnings("deprecation")
public synchronized void runSystemMLDebugger() {
    debuggerUI.setOptions();
    debuggerUI.getDebuggerCLI();
    Thread runtime = new Thread(DMLRuntime);
    boolean isRuntimeInstruction = false;

    while (!quit) {
        try {
            //get debugger function from CLI
            getCommand();
            if (cmd != null) {
                isRuntimeInstruction = false;
                //check for help
                if (cmd.hasOption("h")) {
                    debuggerUI.getDebuggerCLI();
                }
                //check for exit
                else if (cmd.hasOption("q")) {
                    synchronized (DMLDebugger.class) {
                        quit = true;
                    }
                    runtime.stop();
                } else if (cmd.hasOption("r")) {
                    if (currEC != null) {
                        System.out.println(
                                "Runtime has already started. Try \"s\" to go to next line, or \"c\" to continue running your DML script.");
                    } else {
                        currEC = preEC;
                        runtime.start();
                        isRuntimeInstruction = true;
                    }
                } else if (cmd.hasOption("c")) {
                    if (currEC == null)
                        System.out.println(
                                "Runtime has not been started. Try \"r\" to start DML runtime execution.");
                    else if (!runtime.isAlive()) {
                        System.err.println("Invalid debug state.");
                        //System.out.println("Runtime terminated. Try \"-c\" to recompile followed by \"r\" to restart DML runtime execution.");
                    } else {
                        System.out.println("Resuming DML script execution ...");
                        preEC.getDebugState().setCommand(null);
                        runtime.resume();
                        isRuntimeInstruction = true;
                    }
                } else if (cmd.hasOption("si")) {
                    if (!runtime.isAlive()) {
                        currEC = preEC;
                        runtime.start();
                        isRuntimeInstruction = true;
                    }
                    preEC.getDebugState().setCommand("step_instruction");
                    runtime.resume();
                    isRuntimeInstruction = true;
                } else if (cmd.hasOption("s")) {
                    if (!runtime.isAlive()) {
                        currEC = preEC;
                        runtime.start();
                        isRuntimeInstruction = true;
                    }
                    preEC.getDebugState().setCommand("step_line");
                    runtime.resume();
                    isRuntimeInstruction = true;
                } else if (cmd.hasOption("b")) {
                    int lineNumber = dbFunctions.getValue(cmd.getOptionValues("b"), lines.length);
                    if (lineNumber > 0) {
                        if (DMLBreakpointManager.getBreakpoint(lineNumber) == null)
                            System.out.println("Sorry, a breakpoint cannot be inserted at line " + lineNumber
                                    + ". Please try a different line number.");
                        else {
                            if (DMLBreakpointManager.getBreakpoint(lineNumber)
                                    .getBPInstructionStatus() != BPINSTRUCTION_STATUS.INVISIBLE) {
                                System.out.format("Breakpoint at line %d already exists.\n", lineNumber);
                            } else {
                                dbprog.accessBreakpoint(lineNumber, 0, BPINSTRUCTION_STATUS.ENABLED);
                            }
                        }
                    }
                } else if (cmd.hasOption("d")) {
                    int lineNumber = dbFunctions.getValue(cmd.getOptionValues("d"), lines.length);
                    if (lineNumber > 0 && DMLBreakpointManager.getBreakpoint(lineNumber) != null
                            && DMLBreakpointManager.getBreakpoint(lineNumber)
                                    .getBPInstructionStatus() != BPINSTRUCTION_STATUS.INVISIBLE) {
                        dbprog.accessBreakpoint(lineNumber, 1, BPINSTRUCTION_STATUS.INVISIBLE);
                    } else {
                        System.out.println("Sorry, a breakpoint cannot be deleted at line " + lineNumber
                                + ". Please try a different line number.");
                    }

                } else if (cmd.hasOption("i")) {
                    String[] infoOptions = cmd.getOptionValues("i");
                    if (infoOptions == null || infoOptions.length == 0) {
                        System.err.println(
                                "The command \"info\" requires option. Try \"info break\" or \"info frame\".");
                    } else if (infoOptions[0].trim().equals("break")) {
                        dbFunctions.listBreakpoints(DMLBreakpointManager.getBreakpoints());
                    } else if (infoOptions[0].trim().equals("frame")) {
                        if (!runtime.isAlive())
                            System.err.println(
                                    "Runtime has not been started. Try \"r\" or \"s\" to start DML runtime execution.");
                        else
                            dbFunctions.printCallStack(currEC.getDebugState().getCurrentFrame(),
                                    currEC.getDebugState().getCallStack());
                    } else {
                        System.err.println(
                                "Invalid option for command \"info\".  Try \"info break\" or \"info frame\".");
                    }
                } else if (cmd.hasOption("p")) {
                    String[] pOptions = cmd.getOptionValues("p");
                    if (pOptions == null || pOptions.length != 1) {
                        System.err.println("Incorrect options for command \"print\"");
                    } else {
                        String varName = pOptions[0].trim();
                        if (runtime.isAlive()) {
                            if (varName.contains("[")) {
                                // matrix with index: can be cell or column or row
                                try {
                                    String variableNameWithoutIndices = varName.split("\\[")[0].trim();
                                    String indexString = (varName.split("\\[")[1].trim()).split("\\]")[0]
                                            .trim();
                                    String rowIndexStr = "";
                                    String colIndexStr = "";
                                    if (indexString.startsWith(",")) {

                                        colIndexStr = indexString.split(",")[1].trim();
                                    } else if (indexString.endsWith(",")) {
                                        rowIndexStr = indexString.split(",")[0].trim();
                                    } else {
                                        rowIndexStr = indexString.split(",")[0].trim();
                                        colIndexStr = indexString.split(",")[1].trim();
                                    }
                                    int rowIndex = -1;
                                    int colIndex = -1;
                                    if (!rowIndexStr.isEmpty()) {
                                        rowIndex = Integer.parseInt(rowIndexStr);
                                    }
                                    if (!colIndexStr.isEmpty()) {
                                        colIndex = Integer.parseInt(colIndexStr);
                                    }
                                    dbFunctions.print(currEC.getDebugState().getVariables(),
                                            variableNameWithoutIndices, "value", rowIndex, colIndex);
                                } catch (Exception indicesException) {
                                    System.err.println(
                                            "Incorrect format for \"p\". If you are trying to print matrix variable M, you can use M[1,] or M[,1] or M[1,1] (without spaces).");
                                }
                            } else {
                                // Print entire matrix
                                dbFunctions.print(currEC.getDebugState().getVariables(), varName, "value", -1,
                                        -1);
                            }
                        } else
                            System.err.println(
                                    "Runtime has not been started. Try \"r\" or \"s\" to start DML runtime execution.");
                    }
                } else if (cmd.hasOption("whatis")) {
                    String[] pOptions = cmd.getOptionValues("whatis");
                    if (pOptions == null || pOptions.length != 1) {
                        System.err.println("Incorrect options for command \"whatis\"");
                    } else {
                        String varName = pOptions[0].trim();
                        dbFunctions.print(currEC.getDebugState().getVariables(), varName, "metadata", -1, -1);
                    }
                } else if (cmd.hasOption("set")) {
                    String[] pOptions = cmd.getOptionValues("set");
                    if (pOptions == null || pOptions.length != 2) {
                        System.err.println("Incorrect options for command \"set\"");
                    } else {
                        try {
                            if (pOptions[0].contains("[")) {
                                String[] paramsToSetMatrix = new String[4];
                                paramsToSetMatrix[0] = pOptions[0].split("\\[")[0].trim();
                                String indexString = (pOptions[0].split("\\[")[1].trim()).split("\\]")[0]
                                        .trim();
                                paramsToSetMatrix[1] = indexString.split(",")[0].trim();
                                paramsToSetMatrix[2] = indexString.split(",")[1].trim();
                                paramsToSetMatrix[3] = pOptions[1].trim();
                                dbFunctions.setMatrixCell(currEC.getDebugState().getVariables(),
                                        paramsToSetMatrix);
                            } else {
                                dbFunctions.setScalarValue(currEC.getDebugState().getVariables(), pOptions);
                            }
                        } catch (Exception exception1) {
                            System.out.println(
                                    "Only scalar variable or a matrix cell available in current frame can be set in current version.");
                        }
                    }
                } else if (cmd.hasOption("l")) {

                    String[] pOptions = cmd.getOptionValues("l");
                    String[] argsForRange = new String[2];
                    int currentPC = 1;

                    if (runtime.isAlive()) {
                        currentPC = currEC.getDebugState().getPC().getLineNumber();
                    }

                    IntRange range = null;
                    if (pOptions == null) {
                        // Print first 10 lines
                        range = new IntRange(currentPC, Math.min(lines.length, currentPC + 10));
                    } else if (pOptions.length == 1 && pOptions[0].trim().toLowerCase().equals("all")) {
                        // Print entire program
                        range = new IntRange(1, lines.length);
                    } else if (pOptions.length == 2 && pOptions[0].trim().toLowerCase().equals("next")) {
                        int numLines = 10;
                        try {
                            numLines = Integer.parseInt(pOptions[1]);
                        } catch (Exception e1) {
                        }

                        argsForRange[0] = "" + currentPC;
                        argsForRange[1] = "" + Math.min(lines.length, numLines + currentPC);
                        range = dbFunctions.getRange(argsForRange, lines.length);

                    } else if (pOptions.length == 2 && pOptions[0].trim().toLowerCase().equals("prev")) {
                        int numLines = 10;
                        try {
                            numLines = Integer.parseInt(pOptions[1]);
                        } catch (Exception e1) {
                        }

                        argsForRange[0] = "" + Math.max(1, currentPC - numLines);
                        argsForRange[1] = "" + currentPC;
                        range = dbFunctions.getRange(argsForRange, lines.length);
                    }

                    if (range == null) {
                        System.err.println(
                                "Incorrect usage of command \"l\". Try \"l\" or \"l all\" or \"l next 5\" or \"l prev 5\".");
                    } else {
                        if (range.getMinimumInteger() > 0) {
                            dbFunctions.printLines(lines, range);
                        } else {
                            System.err.println(
                                    "Sorry no lines that can be printed. Try \"l\" or \"l all\" or \"l next 5\" or \"l prev 5\".");
                        }
                    }
                } else if (cmd.hasOption("li")) {

                    String[] pOptions = cmd.getOptionValues("li");
                    String[] argsForRange = new String[2];
                    int currentPC = 1;

                    if (runtime.isAlive()) {
                        currentPC = currEC.getDebugState().getPC().getLineNumber();
                    }

                    IntRange range = null;
                    if (pOptions == null) {
                        // Print first 10 lines
                        range = new IntRange(currentPC, Math.min(lines.length, currentPC + 10));
                    } else if (pOptions.length == 1 && pOptions[0].trim().toLowerCase().equals("all")) {
                        // Print entire program
                        range = new IntRange(1, lines.length);
                    } else if (pOptions.length == 2 && pOptions[0].trim().toLowerCase().equals("next")) {
                        int numLines = 10;
                        try {
                            numLines = Integer.parseInt(pOptions[1]);
                        } catch (Exception e1) {
                        }

                        argsForRange[0] = "" + currentPC;
                        argsForRange[1] = "" + Math.min(lines.length, numLines + currentPC);
                        range = dbFunctions.getRange(argsForRange, lines.length);

                    } else if (pOptions.length == 2 && pOptions[0].trim().toLowerCase().equals("prev")) {
                        int numLines = 10;
                        try {
                            numLines = Integer.parseInt(pOptions[1]);
                        } catch (Exception e1) {
                        }

                        argsForRange[0] = "" + Math.max(1, currentPC - numLines);
                        argsForRange[1] = "" + currentPC;
                        range = dbFunctions.getRange(argsForRange, lines.length);
                    }

                    if (range == null) {
                        System.err.println(
                                "Incorrect usage of command \"li\". Try \"li\" or \"li all\" or \"li next 5\" or \"li prev 5\".");
                    } else {
                        if (range.getMinimumInteger() > 0) {
                            dbFunctions.printInstructions(lines, dbprog.getDMLInstMap(), range, false);
                        } else {
                            System.err.println(
                                    "Sorry no lines that can be printed. Try \"li\" or \"li all\" or \"li next 5\" or \"li prev 5\".");
                        }
                    }
                } else if (cmd.hasOption("set_scalar")) {
                    if (!runtime.isAlive())
                        System.err.println(
                                "Runtime has not been started. Try \"r\" to start DML runtime execution.");
                    else
                        dbFunctions.setScalarValue(currEC.getDebugState().getVariables(),
                                cmd.getOptionValues("set_scalar"));
                } else if (cmd.hasOption("m")) {
                    String varname = dbFunctions.getValue(cmd.getOptionValues("m"));
                    if (runtime.isAlive())
                        dbFunctions.printMatrixVariable(currEC.getDebugState().getVariables(), varname);
                    else
                        System.err.println(
                                "Runtime has not been started. Try \"r\" to start DML runtime execution.");
                } else if (cmd.hasOption("x")) {
                    if (!runtime.isAlive())
                        System.err.println(
                                "Runtime has not been started. Try \"r\" to start DML runtime execution.");
                    else {
                        dbFunctions.printMatrixCell(currEC.getDebugState().getVariables(),
                                cmd.getOptionValues("x"));
                    }
                } else if (cmd.hasOption("set_cell")) {
                    if (!runtime.isAlive())
                        System.err.println(
                                "Runtime has not been started. Try \"r\" to start DML runtime execution.");
                    else {
                        dbFunctions.setMatrixCell(currEC.getDebugState().getVariables(),
                                cmd.getOptionValues("set_cell"));
                    }
                } else {
                    System.err.println("Undefined command. Try \"help\".");
                }
                //block until runtime suspends execution or terminates 
                //while(runtime.isAlive() && !currEC.getProgram().isStopped()) {
                wait(300); // To avoid race condition between submitting job and
                //System.out.println(">> Before while");
                while (isRuntimeInstruction && !currEC.getDebugState().canAcceptNextCommand()) {
                    if (quit) {
                        break;
                    } else {
                        wait(300); //wait
                    }
                }
            }
            wait(300);
        } catch (Exception e) {
            System.err.println("Error processing debugger command. Try \"help\".");
        }
    }
}

From source file:com.cloudbees.jenkins.support.timer.DeadlockTest.java

@Test
public void detectDeadlock() throws Exception {
    File[] files = new File(j.getInstance().getRootDir(), "/deadlocks").listFiles();
    int initialCount = files == null ? 0 : files.length;
    final Object object1 = new Object();
    final Object object2 = new Object();
    Thread t1 = new Thread(new Runnable() {
        public void run() {
            synchronized (object1) {
                sleep();//from w  w w .  j a v a2 s .com
                firstMethod();
            }
        }

        void firstMethod() {
            secondMethod(20);
        }

        void secondMethod(int x) {
            if (x > 0) {
                secondMethod(x - 1);
            } else {
                synchronized (object2) {
                }
            }
        }
    });

    Thread t2 = new Thread(new Runnable() {
        public void run() {
            synchronized (object2) {
                sleep();
                synchronized (object1) {
                }
            }
        }
    });

    t1.start();
    try {
        t2.start();
        try {

            Thread.sleep(1000 * 5); // Wait 5 seconds, then execute deadlock checker.

            // Force call deadlock checker
            DeadlockTrackChecker dtc = new DeadlockTrackChecker();
            dtc.doRun();

            // Reason for >= 1 is because depending on where the test unit is executed the deadlock detection thread could be

            // invoked twice.
            files = new File(j.getInstance().getRootDir(), "/deadlocks").listFiles();
            assertNotNull("There should be at least one deadlock file", files);
            assertThat("A deadlock was detected and a new deadlock file created", files.length,
                    greaterThan(initialCount));
            String text = FileUtils.readFileToString(files[initialCount]);
            assertThat(text, Matchers.containsString("secondMethod"));
            assertThat(text, Matchers.containsString("firstMethod"));
        } finally {
            t2.stop();
        }
    } finally {
        t1.stop();
    }
}

From source file:com.linkedin.harisekhon.CLI.java

public final void main2(String[] args) {
    log.trace("running CLI.main2()");
    setup();/*from   w  w w .j av  a2  s  .  c  o  m*/
    try {
        addOptions();
    } catch (IllegalArgumentException e) {
        usage(e);
    }
    try {
        parseArgs2(args);
        //            autoflush();
        // TODO: this will reduce TRACE level, check to only increase log level and never reduce it
        //            if(verbose > 2) {
        //                log.setLevel(Level.DEBUG);
        //            } else if(verbose > 1){
        //                log.setLevel(Level.INFO);
        //            }
        //            if(debug){
        //                log.setLevel(Level.DEBUG);
        //            }
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            e.printStackTrace();
        }
        usage(e.getMessage());
    }
    log.info(String.format("verbose level: %s", verbose));
    validateInt(timeout, "timeout", 0, timeout_max);
    log.info(String.format("setting timeout to %s secs", timeout));
    Thread t = new Thread(new Timeout(timeout));
    t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            if (e instanceof QuitException) {
                println(((QuitException) e).status + ": " + ((QuitException) e).message);
                System.exit(getStatusCode("UNKNOWN"));
            } else {
                // normal Thread.stop() at end of program raises exception with null
                if (e.getMessage() != null) {
                    println(e.getMessage());
                    System.exit(getStatusCode("UNKNOWN"));
                }
            }
        }
    });
    t.start();
    try {
        log.trace("running CLI.processArgs()");
        processArgs();
        log.trace("running CLI.run()");
        run();
        log.trace("running CLI.end()");
        end();
        log.trace("stopping timeout thread");
        t.stop();
    } catch (IllegalArgumentException e) {
        log.trace("caught exception in CLI.main2()");
        if (log.isDebugEnabled()) {
            e.printStackTrace();
            // not as nicely formatted - not printing anything right now??
            //                println(e.getStackTrace().toString());
        }
        usage(e.getMessage());
        // not thrown by try block, how is Control-C thrown?
        //        } catch (InterruptedException e){
        //            System.out.println("Caught control-c...");
        //            System.exit(getStatusCode("UNKNOWN"));
    }
}

From source file:ca.uviccscu.lp.server.main.ShutdownListener.java

@Deprecated
public void threadCleanup(File f) {
    while (!deleteFolder(f, false, 0, 0)) {
        l.error("Trying to stop more threads, list:");
        //List remaining threads
        ThreadGroup tg2 = Thread.currentThread().getThreadGroup();
        while (tg2.getParent() != null) {
            tg2 = tg2.getParent();/*from  ww  w  .  j av  a 2  s  .  c o m*/
        }
        //Object o = new Object();
        //o.notifyAll();
        Thread[] threads = new Thread[tg2.activeCount() + 1024];
        tg2.enumerate(threads, true);
        //VERY BAD WAY TO STOP THREAD BUT NO CHOICE - need to release the file locks
        for (int i = 0; i < threads.length; i++) {
            Thread th = threads[i];
            if (th != null) {
                l.trace("Have thread: " + i + " : " + th.getName());
                if (th != null && th != Thread.currentThread()
                        && (AEThread2.isOurThread(th) || isAzThread(th))) {
                    l.trace("Suspending " + th.getName());
                    try {
                        th.suspend();
                        l.trace("ok");
                    } catch (SecurityException e) {
                        l.trace("Stop vetoed by SM", e);
                    }

                }
            }
        }
        for (int i = 0; i < threads.length; i++) {
            Thread th = threads[i];
            if (th != null) {
                l.trace("Have thread: " + i + " : " + th.getName());
                if (th != null && th != Thread.currentThread()
                        && (AEThread2.isOurThread(th) || isAzThread(th))) {
                    l.trace("Stopping " + th.getName());
                    try {
                        th.stop();
                        l.trace("ok");
                    } catch (SecurityException e) {
                        l.trace("Stop vetoed by SM", e);
                    }

                }
            }
        }
    }
    System.gc();
}

From source file:com.ibm.bi.dml.debug.DMLDebugger.java

/**
 * Controls the communication between debugger CLI and DML runtime.  
 *///from w  w  w. j  a  va 2s  .  com
@SuppressWarnings("deprecation")
public synchronized void runSystemMLDebugger() {
    debuggerUI.setOptions();
    debuggerUI.getDebuggerCLI();
    Thread runtime = new Thread(DMLRuntime);
    boolean isRuntimeInstruction = false;

    while (!quit) {
        try {
            //get debugger function from CLI
            getCommand();
            if (cmd != null) {
                isRuntimeInstruction = false;
                //check for help
                if (cmd.hasOption("h")) {
                    debuggerUI.getDebuggerCLI();
                }
                //check for exit
                else if (cmd.hasOption("q")) {
                    synchronized (DMLDebugger.class) {
                        quit = true;
                    }
                    runtime.stop();
                } else if (cmd.hasOption("r")) {
                    if (currEC != null) {
                        System.out.println(
                                "Runtime has already started. Try \"s\" to go to next line, or \"c\" to continue running your DML script.");
                    } else {
                        currEC = preEC;
                        runtime.start();
                        isRuntimeInstruction = true;
                    }
                } else if (cmd.hasOption("c")) {
                    if (currEC == null)
                        System.out.println(
                                "Runtime has not been started. Try \"r\" to start DML runtime execution.");
                    else if (!runtime.isAlive()) {
                        System.err.println("Invalid debug state.");
                        //System.out.println("Runtime terminated. Try \"-c\" to recompile followed by \"r\" to restart DML runtime execution.");
                    } else {
                        System.out.println("Resuming DML script execution ...");
                        preEC.getDebugState().setCommand(null);
                        runtime.resume();
                        isRuntimeInstruction = true;
                    }
                } else if (cmd.hasOption("si")) {
                    if (!runtime.isAlive()) {
                        currEC = preEC;
                        runtime.start();
                        isRuntimeInstruction = true;
                        // System.out.println("Runtime must be started before single stepping can be enabled. Try \"r\" to start DML runtime execution.");
                    }
                    //else {
                    preEC.getDebugState().setCommand("step_instruction");
                    runtime.resume();
                    isRuntimeInstruction = true;
                    //}
                } else if (cmd.hasOption("s")) {
                    if (!runtime.isAlive()) {
                        currEC = preEC;
                        runtime.start();
                        isRuntimeInstruction = true;
                        //System.out.println("Runtime must be started before step over can be enabled. Try \"r\" to start DML runtime execution.");
                    }
                    //else {
                    preEC.getDebugState().setCommand("step_line");
                    runtime.resume();
                    isRuntimeInstruction = true;
                    //}
                }
                //                 else if (cmd.hasOption("step_return")) {
                //                    if (!runtime.isAlive()) {
                //                       System.out.println("Runtime must be started before step return can be enabled. Try \"r\" to start DML runtime execution.");
                //                    }
                //                    else {
                //                       String fname = dbFunctions.getValue(cmd.getOptionValues("step_return"));
                //                       dbprog.rtprog.setCommand("step return");
                //                       if (fname != null) {
                //                          dbprog.rtprog.setCommandArg(fname);
                //                       }
                //                       runtime.resume();
                //                       isRuntimeInstruction = true;
                //                    }
                //                 }
                else if (cmd.hasOption("b")) {
                    int lineNumber = dbFunctions.getValue(cmd.getOptionValues("b"), lines.length);
                    if (lineNumber > 0) {
                        if (DMLBreakpointManager.getBreakpoint(lineNumber) == null)
                            System.out.println("Sorry, a breakpoint cannot be inserted at line " + lineNumber
                                    + ". Please try a different line number.");
                        else {
                            if (DMLBreakpointManager.getBreakpoint(lineNumber)
                                    .getBPInstructionStatus() != BPINSTRUCTION_STATUS.INVISIBLE) {
                                System.out.format("Breakpoint at line %d already exists.\n", lineNumber);
                            } else {
                                dbprog.accessBreakpoint(lineNumber, 0, BPINSTRUCTION_STATUS.ENABLED);
                            }
                        }
                    }
                } else if (cmd.hasOption("d")) {
                    int lineNumber = dbFunctions.getValue(cmd.getOptionValues("d"), lines.length);
                    if (lineNumber > 0 && DMLBreakpointManager.getBreakpoint(lineNumber) != null
                            && DMLBreakpointManager.getBreakpoint(lineNumber)
                                    .getBPInstructionStatus() != BPINSTRUCTION_STATUS.INVISIBLE) {
                        dbprog.accessBreakpoint(lineNumber, 1, BPINSTRUCTION_STATUS.INVISIBLE);
                        //dbprog.accessBreakpoint(lineNumber, 1, BPINSTRUCTION_STATUS.DISABLED);
                    } else {
                        System.out.println("Sorry, a breakpoint cannot be deleted at line " + lineNumber
                                + ". Please try a different line number.");
                    }

                } else if (cmd.hasOption("i")) {
                    String[] infoOptions = cmd.getOptionValues("i");
                    if (infoOptions == null || infoOptions.length == 0) {
                        System.err.println(
                                "The command \"info\" requires option. Try \"info break\" or \"info frame\".");
                    } else if (infoOptions[0].trim().compareTo("break") == 0) {
                        dbFunctions.listBreakpoints(DMLBreakpointManager.getBreakpoints());
                    } else if (infoOptions[0].trim().compareTo("frame") == 0) {
                        if (!runtime.isAlive())
                            System.err.println(
                                    "Runtime has not been started. Try \"r\" or \"s\" to start DML runtime execution.");
                        else
                            dbFunctions.printCallStack(currEC.getDebugState().getCurrentFrame(),
                                    currEC.getDebugState().getCallStack());
                    } else {
                        System.err.println(
                                "Invalid option for command \"info\".  Try \"info break\" or \"info frame\".");
                    }
                } else if (cmd.hasOption("p")) {
                    String[] pOptions = cmd.getOptionValues("p");
                    if (pOptions == null || pOptions.length != 1) {
                        System.err.println("Incorrect options for command \"print\"");
                    } else {
                        String varName = pOptions[0].trim();
                        if (runtime.isAlive()) {
                            if (varName.contains("[")) {
                                // matrix with index: can be cell or column or row
                                try {
                                    //System.out.println("" + varName);
                                    String variableNameWithoutIndices = varName.split("\\[")[0].trim();
                                    //System.out.println("" + variableNameWithoutIndices);
                                    String indexString = (varName.split("\\[")[1].trim()).split("\\]")[0]
                                            .trim();
                                    //System.out.println(">>" + indexString + "<<");
                                    String rowIndexStr = "";
                                    String colIndexStr = "";
                                    if (indexString.startsWith(",")) {

                                        colIndexStr = indexString.split(",")[1].trim();
                                    } else if (indexString.endsWith(",")) {
                                        rowIndexStr = indexString.split(",")[0].trim();
                                    } else {
                                        rowIndexStr = indexString.split(",")[0].trim();
                                        colIndexStr = indexString.split(",")[1].trim();
                                    }
                                    int rowIndex = -1;
                                    int colIndex = -1;
                                    if (rowIndexStr.compareTo("") != 0) {
                                        rowIndex = Integer.parseInt(rowIndexStr);
                                    }
                                    if (colIndexStr.compareTo("") != 0) {
                                        colIndex = Integer.parseInt(colIndexStr);
                                    }
                                    //System.out.println("" + rowIndex + " " + colIndex);
                                    dbFunctions.print(currEC.getDebugState().getVariables(),
                                            variableNameWithoutIndices, "value", rowIndex, colIndex);
                                } catch (Exception indicesException) {
                                    System.err.println(
                                            "Incorrect fomat for \"p\". If you are trying to print matrix variable M, you can use M[1,] or M[,1] or M[1,1] (without spaces).");
                                }
                            } else {
                                // Print entire matrix
                                dbFunctions.print(currEC.getDebugState().getVariables(), varName, "value", -1,
                                        -1);
                            }
                        } else
                            System.err.println(
                                    "Runtime has not been started. Try \"r\" or \"s\" to start DML runtime execution.");
                    }
                } else if (cmd.hasOption("whatis")) {
                    String[] pOptions = cmd.getOptionValues("whatis");
                    if (pOptions == null || pOptions.length != 1) {
                        System.err.println("Incorrect options for command \"whatis\"");
                    } else {
                        String varName = pOptions[0].trim();
                        dbFunctions.print(currEC.getDebugState().getVariables(), varName, "metadata", -1, -1);
                    }
                } else if (cmd.hasOption("set")) {
                    String[] pOptions = cmd.getOptionValues("set");
                    if (pOptions == null || pOptions.length != 2) {
                        System.err.println("Incorrect options for command \"set\"");
                    } else {
                        try {
                            if (pOptions[0].contains("[")) {
                                String[] paramsToSetMatrix = new String[4];
                                paramsToSetMatrix[0] = pOptions[0].split("\\[")[0].trim();
                                String indexString = (pOptions[0].split("\\[")[1].trim()).split("\\]")[0]
                                        .trim();
                                paramsToSetMatrix[1] = indexString.split(",")[0].trim();
                                paramsToSetMatrix[2] = indexString.split(",")[1].trim();
                                paramsToSetMatrix[3] = pOptions[1].trim();
                                dbFunctions.setMatrixCell(currEC.getDebugState().getVariables(),
                                        paramsToSetMatrix);
                            } else {
                                dbFunctions.setScalarValue(currEC.getDebugState().getVariables(), pOptions);
                            }
                        } catch (Exception exception1) {
                            System.out.println(
                                    "Only scalar variable or a matrix cell available in current frame can be set in current version.");
                        }
                    }
                } else if (cmd.hasOption("l")) {

                    String[] pOptions = cmd.getOptionValues("l");
                    String[] argsForRange = new String[2];
                    int currentPC = 1;

                    if (runtime.isAlive()) {
                        currentPC = currEC.getDebugState().getPC().getLineNumber();
                    }

                    IntRange range = null;
                    if (pOptions == null) {
                        // Print first 10 lines
                        range = new IntRange(currentPC, Math.min(lines.length, currentPC + 10));
                    } else if (pOptions.length == 1 && pOptions[0].trim().toLowerCase().compareTo("all") == 0) {
                        // Print entire program
                        range = new IntRange(1, lines.length);
                    } else if (pOptions.length == 2
                            && pOptions[0].trim().toLowerCase().compareTo("next") == 0) {
                        int numLines = 10;
                        try {
                            numLines = Integer.parseInt(pOptions[1]);
                        } catch (Exception e1) {
                        }

                        argsForRange[0] = "" + currentPC;
                        argsForRange[1] = "" + Math.min(lines.length, numLines + currentPC);
                        range = dbFunctions.getRange(argsForRange, lines.length);

                    } else if (pOptions.length == 2
                            && pOptions[0].trim().toLowerCase().compareTo("prev") == 0) {
                        int numLines = 10;
                        try {
                            numLines = Integer.parseInt(pOptions[1]);
                        } catch (Exception e1) {
                        }

                        argsForRange[0] = "" + Math.max(1, currentPC - numLines);
                        argsForRange[1] = "" + currentPC;
                        range = dbFunctions.getRange(argsForRange, lines.length);
                    }

                    if (range == null) {
                        System.err.println(
                                "Incorrect usage of command \"l\". Try \"l\" or \"l all\" or \"l next 5\" or \"l prev 5\".");
                    } else {
                        if (range.getMinimumInteger() > 0) {
                            dbFunctions.printLines(lines, range);
                        } else {
                            System.err.println(
                                    "Sorry no lines that can be printed. Try \"l\" or \"l all\" or \"l next 5\" or \"l prev 5\".");
                        }
                    }

                    // Old code:
                    // IntRange range = dbFunctions.getRange(cmd.getOptionValues("p"), lines.length);
                    //if (range.getMinimumInteger() > 0) {
                    //   dbFunctions.printLines(lines, range);
                    // }
                } else if (cmd.hasOption("li")) {

                    String[] pOptions = cmd.getOptionValues("li");
                    String[] argsForRange = new String[2];
                    int currentPC = 1;

                    if (runtime.isAlive()) {
                        currentPC = currEC.getDebugState().getPC().getLineNumber();
                    }

                    IntRange range = null;
                    if (pOptions == null) {
                        // Print first 10 lines
                        range = new IntRange(currentPC, Math.min(lines.length, currentPC + 10));
                    } else if (pOptions.length == 1 && pOptions[0].trim().toLowerCase().compareTo("all") == 0) {
                        // Print entire program
                        range = new IntRange(1, lines.length);
                    } else if (pOptions.length == 2
                            && pOptions[0].trim().toLowerCase().compareTo("next") == 0) {
                        int numLines = 10;
                        try {
                            numLines = Integer.parseInt(pOptions[1]);
                        } catch (Exception e1) {
                        }

                        argsForRange[0] = "" + currentPC;
                        argsForRange[1] = "" + Math.min(lines.length, numLines + currentPC);
                        range = dbFunctions.getRange(argsForRange, lines.length);

                    } else if (pOptions.length == 2
                            && pOptions[0].trim().toLowerCase().compareTo("prev") == 0) {
                        int numLines = 10;
                        try {
                            numLines = Integer.parseInt(pOptions[1]);
                        } catch (Exception e1) {
                        }

                        argsForRange[0] = "" + Math.max(1, currentPC - numLines);
                        argsForRange[1] = "" + currentPC;
                        range = dbFunctions.getRange(argsForRange, lines.length);
                    }

                    if (range == null) {
                        System.err.println(
                                "Incorrect usage of command \"li\". Try \"li\" or \"li all\" or \"li next 5\" or \"li prev 5\".");
                    } else {
                        if (range.getMinimumInteger() > 0) {
                            dbFunctions.printInstructions(lines, dbprog.getDMLInstMap(), range, false);
                        } else {
                            System.err.println(
                                    "Sorry no lines that can be printed. Try \"li\" or \"li all\" or \"li next 5\" or \"li prev 5\".");
                        }
                    }

                    // Old code:
                    // IntRange range = dbFunctions.getRange(cmd.getOptionValues("p"), lines.length);
                    //if (range.getMinimumInteger() > 0) {
                    //   dbFunctions.printLines(lines, range);
                    // }
                } else if (cmd.hasOption("set_scalar")) {
                    if (!runtime.isAlive())
                        System.err.println(
                                "Runtime has not been started. Try \"r\" to start DML runtime execution.");
                    else
                        dbFunctions.setScalarValue(currEC.getDebugState().getVariables(),
                                cmd.getOptionValues("set_scalar"));
                } else if (cmd.hasOption("m")) {
                    String varname = dbFunctions.getValue(cmd.getOptionValues("m"));
                    if (runtime.isAlive())
                        dbFunctions.printMatrixVariable(currEC.getDebugState().getVariables(), varname);
                    else
                        System.err.println(
                                "Runtime has not been started. Try \"r\" to start DML runtime execution.");
                } else if (cmd.hasOption("x")) {
                    if (!runtime.isAlive())
                        System.err.println(
                                "Runtime has not been started. Try \"r\" to start DML runtime execution.");
                    else {
                        dbFunctions.printMatrixCell(currEC.getDebugState().getVariables(),
                                cmd.getOptionValues("x"));
                    }
                } else if (cmd.hasOption("set_cell")) {
                    if (!runtime.isAlive())
                        System.err.println(
                                "Runtime has not been started. Try \"r\" to start DML runtime execution.");
                    else {
                        dbFunctions.setMatrixCell(currEC.getDebugState().getVariables(),
                                cmd.getOptionValues("set_cell"));
                    }
                } else {
                    System.err.println("Undefined command. Try \"help\".");
                }
                //block until runtime suspends execution or terminates 
                //while(runtime.isAlive() && !currEC.getProgram().isStopped()) {
                wait(300); // To avoid race condition between submitting job and
                //System.out.println(">> Before while");
                while (isRuntimeInstruction && !currEC.getDebugState().canAcceptNextCommand()) {
                    if (quit) {
                        break;
                    } else {
                        wait(300); //wait
                    }
                }
                //System.out.println(">> After while");
            }
            wait(300);
        } catch (Exception e) {
            System.err.println("Error processing debugger command. Try \"help\".");
        }
    }
}

From source file:com.rapid.server.RapidServletContextListener.java

@Override
public void contextDestroyed(ServletContextEvent event) {

    _logger.info("Shutting down...");

    // interrupt the page monitor if we have one
    if (_monitor != null)
        _monitor.interrupt();/*from   www  .  j  av  a  2 s. c om*/

    // get the servletContext
    ServletContext servletContext = event.getServletContext();

    // get all of the applications
    Applications applications = (Applications) servletContext.getAttribute("applications");
    // if we got some
    if (applications != null) {
        // loop the application ids
        for (String id : applications.getIds()) {
            // get the application
            Versions versions = applications.getVersions(id);
            // loop the versions of each app
            for (String version : versions.keySet()) {
                // get the application
                Application application = applications.get(id, version);
                // have it close any sensitive resources 
                application.close(servletContext);
            }
        }
    }

    // sleep for 2 seconds to allow any database connection cleanup to complete
    try {
        Thread.sleep(2000);
    } catch (Exception ex) {
    }

    // This manually deregisters JDBC drivers, which prevents Tomcat from complaining about memory leaks from this class
    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
        Driver driver = drivers.nextElement();
        try {
            DriverManager.deregisterDriver(driver);
            _logger.info(String.format("Deregistering jdbc driver: %s", driver));
        } catch (SQLException e) {
            _logger.error(String.format("Error deregistering driver %s", driver), e);
        }
    }

    // Thanks to http://stackoverflow.com/questions/11872316/tomcat-guice-jdbc-memory-leak
    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
    Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
    for (Thread t : threadArray) {
        if (t.getName().contains("Abandoned connection cleanup thread")) {
            synchronized (t) {
                try {
                    _logger.info("Forcing stop of Abandoned connection cleanup thread");
                    t.stop(); //don't complain, it works
                } catch (Exception ex) {
                    _logger.info("Error forcing stop of Abandoned connection cleanup thread", ex);
                }
            }
        }
    }

    // sleep for 1 second to allow any database connection cleanup to complete
    try {
        Thread.sleep(1000);
    } catch (Exception ex) {
    }

    // last log
    _logger.info("Logger shutdown");
    // shutdown logger
    if (_logger != null)
        LogManager.shutdown();

}

From source file:org.codelibs.fess.servlet.Tomcat6ConfigServlet.java

@SuppressWarnings("deprecation")
private void cleanupAllThreads() {
    final Thread[] threads = getThreads();
    final ClassLoader cl = this.getClass().getClassLoader();
    try {//from   w  w  w  .  j  a v  a 2 s.c om
        cl.getResource(null);
    } catch (final Exception e) {
    }

    final List<String> jvmThreadGroupList = new ArrayList<String>();
    jvmThreadGroupList.add("system");
    jvmThreadGroupList.add("RMI Runtime");

    // Iterate over the set of threads
    for (final Thread thread : threads) {
        if (thread != null) {
            final ClassLoader ccl = thread.getContextClassLoader();
            if (ccl != null && ccl.equals(cl)) {
                // Don't warn about this thread
                if (thread == Thread.currentThread()) {
                    continue;
                }

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

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

                if (logger.isInfoEnabled()) {
                    logger.info("Interrupting a thread [" + thread.getName() + "]...");
                }
                thread.interrupt();

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

                if (logger.isInfoEnabled()) {
                    logger.info("Stopping a thread [" + thread.getName() + "]...");
                }
                thread.stop();
            }
        }
    }

    Field threadLocalsField = null;
    Field inheritableThreadLocalsField = null;
    Field tableField = null;
    try {
        threadLocalsField = Thread.class.getDeclaredField("threadLocals");
        threadLocalsField.setAccessible(true);
        inheritableThreadLocalsField = Thread.class.getDeclaredField("inheritableThreadLocals");
        inheritableThreadLocalsField.setAccessible(true);
        // Make the underlying array of ThreadLoad.ThreadLocalMap.Entry objects
        // accessible
        final Class<?> tlmClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap");
        tableField = tlmClass.getDeclaredField("table");
        tableField.setAccessible(true);
    } catch (final Exception e) {
        // ignore
    }
    for (final Thread thread : threads) {
        if (thread != null) {

            Object threadLocalMap;
            try {
                // Clear the first map
                threadLocalMap = threadLocalsField.get(thread);
                clearThreadLocalMap(cl, threadLocalMap, tableField);
            } catch (final Exception e) {
                // ignore
            }
            try { // Clear the second map
                threadLocalMap = inheritableThreadLocalsField.get(thread);
                clearThreadLocalMap(cl, threadLocalMap, tableField);
            } catch (final Exception e) {
                // ignore
            }
        }
    }
}

From source file:com.farouk.projectapp.FirstGUI.java

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    final Thread th = new Thread() {
        @Override//from w  ww. ja  v a  2s. c o  m
        public void run() {
            SQLConnect.refreshAllData();
        }
    };
    jButton8.setVisible(true);
    th.start();
    jButton8.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            th.stop();
            jButton8.setVisible(false);
            return;
        }
    });
}

From source file:com.baidu.jprotobuf.mojo.PreCompileMojo.java

private void terminateThreads(ThreadGroup threadGroup) {
    long startTime = System.currentTimeMillis();
    Set<Thread> uncooperativeThreads = new HashSet<Thread>(); // these were not responsive to interruption
    for (Collection<Thread> threads = getActiveThreads(threadGroup); !threads
            .isEmpty(); threads = getActiveThreads(threadGroup), threads.removeAll(uncooperativeThreads)) {
        // Interrupt all threads we know about as of this instant (harmless if spuriously went dead (! isAlive())
        // or if something else interrupted it ( isInterrupted() ).
        for (Thread thread : threads) {
            getLog().debug("interrupting thread " + thread);
            thread.interrupt();/*from  www .  j  a  v  a 2s  .co m*/
        }
        // Now join with a timeout and call stop() (assuming flags are set right)
        for (Thread thread : threads) {
            if (!thread.isAlive()) {
                continue; // and, presumably it won't show up in getActiveThreads() next iteration
            }
            if (daemonThreadJoinTimeout <= 0) {
                joinThread(thread, 0); // waits until not alive; no timeout
                continue;
            }
            long timeout = daemonThreadJoinTimeout - (System.currentTimeMillis() - startTime);
            if (timeout > 0) {
                joinThread(thread, timeout);
            }
            if (!thread.isAlive()) {
                continue;
            }
            uncooperativeThreads.add(thread); // ensure we don't process again
            if (stopUnresponsiveDaemonThreads) {
                getLog().warn("thread " + thread + " will be Thread.stop()'ed");
                thread.stop();
            } else {
                getLog().warn("thread " + thread + " will linger despite being asked to die via interruption");
            }
        }
    }
    if (!uncooperativeThreads.isEmpty()) {
        getLog().warn("NOTE: " + uncooperativeThreads.size()
                + " thread(s) did not finish despite being asked to "
                + " via interruption. This is not a problem with exec:java, it is a problem with the running code."
                + " Although not serious, it should be remedied.");
    } else {
        int activeCount = threadGroup.activeCount();
        if (activeCount != 0) {
            // TODO this may be nothing; continue on anyway; perhaps don't even log in future
            Thread[] threadsArray = new Thread[1];
            threadGroup.enumerate(threadsArray);
            getLog().debug("strange; " + activeCount + " thread(s) still active in the group " + threadGroup
                    + " such as " + threadsArray[0]);
        }
    }
}