Create a stoppable java program (daemon) - java

Starting a java command line application is easy, you only have to write the following line in a command prompt (in the directory where the app is located).
java myApp.java
However, to stop the application in the right way, so that you ensure that all unmanaged resources are cleaned (and anything that must be done before stop, will be done) requires custom code.
The app will run in a debian system with no GUI as a daemon (it will run in background).
Here below I write the skeleton of the code.
public class MainClass {
public static void main(String[] args) throws Exception {
boolean stop = false;
while(!stop){
doSomething();
}
stop();
}
private static void doSomething(){
//Main code of app here
}
private static void stop(){
beforeStop();
System.exit(0);
}
private static void beforeStop(){
clean();
//Code to do anything you have to do before stop
}
private static void clean(){
//Code to clean unmanaged resources
}
}
As you can see, the app will run 24/24 and won't stop until you don't stop it.
Killing the process (as some people suggest) is not a good solution, because (for example) some unmanaged resources might not be cleaned properly.
I need a code which makes possible to alter the boolean variable "stop" from OUTSIDE.
The best solution is the one which makes possible to stop the app with a command similar to the start command, see pseudo code below (executed in a command prompt, in the directory where myApp.java is located).
myApp.java stop=true
But if it's not possible, the second option would be to have an other java command line app, which stops myApp.java, so that I could stop myApp.java with the following code
java stopMyApp.java
Is someone able to suggest a useful code example?

You can use a text file with one word. Your program reads it every x seconds and depending on that word it will autostop.
You can change the file text content by hand or with another program you can run whenever you want.
Even better you can use WatchService API (Java 7) or VFS API from Apache Commons to be notified when the file changes.
If you use a DB you can use it instead of a plain file.

Related

Eclipse Mars (4.5) hot swap code in debugger not working

So I updated to Eclipse Mars (4.5) and for some reason I'm unable to use the hot swap code in the debugger. Normally I could do something like this:
public static void main(String[] args){
while(true){
System.out.println("123");
}
}
Then if I started it in debug mode, changed the text to "321", then save, then it would update without the need for restarting it. It behaves exactly like it was run in "Run" mode instead of "Debug".
What I have tried:
Creating a new workspace, creating a fresh project, using the code above, nothing happens
Have several JDKs installed, have tried with java 6, 7 & 8, changed the workspace and/or the project settings to use the different JDKs, nothing happens (the fact that I have several versions of java installed shouldn't matter as it was just the moment I updated eclipse it stopped working)
Tried uninstalling removing any config files to eclipse (on a mac, so that would be every file/folder with the word "eclipse" in the ~/Library folder, ran a "find" search to detect all the files). Then tried to create a new workspace, now project, the code snipped, ran in debug mode, nothing happens on save.
Have also made sure I have "Auto Build" enabled, even tried to "clean" it, and disable auto build, then save the code, then do a manual build while the debugger was running: nothing happens
I'm starting to get desperate as I have a hard time getting work done without having debug mode available so any help/hints in the right direction would be of much appreciation.
HotSwap doesn't work with static methods. However it works fine with instance methods, so it will work on this code:
public class Main {
public static void main(String[] args) {
new Main().f();
}
public void f() {
while(true){
System.out.println("123");
}
}
}
Ok so I finally found the problem. It seems that you can't edit loops while they are running. Say you have a loop like this:
public static void main(String[] args){
while(true){
System.out.println("123");
}
}
Then you can't edit the "123" string.
You can how ever edit methods which are called inside the loop like this:
public static void main(String[] args){
while(true){
System.out.println(methodA());
}
}
public static String methodA(){
return "123";
}
Now you can edit the string "123" and it will update.
This also applies for infinite "for" loops, so guess the rule of thumb is that the method body has to be "re-called" before updating, and it isn't enough to wait for the next loop call.

How to implement Queue in Java?

I have a folder with 1 ThMapInfratab1-2.exe file and 3 .txt files. If you run .exe file in any way(through command prompt,just double click and through any language) one Icon will be appear on Taskbar.
My .exe will be run 2-3 minutes.
Know I want to run these .exe file using Java.I found How to run .exe from Java technology.
My concept was, first I will find .txt file Names from the directory.finally I will get like this.
List<File> fileNames={"File1.txt","File2.txt","File3.txt"};
Know I want to run my .exe file 3 times because my fileNames length is equals to 3.For this I wrote the following code.
//ExeFileProcess Function
public void ExeternalFileProcessing(String DirectoryPath,String exeFileName,String inputFileName) throws IOException
{
String executableFileName = DirectoryPath+"/"+exeFileName;
String inputFile=inputFileName;
ProcessBuilder processBuilderObject=new ProcessBuilder(executableFileName,inputFile);
File absoluteDirectory = new File(DirectoryPath);
processBuilderObject.directory(absoluteDirectory);
processBuilderObject.start();
//processBuilderObject.wait();
}
//Main Function code.
public static void main(String[] args) throws IOException
{
ExternalFileExecutions ExternalFileExecutionsObject=new ExternalFileExecutions();
for (int fileIndex = 0; fileIndex < fileNames.size(); fileIndex++)
{
ExternalFileExecutionsObject.ExeternalFileProcessing("C:/Users/Infratab Bangalore/Desktop/Rod","ThMapInfratab1-2.exe",fileNames[fileIndex ]);
}
}
I evaluated above code, at a time 3 .exe processes are started.But I don't want like that. I want to run .exe file one by one(we need to monitor, whether the previous .exe process was done or not. once it's done it allows to next Iteration).
I tried with Wait().but it's not working.
I guess, for this I need to add some code in my ExeternalFileProcessing(). But I didn't get anything.
can anyone suggest me.
I hope, you understand, what My problem.
ProcessBuilder.start method returns an instance of Process class. YOu can use waitFor method to wait until created process stops:
...
Process process = processBuilderObject.start();
process.waitFor();
}
processBuilderObject.wait() is a invocation of Object's wait method. It is used for concurrency and doesn't relate to processes at all.

How to start a java program?

I have written a java program and I am running it through command line like "java MyProgram"
Now I want to have a GUI that have a start, pause and stop button. How to start that java program by clicking on start button. How to pause it and how to stop it?
I assume your program is something like:
public class MyProgram {
public void doSomething() {
// ... does something ...
}
public static void main(String[] args) {
new MyProgram().doSomething();
}
}
I recommend reading the Swing Tutorial, but a simple GUI to launch your program could be something like:
public class MyProgramLauncher {
public static void main(String[] args) {
final MyProgram myProgram = new MyProgram();
JFrame frame = new JFrame("My Program");
JComponent cp = frame.getContentPane();
cp.add(new JButton(new AbstractAction("Start") {
public void actionPerformed(ActionEvent e) {
myProgram.doSomething();
}
}));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
If your class has a pause() function, you could add a similar JButton to call that function, but you'd have to write/implement the function.
You would, however, have to launch this with java MyProgramLauncher, which isn't very exciting. Still, that will get you a basic GUI in which you can experiment with starting, pausing, etc.
To turn your program into something you can double-click on, you'll need to create a JAR file. This is basically a special ZIP file that includes all the classes in your application, plus a manifest.xml file that describes those classes and (for launchable JAR files) identifies the "main class" whose main() method should be called when the JAR file is launched.
To turn that JAR file into a more or less self-contained deployable application is a bigger pain and there are a whole lot of options. The Deployment Tutorial might be a place to start.
Basically you need a native launcher, but I cannot figure out what do you mean exactly by "pause"... Sending the process to sleep?
I think that should be very easy to implement with a shellscript using the xdialog command in a Unix like system.
You'll need to implement a state machine:
State: "Stopped"
Start: execute java YourProgram and store the PID in a variable. Change state to "Started"
Pause: do nothing/disabled
Stop: do nothing/disabled
State: "Started"
Start: do nothing/disabled
Pause: send the STOP signal (like ctr+z) to the process. Change state to "Paused"
Stop: send the INT signal (like ctr+c) to the process. Change state to "Stopped"
State "Paused"
Start: do nothing/disabled
Pause: send the CONT signal (like doing fg) to the process. Change start to "Started"
Stop: send the INT signal (like ctr+c) to the process. Change state to "Stopped"
With this, you can loop in the script and react to the buttons. Look the reference for kill and dialog or xdialog for more details on the implementation.
First you need to write your "Forms"...
This will be a helpful resource to a beginner.
Basics

Disconnect java application from console/command window [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Is there a way to the hide win32 launch console from a Java program (if possible without JNI)
When I run my java swing application in a batch file on windows, the console/command window remains open whilst my java application is running. This creates an extra window on my taskbar which I would prefer not to have. But when I close the command window it stops my java application. Is there a way, perhaps via the batch file or command line parameters or code changes to my application, to have java.exe exit after bringing up my swing app and the console window close whilst my application still runs?
Main method is as follows:
public static void main(String args[]) {
ApplContext applContext = new ApplContext();
Throwable error = null;
try {
applContext.setUserConfigDir(args.length>0 ? args[0] : null);
applContext.loadData();
ApplTools.initLookAndFeel(Parameters.P_NIMBUS_LAF.of(applContext.getParameters()));
} catch (Throwable e) {
error = e;
}
// JWorkSheet is a JFrame.
new JWorkSheet(applContext, error).setVisible();
}
Run your application with javaw.exe rather than java. If you're running from a bat file, use this in combination with the start command:
> start javaw.exe -jar myapp.jar
When run in this mode, it's a good idea to set up proper logging or at least redirect your output streams if you rely on the console for any debugging. For example, with no console, you'll never see those friendly stack traces printed for unhandled exceptions.
Note: java.exe is a Windows console application. As such, no matter how it is started, or what threads are running in it, a console will be allocated for it. This is the reason that javaw.exe exists.
Ideally what you will eventually do somewhere in your code is call SwingUtilities.invokeLater(Runnable r). That will throw your GUI code into the correct thread, and you should be able to close the command line after the main thread exits.
This is a basic example of what I am talking about:
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
JFrame yourWindow = new YourFrame();
yourWindow.createAndShow();
}
}
}

How do I launch a completely independent process from a Java program?

I am working on a program written in Java which, for some actions, launches external programs using user-configured command lines. Currently it uses Runtime.exec() and does not retain the Process reference (the launched programs are either a text editor or archive utility, so no need for the system in/out/err streams).
There is a minor problem with this though, in that when the Java program exits, it doesn't really quit until all the launched programs are exited.
I would greatly prefer it if the launched programs were completely independent of the JVM which launched them.
The target operating system is multiple, with Windows, Linux and Mac being the minimum, but any GUI system with a JVM is really what is desired (hence the user configurability of the actual command lines).
Does anyone know how to make the launched program execute completely independently of the JVM?
Edit in response to a comment
The launch code is as follows. The code may launch an editor positioned at a specific line and column, or it may launch an archive viewer. Quoted values in the configured command line are treated as ECMA-262 encoded, and are decoded and the quotes stripped to form the desired exec parameter.
The launch occurs on the EDT.
static Throwable launch(String cmd, File fil, int lin, int col) throws Throwable {
String frs[][]={
{ "$FILE$" ,fil.getAbsolutePath().replace('\\','/') },
{ "$LINE$" ,(lin>0 ? Integer.toString(lin) : "") },
{ "$COLUMN$",(col>0 ? Integer.toString(col) : "") },
};
String[] arr; // array of parsed tokens (exec(cmd) does not handle quoted values)
cmd=TextUtil.replace(cmd,frs,true,"$$","$");
arr=(String[])ArrayUtil.removeNulls(TextUtil.stringComponents(cmd,' ',-1,true,true,true));
for(int xa=0; xa<arr.length; xa++) {
if(TextUtil.isQuoted(arr[xa],true)) {
arr[xa]=TextDecode.ecma262(TextUtil.stripQuotes(arr[xa]));
}
}
log.println("Launching: "+cmd);
Runtime.getRuntime().exec(arr);
return null;
}
This appears to be happening only when the program is launched from my IDE. I am closing this question since the problem exists only in my development environment; it is not a problem in production. From the test program in one of the answers, and further testing I have conducted I am satisfied that it is not a problem that will be seen by any user of the program on any platform.
There is a parent child relation between your processes and you have to break that.
For Windows you can try:
Runtime.getRuntime().exec("cmd /c start editor.exe");
For Linux the process seem to run detached anyway, no nohup necessary.
I tried it with gvim, midori and acroread.
import java.io.IOException;
public class Exec {
public static void main(String[] args) {
try {
Runtime.getRuntime().exec("/usr/bin/acroread");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Finished");
}
}
I think it is not possible to to it with Runtime.exec in a platform independent way.
for POSIX-Compatible system:
Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", "your command"}).waitFor();
I have some observations that may help other people facing similar issue.
When you use Runtime.getRuntime().exec() and then you ignore the java.lang.Process handle you get back (like in the code from original poster), there is a chance that the launched process may hang.
I have faced this issue in Windows environment and traced the problem to the stdout and stderr streams. If the launched application is writing to these streams, and the buffer for these stream fills up then the launched application may appear to hang when it tries to write to the streams. The solutions are:
Capture the Process handle and empty out the streams continually - but if you want to terminate the java application right after launching the process then this is not a feasible solution
Execute the process call as cmd /c <<process>> (this is only for Windows environment).
Suffix the process command and redirect the stdout and stderr streams to nul using 'command > nul 2>&1'
It may help if you post a test section of minimal code needed to reproduce the problem. I tested the following code on Windows and a Linux system.
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
Runtime.getRuntime().exec(args[0]);
}
}
And tested with the following on Linux:
java -jar JustForTesting.jar /home/monceaux/Desktop/__TMP/test.sh
where test.sh looks like:
#!/bin/bash
ping -i 20 localhost
as well as this on Linux:
java -jar JustForTesting.jar gedit
And tested this on Windows:
java -jar JustForTesting.jar notepad.exe
All of these launched their intended programs, but the Java application had no problems exiting. I have the following versions of Sun's JVM as reported by java -version :
Windows: 1.6.0_13-b03
Linux: 1.6.0_10-b33
I have not had a chance to test on my Mac yet. Perhaps there is some interaction occuring with other code in your project that may not be clear. You may want to try this test app and see what the results are.
You want to launch the program in the background, and separate it from the parent. I'd consider nohup(1).
I suspect this would require a actual process fork. Basically, the C equivalent of what you want is:
pid_t id = fork();
if(id == 0)
system(command_line);
The problem is you can't do a fork() in pure Java. What I would do is:
Thread t = new Thread(new Runnable()
{
public void run()
{
try
{
Runtime.getRuntime().exec(command);
}
catch(IOException e)
{
// Handle error.
e.printStackTrace();
}
}
});
t.start();
That way the JVM still won't exit, but no GUI and only a limited memory footprint will remain.
I tried everything mentioned here but without success. Main parent Java process can't quit until the quit of subthread even with cmd /c start and redirecting streams tu nul.
Only one reliable solution for me is this:
try {
Runtime.getRuntime().exec("psexec -i cmd /c start cmd.cmd");
}
catch (Exception e) {
// handle it
}
I know that this is not clear, but this small utility from SysInternals is very helpful and proven. Here is the link.
One way I can think of is to use Runtime.addShutdownHook to register a thread that kills off all the processes (you'd need to retain the process objects somewhere of course).
The shutdown hook is only called when the JVM exits so it should work fine.
A little bit of a hack but effective.

Categories

Resources