How to stop a running process in a GUI in Java?

Posted on 2013-11-10
Last Modified: 2013-11-14
I have a GUI in Java and I need to stop a process while it is running.

I tried to stop the process using the code below but it did not really stop the process instead it stopped showing the results in the GUI. When I do println I can still see that the process is running.

This is the code I have:

public class RunPerl {

    private static List<CheckDetail> checkDetails = null;
    final static List<CheckDetail> checkDetailsAll = new ArrayList<CheckDetail>();    
    static FileTree fileTree = new FileTree();
    //this is to stop all running checks
    private static List<CheckRunner> checkRunners = new ArrayList<CheckRunner>();
    private static Shell shell;
    private static Table table;
    private static String[] titles;
    private static Group groupResults;
    private static Display display;
    private static Composite compTB3_table_newThread;
    private static boolean exitLoop;
    //static Text txt;
    public static String[] getFileList(){
        String[] Filelist = null;
        return Filelist;

        public static void runMwcheck(String content, Map<Integer, String> checkNameMap, Composite compTB3_table, StringBuilder failedCheckList, boolean reRun) throws IOException {
            Set<String> results = null;
            //String content = Gui.getFileList();          
            //separate the text by new line characters
            //and assign them to an array
            String fileData[] = content.split("(" + System.getProperty("line.separator") + ")+");
            //get the list of checks from the checks list in TAB2
            //Map<Integer, TreeItem> checkListMap = new HashMap<Integer, TreeItem>();
            //Map<Integer, String> checkNameMap= new HashMap<Integer, String>();
            //checkNameMap = CheckListTree.getInstance().getCheckedStandards(checkListMap, checkNameMap);
            String tempDir = null;
            StringBuilder checkList = new StringBuilder();
            Iterator<Entry<Integer, String>> it_checkNameMap = checkNameMap.entrySet().iterator();
            // if this is to run only the failed checks, then you should not get the check list from the checks tab.
            //It will be passed from the toolbarlistener
            if (reRun){
            	checkList = failedCheckList;
            	// loop through the hashmap and create the checks list
	            while (it_checkNameMap.hasNext()) {
	                Entry<Integer, String> pairs_checkNameMap =;
	                checkList.append(" -guiCheck ").append(pairs_checkNameMap.getValue());
             //loop through each line (request) in the text box
            String perlCmd;
            String mtcheckCmd;
            String setMwcheckPathCmd;
            String sandboxLocation = null;
            String batchFileCmd = null;
            //FutureTask<CheckRunner> task = new FutureTask(myRunner);
            //ExecutorService checkExecutor = Executors.newFixedThreadPool(5);
           ExecutorService checkExecutor = Executors.newSingleThreadExecutor();
            HashMap<String, Future> futures = new HashMap<String,Future>(fileData.length);
            //int j = 0;
            for (int j = 0; j < fileData.length; j++){
                    String fileInfoLine = fileData[j];
                    String OS = System.getProperty("").toLowerCase();
                    fileInfoLine = fileInfoLine.replaceAll("\\r|\\n", "");
                    Pattern sandboxLocPattern = Pattern.compile("(?<=(-f|-d|-d -r|-c)).+?(?=(?:product))");
                    Matcher matchSandboxLoc = sandboxLocPattern.matcher(fileInfoLine);
                    if (matchSandboxLoc.find()){
                        sandboxLocation =;
                        fileInfoLine = fileInfoLine.replace(sandboxLocation," ");
                        sandboxLocation = sandboxLocation.replaceAll("-f|-d|-d -r|-c", "");
                    } else{
                        sandboxLocation = "";
                    if (OS.indexOf("win") >= 0){
                        tempDir = "C:/Temp/mtcheck";
                        batchFileCmd = "cmd.exe /C \\\\somepath\\bin\\mtcheckGui.bat" +" " + sandboxLocation + " " + fileInfoLine + " " + checkList ;
                        tempDir = "/tmp/mtcheck";
                        batchFileCmd = "/somepath/bin/" +" " + sandboxLocation + " " + fileInfoLine + " " + checkList ;
                    perlCmd = batchFileCmd;
                    CheckRunner myRunner = new CheckRunner();
                    //this is to stop all running checks
                    futures.put(fileInfoLine, checkExecutor.submit(myRunner));       
            exitLoop = false;
            boolean newRun = true;
            boolean evenRow = true;
            // String fileName = null;
            while(true && exitLoop == false) {
            HashMap<String, Future> tempFutures = futures;   
            ArrayList<String> keyList = new ArrayList<String>();
            for (Entry<String, Future> entry  : tempFutures.entrySet()) {
            	//This is to stop the process
            	if (exitLoop) break;
                Future<List<CheckDetail>> f = entry.getValue();
                    try {
                        checkDetails = f.get(1, TimeUnit.MILLISECONDS);
                        if (checkDetails != null) {
                            evenRow = Gui.populateResultsTable(checkDetails,shell,table,titles, newRun, evenRow, groupResults);
                            newRun = false;                            
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                    } catch (ExecutionException e) {
                        // TODO Auto-generated catch block
                    } catch (TimeoutException e) {

            if (!futures.isEmpty()){             
                for (String key : keyList) {
            if (futures.isEmpty())
               exitLoop = true;

            //This is to set the initial set of data in the table to save the relevant information to a xml file.
            //return checkDetailsAll;
        public void setTable(Table table, String[] titles) {
            RunPerl.table = table;
            RunPerl.titles = titles;
        public void setShell(Shell shell, Display display) {
   = shell; 
            RunPerl.display = display;
        public void setGroupResults(Group groupResults) {
            RunPerl.groupResults = groupResults; 
        public static void setcompTB3_table_newThread(Composite combTB3){
            compTB3_table_newThread = combTB3;
        public Composite getcompTB3_table_newThread(){
            return compTB3_table_newThread;
        public static void saveResults(String file) throws ParserConfigurationException, IOException, ClassNotFoundException{
            DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            //get current date time with Date()
            Date date = new Date();

            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("Results");
            Element dateElement = doc.createElement("Date");
            //List<CheckDetail> checkDetailsTable = Gui.getTableData();
            List<CheckDetail> checkDetailsTableAll = CSFilteringCheckBoxes.getTableData();
            for (CheckDetail checkDetail : checkDetailsTableAll) {
                Element detailElement = doc.createElement("Detail");

                Element nameElement = doc.createElement("name");

                Element checkElement = doc.createElement("check");

                Element statusElement = doc.createElement("status");

                Element existingLineNumbersElement= doc.createElement("existingLineNumbers");

                Element newLineNumbersElement= doc.createElement("newLineNumbers");


            Transformer transformer = null;
            try {
                transformer = TransformerFactory.newInstance().newTransformer();
            } catch (TransformerConfigurationException e) {
                // TODO Auto-generated catch block
            } catch (TransformerFactoryConfigurationError e) {
                // TODO Auto-generated catch block
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{}indent-amount", "4");
            // This is to serialize to a File
            FileWriter fileWriter = null;
            try {
                fileWriter = new FileWriter(file);
            } catch (IOException e) {
                // TODO Auto-generated catch block
            try {
                transformer.transform(new DOMSource(doc), new StreamResult(fileWriter));
            } catch (TransformerException e) {
                // TODO Auto-generated catch block
            try {
            } catch (IOException e) {
                // TODO Auto-generated catch block
        //this is to stop all running checks
        public static void stopAllRunners() {
            for (CheckRunner runner : checkRunners) {
                if (runner != null) {
                	exitLoop = true;
        public static List<CheckDetail> getCheckResults(){       	
        	return  checkDetailsAll;

Open in new window

This is the class:

public class CheckRunner implements Callable<List<CheckDetail>> {
    protected String resultsXML;
    protected String execCmd;
    static List<CheckDetail> checkDetails = null;
    final static List<CheckDetail> checkDetailsAll = new ArrayList<CheckDetail>();
    static Process mtcheck_process = null;
   public void setCommand(String perlCmd)
       execCmd = perlCmd;
   public List<CheckDetail> call() {
     //get the environment variables
       Map<String, String> env = System.getenv();
       String [] environment = new String[env.size()];
       int i = 0;
       for (Map.Entry<String, String> entry : env.entrySet())
           environment[i] = entry.getKey() + "=" + entry.getValue();
       Runtime mtcheck_runtime = Runtime.getRuntime();
       try {
           mtcheck_process = mtcheck_runtime.exec(execCmd);
       } catch (Exception e) {
    	 //DEBUG:: System.out.println("error executing " + execCmd);

       /* dump output stream */
       InputStream is = mtcheck_process.getInputStream();
       BufferedReader reader = new BufferedReader
           ( new InputStreamReader(is));
       String commandLineOutput;
       try {
        while ((commandLineOutput = reader.readLine()) != null) {
               Pattern p = Pattern.compile("\\d{8}_\\d{4}_\\d{2}_.*?_Mwcheck_CodingStandards_ALL_Files.xml");
               Matcher m = p.matcher(commandLineOutput);
               if (m.find()){
                   resultsXML =;                       
             //DEBUG:: System.out.println(commandLineOutput);
               //Log command line output to the log file
               try {
            	   DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            	   Date date = new Date();
            	   //This will append the command line out put to the log file
                   BufferedWriter out = new BufferedWriter(new FileWriter("//somepath//mtcheck/" + dateFormat.format(date) + "_UserData.txt", true));                   
                   out.write("\tCommand Line Output: " + commandLineOutput + "\r\n");
               } catch (IOException e) {
               	//DEBUG:: System.out.println("writeToFile problem:");
    } catch (IOException e) {
        // TODO Auto-generated catch block
       /* print final result of process */
     //DEBUG:: System.err.println("Exit status=" + mtcheck_process.exitValue());
       String tempDir = null;
       String OS = System.getProperty("").toLowerCase();
       if (OS.indexOf("win") >= 0){
           tempDir = "C:/Temp/mtcheck";
       } else{
           tempDir = "/tmp/mtcheck";
       //get the name of the  generated XML from the CLI 
       //and parse it to generate the results table
       String path2ResultsXML = tempDir + "/" + resultsXML;
       //TO DO: check if this file exists
       new ParseResultsXML().parse(path2ResultsXML);
       //checkDetails = new ParseResultsXML().getResultsXMLData();
       checkDetails = new ParseResultsXML().parse(path2ResultsXML);
       for(Iterator<CheckDetail> j = checkDetailsAll.iterator();j.hasNext();) {
           CheckDetail checkDetail =;
           String fileName = checkDetail.getFileName();
           fileName = fileName.replace('/', '\\');
    //return checkDetailsAll;
       return checkDetails;

    public static List<CheckDetail> getList(){
        return checkDetailsAll;
    public static void cleanList(){
    public void stop() {
        if (mtcheck_process != null) {

Open in new window

stopAllRunners() is invoked by a listener when you click on a button. Then this is supposed to stop the runners but it does not stop it. Instead, since the exitloop is becomes true, the populateResultsTable method is not called.

But this is not enough for me, because if I start the process again then everything masses up due to already running process..

Can you please me help to stop this running process?

Question by:Tolgar
  • 2
LVL 86

Expert Comment

ID: 39638486
As i've mentioned elsewhere before, the ultimate sanction is Process.destroy. I note that the Process class doesn't appear anywhere in the code you posted
LVL 35

Accepted Solution

mccarl earned 500 total points
ID: 39638511

In our last attempt at this I thought that I couldn't fully help because I don't have your full environment on my side to play with and get working. However, I should have asked you to post the full code again, and I would have noticed this.... You didn't do everything that I suggested in that previous question (the first bullet point).

Look at line 6 of, you STILL have your Process object declared as static.

Author Comment

ID: 39644688
I think it works now. I am closing this thread for now :)
LVL 35

Expert Comment

ID: 39647340
Glad you got it going! :)

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
stackato and cloud 4 69
This code tracks birthdays 3 60
Definitions and default visual studio colors 5 58
arguments to jar 5 14
Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
Although it can be difficult to imagine, someday your child will have a career of his or her own. He or she will likely start a family, buy a home and start having their own children. So, while being a kid is still extremely important, it’s also …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now