End process in java

Killing a process using Java

I would like to know how to «kill» a process that has started up. I am aware of the Process API, but I am not sure, If I can use that to «kill» an already running process, such as firefox.exe etc. If the Process API can be used, can you please point me into the correct direction? If not, what are the other available options? Thanks.

java runs in a virtual machine, it’s like a closed box; by no means you kill a system process in pure java. There might be options invoking native interfaces. See JNI or JNA

What trick resolved your issue ? I am also facing the same issue. I have described details here: stackoverflow.com/questions/27942679/…

@BilalAhmedYaseen I used the selected answer and the answer by Lakshitha Ranasingha, they did the trick for me.

8 Answers 8

If you start the process from with in your Java application (ex. by calling Runtime.exec() or ProcessBuilder.start() ) then you have a valid Process reference to it, and you can invoke the destroy() method in Process class to kill that particular process.

But be aware that if the process that you invoke creates new sub-processes, those may not be terminated (see https://bugs.openjdk.org/browse/JDK-4770092).

On the other hand, if you want to kill external processes (which you did not spawn from your Java app), then one thing you can do is to call O/S utilities which allow you to do that. For example, you can try a Runtime.exec() on kill command under Unix / Linux and check for return values to ensure that the application was killed or not (0 means success, -1 means error). But that of course will make your application platform dependent.

Источник

How to end java program

enter image description here

Do I have to add some exit statement? Code seems to be running well, but after it finish its task I still can’t interact with console.

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package excelb; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; import javax.swing.JFileChooser; import javax.swing.JFrame; /** * * @author hp */ public class Excelb < /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException, IOException < // TODO code application logic here String row; String row2; File fn = null; int counter = 0; Scanner in = new Scanner(System.in); System.out.println("Enter the run identifier for output file"); String output = in.nextLine(); //input JFileChooser jFileChooser = new JFileChooser(); jFileChooser.setCurrentDirectory(new File("C:/")); int result = jFileChooser.showOpenDialog(new JFrame()); if (result == JFileChooser.APPROVE_OPTION) < fn=jFileChooser.getSelectedFile(); System.out.println("Data file: " + fn.getAbsolutePath()); //System.out.println("Data file: " + fn.getTitle()); >BufferedReader csvReader = new BufferedReader(new FileReader("Keywords.csv")); BufferedReader csvReader2 = new BufferedReader(new FileReader(fn.getAbsolutePath())); row = csvReader.readLine(); String[] data = row.split(","); while (counter < data.length) < while ((row2 = csvReader2.readLine()) != null) < String[] data2 = row2.split(","); for (int j = 0; j < data.length; j++) < if ((data2[data2.length - 1].contains(data[j]))) < //DateFormat df = new SimpleDateFormat("dd/MM/yy"); //Date dateobj = new Date(); //String d = df.format(dateobj); //d = d.replaceAll("/", ""); String newFile = data[j] + "_" + output + ".csv"; FileWriter csvWriter = new FileWriter(newFile, true); for (int i = 0; i < data2.length; i++) < csvWriter.append(data2[i]); csvWriter.append(","); >csvWriter.append("\n"); csvWriter.close(); > > > counter++; > System.out.println("Finished"); csvReader.close(); csvReader2.close(); > > 

You know, now would be a great time to start using Windows new and improved subsystem for Linux. CMD is the most developed unfriendly command line I know of

Читайте также:  Document

Источник

Terminating a Java Program

I am sure that 2 will not appear. I would like to know is why return; or other codes can write below the statement of System.exit(0); and what was real definition for return; (because it is strange thing for me return without any variables or values) ?

7 Answers 7

Calling System.exit(0) (or any other value for that matter) causes the Java virtual machine to exit, terminating the current process. The parameter you pass will be the return value that the java process will return to the operating system. You can make this call from anywhere in your program — and the result will always be the same — JVM terminates. As this is simply calling a static method in System class, the compiler does not know what it will do — and hence does not complain about unreachable code.

return statement simply aborts execution of the current method. It literally means return the control to the calling method. If the method is declared as void (as in your example), then you do not need to specify a value, as you’d need to return void . If the method is declared to return a particular type, then you must specify the value to return — and this value must be of the specified type.

return would cause the program to exit only if it’s inside the main method of the main class being execute. If you try to put code after it, the compiler will complain about unreachable code, for example:

public static void main(String. str)

will not compile with most compiler — producing unreachable code error pointing to the second System.out.println call.

Читайте также:  Java jdk old versions

Источник

Java Exit Program — How to end program in java?

Twitter Facebook Google Pinterest

A quick guide to exit program in java. Use System.exit() or return to end and terminate the java programs.

1. Overview

In this tutorial, We’ll learn how many ways to end java program and how to terminate program execution in java.

How to end program in java?

2. End and Terminate program using System.exit()

Use System.exit() method to end the java program execution. exit() method is from the System class and exit() is a static method.

System.exit() method gives the instructions to JVM to terminate the current running program from the point of exit() method.

package com.javaprogramto.programs.exit; public class JavaProgramExitExample < public static void main(String[] args) < System.out.println("hello java developers "); System.out.println("understand how System.exit() method works"); System.exit(0); System.out.println("Last line from this program"); >>
hello java developers understand how System.exit() method works Process finished with exit code 0

From the above code, we expect the 3 statement to be printed on the console from three System.out.println() statements But it has prinited only first two.

Because System.exit() is after the second sysout. Wheneven java runtime finds exit() method, it just stops the program execution at any point of time.

0 value indicates to jvm exit the program with successful finishing with no errors. That is graceful termination.

but if you pass any non zero value leads to print with the error message. But from java 8 or above versions, it does not show any error message even if non zero value is pased.

System.exit(2); System.exit(-1); System.exit(3);

3. Java end program using return statement

We can use return statements from the methods or from the main program to end the current method execution and continue from its parent.

package com.javaprogramto.programs.exit; public class JavaProgramExitExample2 < public static void main(String[] args) < System.out.println("satement 1"); System.out.println("statement before return statement"); return; System.out.println("Last line from this program"); >>

This program does not compile because there is a sysout statement after return statement. That mean compiler detects that last line of the program is never going to be executed with the error message «Unreachable code«.

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unreachable code at com.javaprogramto.programs.exit.JavaProgramExitExample2.main(JavaProgramExitExample2.java:12)
package com.javaprogramto.programs.exit; public class JavaProgramExitExample3 < public static void main(String[] args) < System.out.println("first line from main method"); method(); System.out.println("last line from main method"); >private static void method() < System.out.println("executing the method"); return; >>
first line from main method executing the method last line from main method

4. Java end program using return statement with if else

If the condition is met then execute the logic and return «even number» and from else condition return «odd number» value.

package com.javaprogramto.programs.exit; public class JavaProgramExitExample4 < public static void main(String[] args) < System.out.println("first line from main method"); int number = 10; String value = getValue(number); System.out.println(value); System.out.println("last line from main method"); >private static String getValue(int number) < System.out.println("statement 1"); if(number % 2 == 0) < return "even number"; >else < return "odd number"; >> >
first line from main method statement 1 even number last line from main method

5. Conclusion

In this article, we’ve seen how to end the program in java using System.exit() and return statement.

Читайте также:  Web xml tags in java

In the real time, system.exit() is used in the standalone and concurrent applications on the particular conditions met. But, prefer to throw the custom exception with the correct error message for better debugging.

Labels:

SHARE:

Twitter Facebook Google Pinterest

About Us

Java 8 Tutorial

  • Java 8 New Features
  • Java 8 Examples Programs Before and After Lambda
  • Java 8 Lambda Expressions (Complete Guide)
  • Java 8 Lambda Expressions Rules and Examples
  • Java 8 Accessing Variables from Lambda Expressions
  • Java 8 Method References
  • Java 8 Functional Interfaces
  • Java 8 — Base64
  • Java 8 Default and Static Methods In Interfaces
  • Java 8 Optional
  • Java 8 New Date Time API
  • Java 8 — Nashorn JavaScript

Java Threads Tutorial

Kotlin Conversions

Kotlin Programs

Java Conversions

  • Java 8 List To Map
  • Java 8 String To Date
  • Java 8 Array To List
  • Java 8 List To Array
  • Java 8 Any Primitive To String
  • Java 8 Iterable To Stream
  • Java 8 Stream To IntStream
  • String To Lowercase
  • InputStream To File
  • Primitive Array To List
  • Int To String Conversion
  • String To ArrayList

Java String API

  • charAt()
  • chars() — Java 9
  • codePointAt()
  • codePointCount()
  • codePoints() — Java 9
  • compareTo()
  • compareToIgnoreCase
  • concat()
  • contains()
  • contentEquals()
  • copyValueOf()
  • describeConstable() — Java 12
  • endsWith()
  • equals()
  • equalsIgnoreCase()
  • format()
  • getBytes()
  • getChars()
  • hashcode()
  • indent() — Java 12
  • indexOf()
  • intern()
  • isBlank() — java 11
  • isEmpty()
  • join()
  • lastIndexOf()
  • length()
  • lines()
  • matches()
  • offsetByCodePoints()
  • regionMatches()
  • repeat()
  • replaceFirst()
  • replace()
  • replaceAll()
  • resolveConstantDesc()
  • split()
  • strip(), stripLeading(), stripTrailing()
  • substring()
  • toCharArray()
  • toLowerCase()
  • transform() — Java 12
  • valueOf()

Spring Boot

$show=Java%20Programs

$show=Kotlin

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,

A quick guide to exit program in java. Use System.exit() or return to end and terminate the java programs.

Источник

Оцените статью