Runtime.exec() in a seperate thread, and multithreading in general

Hey guys -
I've scoured the web trying to learn how to make separate threads in Java, but to no avail. My situation is that I am using mplayer in Linux with my application, but the JFrame that I am using freezes after selecting the file and mplayer successfully being launched in the background and playing. The JFrame has a textbox that is trying to get the output of the command from the console using a simple BufferedReader.
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                     
           int status = musicfile_dialog.showOpenDialog(null);
           if (status == musicfile_dialog.APPROVE_OPTION)
                 File selectedFile = musicfile_dialog.getSelectedFile();
                 String[] cmd = {"mplayer", selectedFile.toString()};
                 try                        
                     int index = 0;
                     double current = 0.0;
                     double end = 0.0;
                     char[] split_up;
                     boolean output_percent = true;
                     String line;
                     Process p = Runtime.getRuntime().exec(cmd);
                     catch (InterruptedException interrupt)
                     BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
                     while ((line = input.readLine()) != null)
                         split_up = line.toCharArray();
                         for(int x=0;x<line.length();x++)
                             try{current = Double.parseDouble(String.valueOf(split_up[3]) + String.valueOf(split_up[4]) + String.valueOf(split_up[5]) + String.valueOf(split_up[6]) + String.valueOf(split_up[8])); output_percent = true;}
                             catch (NumberFormatException numf) // happens becuase mplayer outputs some junk at very beginning of output
                                 output_percent = false;
                             if(split_up[x]=='f')
                                 try{end = Double.parseDouble(String.valueOf(split_up[x+2]) + String.valueOf(split_up[x+3]) + String.valueOf(split_up[+4]) + String.valueOf(split_up[x+5])); output_percent = true;}
                                 catch (NumberFormatException numf2) // happens becuase mplayer outputs some junk at very beginning of output
                                     output_percent = false;
                             if(output_percent)
                                 double percent = (current/end)*100;
                                 String display_percent = Double.toString(percent);
                                 jTextField1.setText(jTextField1.getText() + "\n" + display_percent);
                                 System.out.println(display_percent);
                     input.close();
                catch (IOException e) { e.printStackTrace();}           
    } So essentially, I'm trying to make it so that the JFrame doesn't freeze up when given the command
jTextField1.setText(jTextField1.getText() + "\n" + display_percent);and also so that mplayer's console output is still available to the JFrame for processing.
Any ideas?
Thank you so much,
Andrew
Edited by: AndrewTheArt on Nov 4, 2007 6:29 AM

I've scoured the web trying to learn how to make separate threads in Java, but to no avail. Err.. the first Google hit - http://java.sun.com/docs/books/tutorial/essential/concurrency/ . Also there is a section of Threading within Swing in the Swing tutorial.

Similar Messages

  • Runtime.exec failure in applet(IE and Netscape)

    Hi
    Runtime.exec() failures to execute an executable(VB) in an Applet with Internet Explorer and Netscape Navigator. But the same is working fine with Mozilla Firefox and Opera. All the four browsers can load the applet successfully and listens the Swing component's action by actionlistener. But the problem is that IE and Netscape cant execute a VB created executable. The sample code of failure part is:
    public void actionPerformed(java.awt.event.ActionEvent e){
    Runtime.getRuntime().exec(abc.exe);
    Here abc.exe is a VB exe for doing simple thing.
    Plz help me on it if anyone knows about it..................
    Raz
    Message was edited by:
    rashidul

    hi,
    1st: 40MB is maybe a little bit too much :-)
    2nd swing is not really good for applets and espicially not for IE
    regards

  • Applet to Applet communication between two seperate threads and jsp pages

    Hi,
    have two java applets running on two separate jsp pages. I am trying to have one applet talk to the other applet. I have tried putting the applets in a static hashtable, but I found out (through trial and error) that the memory is not shared between the applets. Needless to say the appletcontext object will not work as well. I have also tried to put the applet threads into a thread group, but it seems that the second applet can't find the first applet's threads. Is there a funky way that I need to create the threads for the threadgroup? Is there a way or type of object that I can use that will share the static memory between plugins? I am using 1.6 in IE. Or am I looking at this wrong and there is an easy way to do this and I am not seeing it.
    Thanks,
    Marc

    Hi Mylene,
    I hope I have understood your problem correctly. I can try to give you a tip. The times I've had to do a pop-up, for instance to show details or a part of the data in a table, I call a javascript function with the required parameters (an ID for details or an array of rows) when the button is pressed or a link is clicked. The function then builds a URL with all the paremeters and uses it to call the standard window.open function. After that the request is handled "as usual", ie as if you didn't actually do a pop-up but simply displayed a new page. The content of the pop-up is a jsp with all the required code to build the table and/or display the data. The contents of the table or data are retrieved with the help of the parameters sent.
    I'm not sure if the portal kit provides some kind of standard functionality for this, but in the cases I've worked with J2EE solutions this has been the most common way of solving the problem.
    I hope this helps.
    kind regards,
    Dionisios

  • Runtime.exec and locked window

    So I'm working in a Swing application guaranteed to run only on Windows systems using Java 1.6 u 7. The users want a help button to launch a local web browser and point to the company's web site.
    After reading online and finding that getDesktop.browse() sometimes crashes in that version of Java, I use Runtime.exec("rundll ...") to kick off the local browser with the appropriate web address.
    The browser comes up appropriately, but the original Swing application's mouse pointer converts to an hourglass; I can click on the original window and get results but I can't open a new window.
    So I create a short thread implementing the Runnable interface and put the Runtime.exec call in that thread; I assume the problem is that the process is interfering with the GUI thread, and putting the Runtime.exec call in a separate thread will clear the problem up. It doesn't work; I still have the hourglass.
    I read online that some processes require that their input and error streams be consumed, or they may block; That shouldn't be a problem with internet explorer, but I add two threads to consume those streams; still no change.
    I also tried getDesktop().browse() anyway, and in a separate thread, and had the same problem.
    Does anyone have any suggestions?
    Respectfully,
    Brian P.

    Okay.
    First, let's look at the basic client.
    As you can see, when asked to show a window,
    it puts it in a separate thread for rendering:
    public class Client     
    // Show one example method
         private void showNewWindow(Window window)
              ourLogger.info("New request to display window: " + window.getClass().getName());
              if (window instanceof ClientWindow)
                   try
                        ((ClientWindow) window).bindFrames();
                        ((ClientWindow) window).setClient(this);
                        if (window instanceof ClientJDialog)
                             window = new ClientJDialog((ClientJDialog) window);
                        else
                             correctSize(window);
                        showCenter(window);
                        synchronized(myWindows)
                             myWindows.add(window);
                        counter = 0;
                        thread.hide();
                   catch (Exception re)
                        ourLogger.error("Client error while trying to show window", re);
                        ((ClientWindow) window).unbindFrames(false);
              else
                   throw new Error(window.getClass().getName() + " is NOT an instance of ClientWindow");
    // Snip some more
    At this same level on this class, I had originally put a showHelp() procedure with a single
    command thus:
         public void showHelp()
              Desktop.getDesktop().browse(java.net.URI.create(<help web site>));
    Simple, eh? But that gave me the hourglass as discussed. So I pushed it into a new thread.
    It eventually mutated thus:
         public void showHelp()
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
              //windows only
              Runtime rt = Runtime.getRuntime();
              Process p = rt.exec("rundll32 url.dll,FileProtocolHandler " + "<help URL>");
              StreamGobbler s1 = new StreamGobbler ("stdin", p.getInputStream ());
              StreamGobbler s2 = new StreamGobbler ("stderr", p.getErrorStream ());
              s1.start ();
              s2.start ();
              try {
              p.waitFor();
              } catch (java.lang.InterruptedException e) {}
    So as you can see, I ditched Desktop from Runtime and added a pair of stream consumers
    to ensure I wasn't having the stream problem our second poster discussed. Still no joy.
    I eventually replaced the url call with an attempt to invoke a simple batch file which
    did nothing, and I still had the same problem. I still have an hour glass, even when
    the process has been pushed into a new thread as you can see.
    Respectfully,
    Brian P.
    Edited by: pendell on Apr 16, 2010 3:14 PM

  • Urgent Help Required : Java Runtime.exec

    Hello,
    We are using the java Runtime.exec in the AIX 4.3.3 environment. Java version 1.1.8. We are consuming the output of the Runtime.exec without using the threads. i.e we are doing a readline on the output stream of the runtime and printing it to th standard output in a loop. When this is over we take the error stream and do the same.
    We have two problems.
    1. A ksh that is run using the java Runtime.exec is showing up multiple processes with the same as a tree structurre when we do a ps.
    Why is this ?
    2. Also whatever we consume from the standard output/error of runtime and print it to system.out is not being output/error. Any pointers on this ?
    Thanks in advance,
    Raj.

    thanks !
    1. we have single thread executing the command. And there are no multiple processes spawned inside the shell script also.
    2. I am sorry about the phrasing. Eventhough we are catching the output stream and error stream and dumping the output correspondingly, the process ( the shell script ) hangs ! And this behaviour is sporadic. Please let us know why the process should hang !
    Thanks,
    rajesh.

  • Running interactive command with Runtime.exec

    I'm trying to run a command via the Runtime.exec interface.
    Occasionally, the command needs to prompt for additional information. The response depends on the specific configuration, however, the command returns a list of options and then waits for a response.
    However, when the command waits for the response, my Java app hangs.
    After I call Runtime.exec, I create 2 threads to consume the contents of stderr and stdout. I then start them and call proc.waitFor()
    I would expect to see the output of the command in the stdout stream even though the command hasn't exited. I had hoped to parse the output to determine the necessary response. However, the calls to read the contents of the stdout and stderr streams block and I never see any output.
    How can I get access to the contents of those streams while the command is still running? Is this supported through the Runtime.exec interface?
    Thanks,
    Shawn

    This article should help:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Using Runtime.exec to execute Java.exe

    I am trying to use Runtime.exec to spawn a thread that runs java.exe, but havn't had any luck. I have two versions of code, the first one works (example 1), but I want to eliminate the use of "cmd /c" to keep system independance. The second example (example 2) does not work. Both versions work if invoked from the command line. I'm running Win2000. Any Ideas?
    Example 1:
    aProcess = aRuntime.exec("cmd /c java.exe
    -cp "<MyClassPathHere>" <arg1> <arg2> <arg3> <arg4> <arg5>");
    Example 2:
    aProcess = aRuntime.exec("java.exe
    -cp "MyClassPathHere" <arg1> <arg2> <arg3> <arg4> <arg5>");

    I think you mix two concepts: "threads" and "processes". A "thread" is a thread of execution inside the VM, but you want to actually start a new VM in a new process, which is an OS level thing, right?
    I've tried Idea 2 also, same result: works if
    i specify cmd c/, doesn't if I don't.It should work if java.exe is in your path... are you taking care of the standard streams of your process?

  • Runtime.exec with a unix shell script

    I've done a lot of google'ing and haven't found a definitive answer to my question, including the JavaWorld article that is pointed to quite often. Scenario1 - The program calling Runtime.exec is running in /dir1 and I have a script called test.sh in /dir2 (neither directory are in the path). If I call Runtime.exec("test.sh", null, "/dir2"), I get java.io.IOException: test.sh: not found. However, if I do "touch test.sh" AND "chmod +x test.sh" in /dir1 and call the same exec, it works AND runs the script in /dir2 not /dir1?!?! Also, if I copy /dir2/test.sh /dir1/test.sh and I call exec("test.sh"), it works fine. Scenario2 - If I get rid of /dir1/test.sh and call exec("/dir2/test.sh", null, "/dir2") OR exec("/bin/sh test.sh", null, "/dir2") - both of those work. I just don't get Scenario1. Why does having the dummy executable test.sh in /dir1 allow it to run in /dir2 OR if the script is in the local directory of the process calling exec, why does it work without adding the path? It doesn't seem consistent. Seems like the working directory I specify isn't set before trying to run it or something. On the flip side, if I have a java class in /dir2 called test.class, I can call exec("java test", null, "/dir2") and it just runs without jumping through any hoops - although I think the explanation for that is that "java" is in the path. Let me know what you think.
    Gary

    I think the problem is that the three argument version of exec specifies the command to run (should be full path to it if it is not in the current dir), the environment, then the working directory. The working directory will not help java to find the command to run in the first place. The following does work as you say:
    Runtime.exec("/bin/sh test.sh",null,"/dir2");This is because the full path to the command (/bin/sh) is specified, that runs in directory /dir2 then tries to find test.sh which it finds there.
    Basically to run anything, you should specify the full path in the command, the working directory will not help java find it.
    Dave

  • Using Runtime exec() to open and close process like java or javac

    Hi, I m a student who is learning IT and is wondering if
    Runtime exec() can run and stop commands like java and javac?
    Can someone post the code to do so here?Thank you

    Well, Here is my complete code:
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    class StreamGobbler extends Thread
    InputStream is;
    String type;
    StreamGobbler(InputStream is, String type)
    this.is = is;
    this.type = type;
    public void run()
    try
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line=null;
    while ( (line = br.readLine()) != null)
    System.out.println(type + ">" + line);
    } catch (IOException ioe)
    ioe.printStackTrace();
    class Program implements Runnable
         Process proc;
    String args[];
         String[] cmd = new String[4];
         boolean isGone=false;
         public Program(String args[])
              this.args=args;
         public void run()
              if (isGone==true)
                   try
                        Runtime.getRuntime().exec(cmd).destroy();
                   catch(IOException e)
                        System.out.println("Error: "+e.toString());
                   System.out.println("User abort");
         public void start(String args[])
              if (args.length < 1)
    System.out.println("USAGE: java GoodWindowsExec <cmd>");
    System.exit(1);
    try
    String osName = System.getProperty("os.name" );
    if( osName.equals( "Windows NT" ) )
    cmd[0] = "cmd.exe" ;
    cmd[1] = "/C" ;
    cmd[3] = args[0];
    else if( osName.equals( "Windows 95" ) ||osName.equals( "Windows 98" ))
    cmd[0] = "command.com" ;
    cmd[1] = "/C" ;
    cmd[2] = args[0];
                        cmd[3]=args[1];
    Runtime rt = Runtime.getRuntime();
    // System.out.println("Execing " + cmd[0] + " " + cmd[1]
    // + " " + cmd[2]+" "+args[1]);                                    
    proc = rt.exec(cmd);
    // any error message?
    StreamGobbler errorGobbler = new
    StreamGobbler(proc.getErrorStream(), "ERROR");
    // any output?
    StreamGobbler outputGobbler = new
    StreamGobbler(proc.getInputStream(), "OUTPUT");
    // kick them off
    errorGobbler.start();
    outputGobbler.start();
    // any error???
    // int exitVal = proc.waitFor();
    //System.out.println("ExitValue: " + exitVal);
    } catch (Throwable t)
    t.printStackTrace();
         public void destroy()
              isGone=true;
    class test1 implements ActionListener
         String s[]={"c:\\jdk1.3\\bin\\java.exe","ContactProcessor1"};
         GUI g=new GUI();
              Program p=new Program(s);
         public test1()
              //didnt work
              g.getStart().addActionListener(this);
              g.getStop().addActionListener(this);
              g.show();
         public void actionPerformed(ActionEvent e)
              if (e.getSource()==g.getStart())
                   p.start(s);
                   p.run();
              if (e.getSource()==g.getStop())
                   p.destroy();
                   p.run();
         public static void main(String args[])
              test1 t = new test1();
    class GUI extends JFrame
         JButton start;
         JButton stop;
         public GUI()
              super();
              getContentPane().setLayout(new FlowLayout());
              start=new JButton("start");
              stop=new JButton("stop");
              getContentPane().add(start);
              getContentPane().add(stop);
              setSize(100,100);
         public JButton getStart()
              return start;
         public JButton getStop()
              return stop;
    }

  • Best way to close a Runtime.exec() process and how to handle closing it?

    I have multiple Runtime.exec() Processes running and am wondering what the best way it is to close them and take care of closing the resources. I see that Process.destroy() seems to be the way to terminate the Process - is finalize() the best way to close anything in that Process?
    Thanks

    I was involved with your other thread, so I think I know what you are trying to do.
    All Dr's answers are correct.
    Now you have a program A written by you that does Runtime.exec() of multiple instances
    of another program B written by you. You want A to somehow tell B to exit.
    You must use some kind of Inter Process Communication. If this is the only interraction
    between the two programs I can suggest two options. If you anticipate more
    interraction, you may want to look at other means (RMI, for instance, which was proposed
    by EJP in the other thread for starting B, is also useful in exchanging info).
    Solution 1:
    Start a thread in B and read stdin. A will write to stdin a command, such as QUIT.
    When B reads it, it does System.exit().
    Solution 2:
    Start a SocketServer in B that accepts connections on a separate thread.
    When A wants B to exit, it connects to it and writes a command such as QUIT.
    When B reads it, it does System.exit().
    You may note that QUIT is not the only command you can send from A to B, in case you will need more.
    Edited by: baftos on Nov 5, 2007 2:15 PM

  • Reading InputStream from Runtime.exec() and ffmpeg?

    I've got a lot of things going on here and I'm having trouble debugging. I'm working on a streaming music player, and the platform only handles MP3 natively. Specifically, the method that handles incoming requests has to return an InputStream for further processing upstream (out of my visibility).
    I'm trying to extend the music player to play AAC files with the extension ".m4a". To do this, my plan is to transcode from MP3 to AAC using Runtime.exec() and ffmpeg, and then return an InputStream that contains the MP3. This works fine if I use ffmpeg to transcode to a temp file, and then return a FileInputStream constructed from that temp file. But like I said, this is supposed to be a steaming music player, and the blocking for the ~30 seconds it takes to completely transcode to a file is too much of a delay.
    So what I'm trying to do is have ffmpeg transcode to stdout, and then use Process.getInputStream() to return the InputStream that contains ffmpeg's stdout while the transcoding is still going on. This doesn't work and I'm not sure why. (I'm fairly new to java, and this is the first time I've used Runtime.) My player just hangs there. I know Runtime is picky about exhausting the stdout and stderr streams, so I'm not sure if it's something related to that, or if I somehow need to buffer the stdout before returning it, or if I need to run something in a different thread, or if I'm just completely barking up the wrong tree.
    If anyone has any experience with something like this, or can point me at some code that implements something similar, I'd appreciate the help.
    Below a sample of the code in question. Also, for what it's worth, all of the console messages that I put in there are printing, but the music doesn't play.
       public InputStream getStream(String uri) throws IOException
                 System.out.println("Entering Factory.getStream()");
                  System.out.flush();
                File file = new File(URLDecoder.decode(uri, "UTF-8"));
                if (file.exists())
                     if(file.getPath().toLowerCase().endsWith(".mp3")) {
                            // This code for playing MP3 files works correctly
                          System.out.println("Playing MP3");
                          System.out.flush();
                          InputStream in = new FileInputStream(file);
                          return in;
                     else if(file.getPath().toLowerCase().endsWith(".m4a")){
                          System.out.println("Playing M4A");
                          System.out.flush();
                          // Create array for ffmpeg command line
                            // This command line transcodes to STDOUT
                          String[] command = { this.ffmpeg_path,
                                                             "-i", 
                                                             "input.m4a",
                                                             "-acodec",
                                                             "libmp3lame",
                                                             "-ac",
                                                             "2",
                                                             "-ab",
                                                             "256",
                                                             "-f",
                                                             "mp3",
                          // Begin transcoding with ffmpeg
                          System.out.println("Transcoding...");
                          System.out.flush();
                          Runtime runtime = Runtime.getRuntime();
                          Process ffmpeg = runtime.exec(command);
                          // Must exhaust error stream, or the application can become deadlocked.
                          System.out.println("Exhausting stderr...");
                          System.out.flush();
                          this.exhaustInputStream(ffmpeg.getErrorStream());
                          // Return ffmpeg's stdout as an input stream
                          System.out.println("Returning stdout...");
                          System.out.flush();
                          return ffmpeg.getInputStream();
                     else {
                          System.out.println("Unsupported Audio File");
                          System.out.flush();
                          return null;
                else
                    // We aren't requesting a file, so let the API handle the request upstream...
                    return super.getStream(uri);
         private void exhaustInputStream(final InputStream inputStream) {
                  // Since InputStream.read() blocks, exhast the stream in a separate thread
                  new Thread() {
                       public void run() {
                            try {
                                 while(inputStream.read() >= 0) {
                                      // Just throw the bytes away
                            catch(IOException e) {
                                 e.printStackTrace();
                  }.start();
             }

    Read this article
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Runtime.exec and ServerSocket for IPC...blocking problems

    I have built an IDE for assembling/deploying web applications.
    I am supporting a 'test' mode in the IDE where a compiled 'solution/application' is executed in a separate vm from the IDE using Runtime.exec. For the whole sandbox thing. Don't want a wayward application crashing my IDE.
    Naturally I want a way to communicate start/stop from the IDE to the running application. So sockets are my only choice. Calling process.destroy from my IDE won't invoke a shutdownhandler in the generated application's vm, and I want an orderly shutdown as the generated applications open resources/etc.
    When I execute the generated application from within the IDE the thread code that creates a server socket blocks in the ServerSocket constructor...why?
    When I execute the solution using 'java' outside of my IDE, I can set up a server socket and all works fine.
    My IDE is NEVER creating server sockets waiting for client connects...only the generated application does this. So it isn't a case of the IDE already listening for requests on the same port as the server/generated application.
    Proving the above is that I can manually start my generated application, start my ide, then invoke the menuitem from the IDE that writes a 'close' byte to the client's socket...and the running application DOES shut down.
    Any ideas?

    I have decided on a different approach.
    At first I thought...ok I have the ServerSocket on the wrong 'side'. I then put the ServerSocket code in the always-running IDE and the Socket code on the running/exec'd application. But still a hang on the running application when constructing the Socket.
    I decided instead to call Process.destroy on the running app.
    Given that generated app is running in a separate vm, when it shuts down via process.destroy from the ide...although vm shutdown hooks aren't called...I guess it's ok since a destroy of the vm will release all resources. Not as clean as I'd like though.
    Additionally, I cannot determine 'true' start of application as no socket notification can be done. I merely determine start after a Runtime.exec of jvm process. Subsequent errors in startup will merely be determined by the IDE in process.waitFor or process.exitValue.
    I was getting a wierd socket error when attempting my prior solutions...and not a lot on the web regarding this subject...all relevant posts seemed to be in German/from Germany. Odd. Would need my wife to translate! Mein gott!
    I guess I could've communicated from ide to Runtime.exec'd application via a generated file in filesystem...but this seemed cheesy. Sockets should've been used for ipc between java vms...or so I thought.

  • Runtime.exec() and fork() and Process

    So let me see if I understand this correctly, and if I don't please fill me in. If I call the following piece of codeRuntime.getRuntime().exec("chgrp rcsweb " + path+fs+orgName);
    Runtime.getRuntime().exec("chmod 660 " + path+fs+orgName);where path is the real path to a file, fs is short for File.spearator and orgName is the name of a file, then in the Unix environment, it will fork off a process.
    First, I seem to remember one forum topic that mentioned not forgetting about killing the process returned by exec, so I guess I need to add that to my code.
    Second, since I am forking off this process inside of a J2EE container, am I actually forming off the entire container, or just the Servlet where Runtime is called, or what?
    Third, how can I prevent the error java.io.IOException: Not enough space
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:54)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:546)
    at java.lang.Runtime.exec(Runtime.java:413)
    at java.lang.Runtime.exec(Runtime.java:356)
    at java.lang.Runtime.exec(Runtime.java:320)when I do not have the option of changing my VM size? Is killing the Process (and using waitFor()) going to take care of this issue?
    I appreciate your help.

    OK, after writing a few test programs, it is indeed clear..on unix (at least on solaris) when calling runtime.exec(..) The ENTIRE VM does indeed get forked. Therefore if your current Memory allocation for you VM is sitting at say 64MB (or you initial memory setting), another 64MB process will be created, even if you doing something as a simple
    exec("ls");
    I also tried putting runtime.exec call in its own thread hoping that if it was not in the main thread, that only that process would be forked..to no avail..the entire vm is indeed forked everytime...making runtime.exec damn near useless for server side work, and very dangerious..as you can essentialy assume you always need 2x your memory requirements.
    If anyone has figured out a workaround...any suggestions greatly appreciated.
    Some thoughts on some work-arounds
    1. Run 2 VMs (then when native calls are required..send a message to the 'native-calling vm' (insure its memory footprint is very low)
    2. Write your exec method via JNI (or does JNI calls also result in a fork of the vm on unix..)
    Test code below (threaded version)
    import java.util.*;
    import java.io.*;
    public class test5 extends Thread
         public void run()
              int loops = 0;
              while (true)
                   loops++;
                   System.out.println("---- iteration " loops "---");
                   makeNativeCall();
         public static void main(String[] args)
              try
                   System.out.println("testing on OS: " + System.getProperty("os.name"));
                   // Allocate a nice chunk of memory
                   byte[] bytes = new byte[1024 * 1000 * 50];
                   test5 tst = new test5();
                   tst.start();
                   while (true)
                        Thread.sleep(1000);
         catch(Exception e)
         {e.printStackTrace();}
    public void makeNativeCall()
              Runtime runtime = Runtime.getRuntime();
    InputStream stderr = null;
    InputStream stdout = null;
              OutputStream stdin = null;
    Process proc = null;
    long totalMem = (long)(runtime.totalMemory()/1024);
    long freeMem = (long)(runtime.freeMemory()/1024);
    long usedMem = (long)((totalMem - freeMem));
    System.out.println("VM REPORT: TOTAL(" totalMem") FREE("+freeMem+") USED(" usedMem")" );
    try
    proc = runtime.exec("sleep 1");
    stderr = proc.getInputStream();
    stdout = proc.getErrorStream();
    stdin = proc.getOutputStream();
    String line = null;
    int i = 0;
    String error = "";
    int exitVal = proc.waitFor();
    if (exitVal != 0)
    System.out.println("ERROR " +exitVal);
    System.out.println("DETIAL" +error);
    catch(Exception e)
    e.printStackTrace();
    finally
    if (stderr != null)
    try{stderr.close();}catch(Exception ignore){ignore.printStackTrace();}
                   if (stdout != null)
    try{stdout.close();}catch(Exception ignore){ignore.printStackTrace();}
                   if (stdin != null)
    try{stdin.close();}catch(Exception ignore){ignore.printStackTrace();}
    if (proc != null)
    try{proc.destroy();}catch(Exception ignore){ignore.printStackTrace();}

  • UNIX script with Runtime.exec and ssh

    I am trying to run a script that is on a UNIX server which doesn't require a password to connect to. Here's my code:
    String _cmd = new String("ssh -l root mach01 \"(/projects/examples/findsw java)\"");
    Process proc = Runtime.getRuntime().exec(_cmd);
    InputStreamReader is = new InputStreamReader(proc.getErrorStream());
    BufferedReader br = new BufferedReader(is);     
    String line = null;
    while ( (line = br.readLine()) != null)
    _logger.error(line);
    proc.waitFor();
    The error outputs:
    ERROR [Thread-7] beans.RunScript - sh: (/projects/examples/findsw java): not found
    INFO [Thread-7] beans.RunScript - _proc.exitValue() = 1
    When I execute _cmd directly from xterm, I have no problems.
    Thanks

    Runtime.exec is not a shell and doesn't run a shell. Try
    adding something like "/bin/sh -c" or whatever shell you use to the beginning of the command.
    BYe!
    EXP

  • To jschell How to get data System properties by JNI and Runtime.exec()

    Thank you very much for answer. ummm....but I'm can not gets data system properties by JNI or Runtime.exec(). Please help me. I'm want create Java-Applet for data System properties ( memory quantity?, Harddisk capacity?, CPU speed ?, Printer Name? and all hardwares ) in my computer. It very important for me. Help me please. thank you..

    Java applets are restricted to accessing only some system properties - and it is good so. I would not be happy if any applet could inquire about, say, my user name or the amount of memory in my box.

Maybe you are looking for

  • Deprecation warnings in OVDIdentityStoreFactory

    I am working in the Fusion Apps CRM development team and am investigating a couple of deprecation warnings in our code. The source of these warnings seems to be a deprecated constant "RT_SUBSCRIBER_NAME" in oracle.security.idm.providers.ovd.OVDIdenti

  • Importing existing classes loses package identity in 9.0.2

    I have tried several ways, but everytime I import existing classes, they all go to Miscellaneous Files and won't display under their packages. This is from disk or from source code control (CVS). This works fine with the same exact classes and direct

  • APs missing from WLC

    My customer who has one WLC4402,36 AP1130.Some of APs miss from WLC sometimes but I can ping those APs at this time.I can not find any messages from WLC(version 4.2.61).Any suggestions?

  • How to transfer PSE 12 from old computer to new computer

    I have a new subscription PSE 12 (Dec 2013) on my old computer which was too old and slow to operate PSE 12.  I bought a new computer and now would like to move my existing subscription of PSE 12  to my new computer,  I have the SN and order numbers.

  • Sharing Forms

    Is it possible to share / exchange locally stored forms with another account holder?