Start a new java process using Runtime.Exec() seems to ignore the -Xmx

I am working with a process that requires a minimum of 1.5 GB to run and works better if more is available.
So I am determining how much memory is available at startup and restarting the jre by calling
Runtime.exec("java -Dcom.sun.management.jmxremote=true -Xmx1500M -jar XXX.jar")
which reinvokes the same process with a new max memory size.
The initial call to the process is
java -Dcom.sun.management.jmxremote=true -Xmx3500M -jar XXX.jar
The initial call returns 3262251008 from Runtime.maxmemory()
When reinvoked through Runtime.exec() as above
Runtime.maxmemory() still returns 3262251008
Is there a way to separate the new process from the size specified by the parent process?

That is strange. Here is a program I wrote which calls itself recursively.
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.ArrayList;
import static java.util.Arrays.asList;
public class MemorySize {
    public static void main(String... args) throws IOException, InterruptedException {
        System.out.println("Maximum memory size= "+Runtime.getRuntime().maxMemory());
        if (args.length == 0) return;
        List<String> cmd = new ArrayList<String>();
        cmd.add("java");
        cmd.add("-cp");
        cmd.add(System.getProperty("java.class.path"));
        cmd.add("-Xmx"+args[0]+'m');
        cmd.add("MemorySize");
        cmd.addAll(asList(args).subList(1,args.length));
        Process p = new ProcessBuilder(cmd).start();
        readin(p.getErrorStream());
        readin(p.getInputStream());
    private static void readin(final InputStream in) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    byte[] bytes = new byte[1024];
                    int len;
                    while((len = in.read(bytes))>0)
                        System.out.write(bytes, 0, len);
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
        }).start();
}If you run this with the args 128 96 33 222 it prints out
Maximum memory size= 66650112
Maximum memory size= 133234688
Maximum memory size= 99942400
Maximum memory size= 35389440
Maximum memory size= 231014400

Similar Messages

  • Spawn a java process using runtime.exec() method

    Hi,
    This is my first post in this forum. I have a small problem. I am trying to spawn a java process using Runtime.getRuntime().exec() method in Solaris. However, there is no result in this check the follwoing program.
    /* Program Starts here */
    import java.io.*;
    public class Test {
    public static void main(String args[]) {
    String cmd[] = {"java", "-version"};
    Runtime runtime = Runtime.getRuntime();
    try{
    Process proc = runtime.exec(cmd);
    }catch(Exception ioException){
    ioException.printStackTrace();
    /* Program ends here */
    There is neither any exception nor any result.
    The result I am expecting is it should print the following:
    java version "1.4.0"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-b92)
    Java HotSpot(TM) Client VM (build 1.4.0-b92, mixed mode)
    Please help me out in this regard
    Thanks in advance
    Chotu.

    Yes your right. It is proc.getInputStream() or proc.getErrorStream(). That is what I get for trying to use my memory instead of looking it up. Though hopefully the OP would have seen the return type of the other methods and figured it out.

  • How to capture output of java files using Runtime.exec

    Hi guys,
    I'm trying to capture output of java files using Runtime.exec but I don't know how. I keep receiving error message "java.lang.NoClassDefFoundError:" but I don't know how to :(
    import java.io.*;
    public class CmdExec {
      public CmdExec() {
      public static void main(String argv[]){
         try {
         String line;
         Runtime rt = Runtime.getRuntime();
         String[] cmd = new String[2];
         cmd[0] = "javac";
         cmd[1] = "I:\\My Documents\\My file\\CSM\\CSM00\\SmartQ\\src\\E.java";
         Process proc = rt.exec(cmd);
         cmd = new String[2];
         cmd[0] = "javac";
         cmd[1] = "I:\\My Documents\\My file\\CSM\\CSM00\\SmartQ\\src\\E";
         proc = rt.exec(cmd);
         //BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
         BufferedReader input = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
         while ((line = input.readLine()) != null) {
            System.out.println(line);
         input.close();
        catch (Exception err) {
         err.printStackTrace();
    public class E {
        public static void main(String[] args) {
            System.out.println("hello world!!!!");
    }Please help :)

    Javapedia: Classpath
    How Classes are Found
    Setting the class path (Windows)
    Setting the class path (Solaris/Linux)
    Understanding the Java ClassLoader
    java -cp .;<any other directories or jars> YourClassNameYou get a NoClassDefFoundError message because the JVM (Java Virtual Machine) can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.
    javac -classpath .;<any additional jar files or directories> YourClassName.javaYou get a "cannot resolve symbol" message because the compiler can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.

  • Can we run a java application using Runtime.exec()?

    Can we run a java application using Runtime.exec()?
    If yes what should i use "java" or "javaw", and which way?
    r.exec("java","xyz.class");

    The best way to run the java application would be to dynamiically load it within the same JVM. Look thru the class "ClassLoader" and the "Class", "Method" etc...clases.
    The problem with exec is that it starts another JVM and moreover you dont have the interface where you can throw the Output directly.(indirectly it can be done by openong InputStreams bala blah............). I found this convenient. I am attaching part of my code for easy refernce.
    HIH
    ClassLoader cl = null;
    Class c = null;
    Class cArr[] ;
    Method md = null;
    Object mArr[];
    cl = ClassLoader.getSystemClassLoader();
    try{
         c = cl.loadClass(progName.substring(0,progName.indexOf(".class")) );
    } catch(ClassNotFoundException e) {
    System.out.println(e);
         cArr = new Class[1] ;
         try{
         cArr[0] = Class.forName("java.lang.Object");
         } catch(ClassNotFoundException e) {
         System.out.println(e);
         mArr = new Object[1];
         try{
         md = c.getMethod("processPkt", cArr);
         } catch(NoSuchMethodException e) {
         System.out.println(e);
         } catch(SecurityException e) {
         System.out.println(e);
    try {            
    processedPkt = md.invoke( null, mArr) ;
    } catch(IllegalAccessException e) {
              System.out.println(e);
    } catch(IllegalArgumentException e) {
              System.out.println(e);
    }catch(InvocationTargetException e) {
              System.out.println(e);
    }catch(NullPointerException e) {
              System.out.println(e);
    }catch(ExceptionInInitializerError e) {
              System.out.println(e);
    }

  • Socket stays open after java process exits, Runtime.exec()

    I have a program that does the following:
    opens a socket
    Does a runtime.exec() of another program
    then the main program exits.
    what i am seeing is, as long as the exec'd program is running, the socket remains open.
    What can i do to get the socket to close?
    I even tried to explicity call close() on it, and that didn't work. Any ideas would be great.
    I am running this on WindowsXP using netstat to monitor the port utilization.
    here is some sample code
    import java.io.*;
    import java.net.*;
    public class ForkTest
        public static void main(String[] args)
            try
                DatagramSocket s = new DatagramSocket(2006);
                Process p = Runtime.getRuntime().exec("notepad.exe");
                System.out.println("Press any key to exit");
                System.in.read();
            catch (IOException ex)
                ex.printStackTrace();
    }

    java.net.BindException: Address already in use: Cannot bind
            at java.net.PlainDatagramSocketImpl.bind(Native Method)
            at java.net.DatagramSocket.bind(DatagramSocket.java:368)
            at java.net.DatagramSocket.<init>(DatagramSocket.java:210)
            at java.net.DatagramSocket.<init>(DatagramSocket.java:261)
            at java.net.DatagramSocket.<init>(DatagramSocket.java:234)
            at ForkTest.main(ForkTest.java:11)

  • Invoking "java myClass" using Runtime.Exec from a Java Stored Procedure

    Hi All,
    This is regarding the use of Runtime.getRunTime().exec, from a java programme (a Java Stored Procedure), to invoke another Java Class in command prompt.
    I have read many threads here where people have been successuful in invoking OS calls, like any .exe file or batch file etc, from withing Java using the Runtime object.
    Even i have tried a sample java programme from where i can invoke notepad.exe.
    But i want to invoke another command prompt and run a java class, basically in this format:
    {"cmd.exe","java myClass"}.
    When i run my java programme (in command prompt), it doesnt invoke another command prompt...it just stays hanging.
    When i run the java programme from my IDE, VisualCafe, it does open up a command prompt, but doesnt get the second command "java myCLass".
    Infact on the title of the command prompt (the blue frame), shows the path of the java.exe of the Visual Cafe.
    and anyway, it doesnt run my java class, that i have specified inside the programme.
    Even if i try to run a JAR file, it still doesnt do anything.
    (the JAR file other wise runs fine when i manually invoke it from the command prompt).
    Well, my question is, actually i want to do this from a Java Stored Procedure inside oracle 8.1.7.
    My feeling is, since the Java Stored Procedure wont be running from the command prompt (i will be actually invoking it through a Oracle trigger), it may be able to invoke the command prompt and run the java class i want. and that java class has to run with the SUn's Java, not Oracle JAva.
    Does any one have any idea about it?
    Has anyone ever invoked a java class or JAR file in command prompt from another Java Programme?
    YOur help will be highly appreciated.
    (P:S- Right now, my database is being upgraded, so i havent actually been able to create a Java Stored procedure and test it. But i have tested from a normal java programme running in command prompt and also from Visual Cafe).
    Thanks in advance.
    -- Subhasree.

    Hello Hari,
    Thanks for your quick reply.
    Can you please elaborate a little more on exactly how you did? may be just copy an dpaste taht part of teh code here?
    Thanks a lot in advance.
    --Subhasree                                                                                                                                                                                                                                                                                                                                                                                                           

  • Problem of executing a process under Linux using Runtime.exec

    Hi, All
    I am having a problem of executing a process under Linux and looking for help.
    I have a simple C program, which just opens a listening port, accept connection request and receive data. What I did is:
    1. I create a script to start this C program
    2. I write a simple java application using Runtime.exec to execute this script
    I can see this C program is started, and it is doing what it supposed to do, opening a listening port, accepting connection request from client and receiving data from client. But if I stop the Java application, then this C program will die when any incoming data or connection request happens. There is nothing wrong with the C program and the script, because if I manually execute this script, everying works fine.
    I am using jre1.4.2_07 and running under Linux fedora 3.0.
    Then I tried similar thing under Windows XP with service pack2, evrything works OK, the C program doesn't die at all.

    Mind reading is not an exact science but I bet that you are not processing either the process stdout or the stderr stream properly. Have you read http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html ?

  • Issue using Runtime.exec() to export a DB

    hi ,
    i'm trying to write a piece of code to export an oracle DB using Runtime.exec(). I searched the forums and came up a with a piece of code , modified it a bit .The issue is the system sometimes hangs while executing the code , it's like the proc.waitFor() never returns. However the execution is error-free if using a command like 'shutdown' instead of 'exp' .
    this is my main
    public class DBExporter
               * @param args
              public static void main(String[] args)
                        try
                                  StreamReaderThread outReaderThread = new StreamReaderThread();
                                  StreamReaderThread errReaderThread = new StreamReaderThread();
                                  //StreamReaderThread ww = new StreamReaderThread();
                                  Runtime rt = Runtime.getRuntime();
                                  outReaderThread.start();
                                  errReaderThread.start();
                                  String command = "exp beta/beta@frsp_dbS file=\"c:/shop.dmp\" full=\"N\" ";
                                  //command = "shutdown -s";
                                  Process proc = rt.exec(command);
                                  outReaderThread.setInputStream(proc.getInputStream());
                                  errReaderThread.setInputStream(proc.getErrorStream());
                                  //ww.setOutputStream(proc.getOutputStream());
                                  System.out.println(proc.waitFor());
                                  proc.getInputStream().close();
                                  proc.getErrorStream().close();
                                  proc.getOutputStream().close();
                        catch (Exception e)
                                  e.printStackTrace();
         }and this is the reader class
    import java.io.BufferedWriter;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    *@deprecated
    public class StreamReaderThread extends Thread
         private BufferedReader     br;
         private BufferedWriter     bw;
         private StringBuffer     sb;
         private String               newline;
         private String               line;
         public StreamReaderThread()
              br = null;
              sb = null;
              newline = null;
              line = null;
         public synchronized String getText()
              if( sb == null )
                   return "";
              return sb.toString();
         private boolean     flag     = false;
         public synchronized void setInputStream( InputStream is )
              br = new BufferedReader(new InputStreamReader(is));
              flag = true;
         public synchronized void setOutputStream( OutputStream is )
                   bw = new BufferedWriter(new OutputStreamWriter(is));
                   flag = true;
         public synchronized void run()
              int i = 0;
              try
                   while( !flag )
                        wait();
                   flag = false;
                   while( (line = br.readLine()) != null )
                        try
                             if( sb == null )
                                  sb = new StringBuffer();
                                  newline = System.getProperty("line.separator");
                             else
                                  sb.append(newline);
                             sb.append(line);
                        catch( Exception e )
                             e.printStackTrace();
                        i++;
                        if( br == null )
                             break;
              catch( IOException ex )
                   ex.printStackTrace();
              catch( InterruptedException ex )
                   ex.printStackTrace();
    }

    Looks like a bug in StreamReaderThread. I can't see that it ever exits the wait() call since no one is calling notify or notify all.
    Kaj

  • Opening a new browser using Runtime.exec()...

    I am trying to open a new IE browser window (from Windows) using Runtime.exec( ) command. The problem is that it uses the existing browser window instead of opening a new window. (opens a new window only if there isn't any other browser window)
    Here is the snippet of code that I am using to do this:
    String WIN_PATH = "rundll32";
    String WIN_FLAG = "url.dll,FileProtocolHandler";
    String url = "http://www.cnn.com";
    String cmd = WIN_PATH + " " + WIN_FLAG + " " + url;
    Process p = Runtime.getRuntime().exec(cmd);
    Thanks in advance.
    -Kishore

    >
    opening browser window seems to be easy task, >Even easier with [Desktop.browse(URI)|http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html#browse(java.net.URI)].
    >
    ..can someone help me with closing browser window from java?>Which browser window?
    If you're app. opens a page that you control, it can be done from the web page. See [Have a Java button close the browser window|http://www.rgagnon.com/javadetails/java-0282.html] or the JS based [Close the browser|http://www.rgagnon.com/jsdetails/js-0079.html].
    If you do not control the page, don't close it - the user knows where the little 'x' button is.
    As an aside, despite being opposite ends of the one question, I do not consider this question to be 'part' of the current thread. I think you would have been better off starting a dedicated thread and explaining more fully what the use case is (and adding lots of Dukes).

  • 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?

  • Using runtime.exec,process streams

    Hi all,
    I am using runtime.exec to execute a batch file(rmdir /s/q directoryname) which deletes all the files in a certain directory(including subdirectories). However, some of the files are not deleted since they are being used by other processes.
    I have closed all file references but still the batch file says they are being used by other processes. The File.canWrite() method however, returns true for all the files. I have also tried to delete the files using file.delete but it does not work.
    So I have 2 questions.
    1. Can I forcibly delete these files some other way.
    2. If i call a batch file to delete the files and it fails on some files, the command window displays "cannot delete files". How can I write out thse messages into a text file which i can use as a log file.Do I have to use Process.getInputstream()/Process.getInputstream() ? If so, how?
    Thanks for your help.
    Vinny

    I tried the following before but the string i get is always empty, but i can see there are messages in the command window. Please let me now if i am doing something wrong.
    try{
    Process p = rt.exec("cmd.exe /c start deletefiles.bat");
    InputStream ins = p.getInputStream();
    byte[] bytearray = new byte[1024];
    int bytecount;
    String dos_string="";
    BufferedInputStream bis = new BufferedInputStream(ins);
    while ((bytecount = bis.read(bytearray, 0, 1024)) > -1) {
    String str = new String(bytearray,0,bytecount);
    dos_string += str;
    System.out.println("dos string is" +dos_string);
    catch (Exception e) {
    System.out.println("Error: " + e);

  • Using Runtime exec() to open java on other directory

    HI, I have a little problem and i hope everyone can help me out abit. You see when u use Runtime.exec(), how to you use it so that when the file you want to open is different from your program directory.
    For example,
    my program is in c:\windows\desktop
    but the file i want to open eg. Somthing.class is in c:\my documents\
    How do I open it using java and i wish to open the file using the java command. Thank a million

    Runtime.getRuntime().exec("cmd /c start /d\"C:\\my documents\" java.exe Somthing");
    Can someone explain the /c start /d\"C:\Mydocuments\" java.exe Somthing.
    And I try to use ping in RunTime.exec,how do I construct the string?And how do i get the result of the ping?
    Thanks

  • Monitoring a Process using Runtime.exce()

    Hi,
    In my Program, I'm using the
    new BufferedReader(new InputStreamReader(Runtime.getRuntime()                         .exec("ps -ef | grep xmlfeed").getInputStream()));
    The above statement is not returning any inputstream to the BuffredReader.
    When I gave the command as "PWD", it's returning the lines as expected.
    But it's not working even for "PS" command also.I'm running this in AIX machine.
    Any Ideas,Please help....
    Edited by: haijdp on Dec 21, 2007 1:11 AM

    Hello! And sorry I didn't reply earlier. I hope the Original Poster will find revisit this thread and it helps him.
    From your post I assumed that you were not a student trying to create some homework. That's why I felt free to simply code a solution and submit the code here. But first some remarks:
    I don't think that your code can work. Runtime.exec expects an array of type String, where the first element is the command and subsequent elements are a command line option each. I don't think you can use the pipe and call several commands using Runtime.exec, but that's just a kind of guess. YMMV.
    Running external Processes in Java is a bit complicated. Basically,
    * It's good to run the process in it's own thread. That way the main program can continue without getting stuck.
    * To extract stdout and stderr of your target process you must run two threads, one for stderr and one for stdout. Both threads extract the characters of their respective streams in a loop that runs inside the thread. Again, that way we avoid deadlocks, program getting stuck etc.
    This explanation is terrible, I know - I think a slice of source code speaks louder than words. I have attached five java files which together make a little process runner which extracts stdout and stderr in a safe manner. To run:
    * Cut'n paste them into five text files, one per class.
    * Save the each text file as {contained-class-name}.java
    * Compile the stuff
    * Run RunnerDemo (When I ran it, I got a directory listing printed on the console)
    Explanation sounds a bit sloppy, but I did it under the assumption that you are a seasoned java pro, so it should not pose any problems. Since you seem to be a different OS than I (AIX, I run Linux), the command may or may not work. Try other commands. For example, in the RunnerDemo class you could set the cmd field to this:
            String [] cmd =
                "ps",
                "-A",
                "-H"
            };This would give you a process listing (works on Linux).
    By the way, commands are passed as array. See Java documentation for java.lang.Runtime.exec (String []) for explanation of this array.
    One problem I see in your command is that the output of ps is piped to some other program. Sorry, I don't know whether my code could achieve this. All it can do is to rum one single command with command line options. But you should be able to adjust the given example, so it supports piping to another program.
    If you have any further questions, please don't hesitate to ask!
    Class: RunnerDemo
    *                           RunnerDemo.java
    *                     Demo for the process runner
    package rtimeexec;
    public class RunnerDemo
        public static void main (String [] args)
            String [] cmd =
                "ls",
                "-a",
                "-l"
            ProcessRunner   runner;
            String          stdOutStr;
            String          stdErrStr;
            runner = new ProcessRunner (cmd);
            runner.start ();
            runner.BlockUntilFinished ();
            stdOutStr = runner.GetStdOutText ();
            stdErrStr = runner.GetStdErrText ();
            System.out.println ("Process result, ls -a -l");
            System.out.println ("-----------------------------------------------------------------------");
            System.out.println ("Stdout:");
            System.out.println ("-----------------------------------------------------------------------");
            System.out.println (stdOutStr);
            System.out.println ();
            System.out.println ("-----------------------------------------------------------------------");
            System.out.println ("Stderr:");
            System.out.println ("-----------------------------------------------------------------------");
            System.out.println (stdErrStr);
    Class: ProcessRunner
    package rtimeexec;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    * Runs a system process and extracts stdout and stderr of that process.
    * Process will run in its own thread, so that the caller can simply continue
    * with less of a chance to get locked down. Caller can invoke the {@link BlockUntilFinished}
    * method after starting this thread. This method blocks until the thread is finished,
    * i.e. the process has finished.
    * Unfortunately, we haven't implemented any facility to stream characters to
    * stdin of the process called. If that facility would exist we could refactor
    * the classes and realize some sort of piping facility, as it's possible in
    * Linux, for example.
    * Example on how to run a process:
    * <pre>
    * String []         cmd  = {"ps", "-AH"};
    * String            sOut;
    * String            sErr;
    * ProcessRunner     runner;
    * runner = new ProcessRunner (cmd);
    * runner.start ();
    * runner.BlockUntilFinished ();
    * sOut = runner.GetStdOutText ();
    * sErr = runner.GetStdErrText ();
    * System.out.println ("Stdout:");
    * System.out.println (sOut);
    * System.out.println ("------------------------------------------------------");
    * System.out.println ("Stderr:");
    * System.out.println (sErr);
    * </pre>
    public class ProcessRunner extends Thread
        private String []                   command;
        private int                         execResult;
        private String                      stdOutText;
        private String                      stdErrText;
        private boolean                     isFinished;
        public ProcessRunner (String [] cmd)
            command     = cmd;
            execResult  = 0;
            stdOutText  = null;
            stdErrText  = null;
            isFinished  = false;
        public int GetResult ()
            return execResult;
        public String GetStdOutText ()
            return stdOutText;
        public String GetStdErrText ()
            return stdErrText;
        public boolean IsFinished ()
            return isFinished;
        public void BlockUntilFinished ()
            while (! isFinished)
                try {Thread.sleep (250);} catch (InterruptedException e) {}
        public void run ()
            Process         proc;
            Runtime         rt;
            InputStream     stdOut;
            InputStream     stdErr;
            CharStream      stdOutEx;
            CharStream      stdErrEx;
            int             res;
            isFinished = false;
            try
                res         = 0;
                rt          = Runtime.getRuntime ;       ();
                proc        = rt.exec ;                  (command);
                stdOut      = proc.getInputStream ;      ();
                stdErr      = proc.getErrorStream ;      ();
                stdOutEx    = new CharStream            (stdOut);
                stdErrEx    = new CharStream            (stdErr);
                stdOutEx.start ();
                stdErrEx.start ();
                try {res = proc.waitFor ();} catch (InterruptedException e) {}
                // Process has finished; now wait until any buffers are empty.
                stdOutEx.BlockUntilFinished ();
                stdErrEx.BlockUntilFinished ();
                stdOutText = stdOutEx.GetResult ();
                stdErrText = stdErrEx.GetResult ();
                execResult = res;
            catch (IOException e)
                isFinished = true;
                throw new ExtractionException (e.getLocalizedMessage());
            isFinished = true;
    Class: CharStream
    package rtimeexec;
    import java.io.IOException;
    import java.io.InputStream;
    * A Character extractor. Extracts characters from a stream and puts them
    * into a String. To protect from memory overflow we put a limit in place.
    * When storage demads exceed that limit, an exception is thrown.
    public class CharStream extends Thread
        private static final int    maxChunkLen         = 8192;
        private static final int    maxStorageSize      = 512 * 1024;   // 512 KBytes
        private InputStream     sourceStream;
        private StringBuffer    extracted;
        private boolean         isFinished;
        public CharStream (InputStream istream)
            sourceStream    = istream;
            extracted       = new StringBuffer ();
            isFinished      = false;
        public String GetResult ()
            String ret;
            ret = extracted.toString ();
            return ret;
        public void BlockUntilFinished ()
            while (! isFinished)
                SleepThread (250);
        public void run ()
            byte []                 buffer;
            int                     nBytesRead;
            byte                    b;
            char                    c;
            int                     iChar;
            int                     nCharsTotal;
            boolean                 isEOF;
            isEOF       = false;
            nCharsTotal = 0;
            isFinished = false;
            while (! isEOF)
                try
                    buffer      = new byte [maxChunkLen];
                    nBytesRead  = sourceStream.read (buffer);
                    if (nBytesRead >= 1)
                    {   // much faster stream extraction method than when we use
                        // BufferedReader(new InputStreamReader(sourceStream)).
                        for (iChar = 0; iChar < nBytesRead; iChar++)
                            nCharsTotal++;
                            if (nCharsTotal > maxStorageSize)
                                throw new StoreFullException
                                    "Storage limit exceeded (" + Integer.toString (maxChunkLen) + "Bytes)"
                            b = buffer [iChar];
                            c = (char) b;
                            extracted.append (c);
                    else if (nBytesRead <= -1)
                        isEOF       = true;
                catch (IOException e)
                    isFinished = true;
                    throw new ExtractionException (e.getLocalizedMessage());
                SleepThread (250);
            isFinished  = true;
        private void SleepThread (int mSec)
            try
                Thread.sleep (mSec);
            catch (InterruptedException e)
    Class: StoreFullException
    package rtimeexec;
    * Exception that gets thrown when a storage container is full.
    public class StoreFullException extends RuntimeException
        private static final long serialVersionUID = - 4996246591135389009L;
        public StoreFullException (String message)
            super (message);
    Class: ExtractionException
    package rtimeexec;
    * Thrown when there was some problem during stream extraction.
    public class ExtractionException extends RuntimeException
        private static final long serialVersionUID = - 6124525536783450209L;
        public ExtractionException (String message)
            super (message);
    }

  • Issue using Runtime.exec() in Vista

    I've coded a simple method using Runtime.exec() to get the client MAC ID , and it worked alright on XP. Now my client want to switch to vista , and the method is not working. Here's my code
    import java.io.*;
    import java.util.regex.*;
    public class GetMac
         public static String getMacAddress()
              String mac="";
              System.out.println("getMacAddress");
              try {
                   RunTimeExecutor re=new RunTimeExecutor("ipconfig /all");
                    mac=re.executeAndReturnMac();
                    re.destroy();
              } catch (Exception e) {
                   e.printStackTrace();
              return mac;
    import java.io.IOException;
    import java.io.InputStream;
    * @author amal
    public class RunTimeExecutor
              String cmd;
              Process proc;
               * @param cmd
              public RunTimeExecutor(String cmd)
                        this.cmd=cmd;
               * @return boolean
               * @throws WIException
              public  String executeAndReturnMac() throws Exception
                   System.out.println("run");
                   String mac="";
                        if(cmd==null)
                                  throw new Exception("No Commands");
                        try
                              final Runtime rt = Runtime.getRuntime();
                              proc = rt.exec(cmd);
                              final StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream());
                              InputStream iis=proc.getInputStream();
                              final StreamGobbler outputGobbler = new StreamGobbler(iis);
                              errorGobbler.start();
                              outputGobbler.start();
                              int exit=proc.waitFor();
                              System.out.println("exitVAl "+exit);
                              if(exit==0)
                                   mac=outputGobbler.MAC;
                              return (exit==0) ? mac :null;
                    catch (IOException e)
                              e.printStackTrace();
                    catch (InterruptedException e)
                              e.printStackTrace();
                    catch(Exception e)
                         e.printStackTrace();
                    return null;
              public void destroy()
                        if(proc!=null )
                                  proc.destroy();
    * @author amal
    import java.io.*;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    * @author amal
    public class StreamGobbler extends Thread
        InputStream is;
        OutputStream os;
        public String MAC;
        StreamGobbler(InputStream is)
            this(is,null);
        StreamGobbler(InputStream is,OutputStream redirectTo)
            this.is = is;
            this.os = redirectTo;
         * @see java.lang.Thread#run()
        public void run()
            try
                PrintWriter pw = null;
                if (os != null)
                    pw = new PrintWriter(os);
                InputStreamReader isr = new InputStreamReader(is);
                int c=0;
                BufferedReader br = new BufferedReader(isr);
                String line=null;
    System.out.println("Start Reading");
                     while ( (line = br.readLine()) != null)
                          System.out.println(line);
                         if (pw != null)
                             pw.println(line);
                         Pattern p = Pattern.compile(".*Physical Address.*: (.*)");
                            Matcher m = p.matcher(line);
                            if (m.matches())
                                 MAC = m.group(1);
                                 System.out.println("seting MAC to "+MAC);
                                 break;
                if (pw != null)
                    pw.flush();
            } catch (Exception e)
                e.printStackTrace(); 
    }The inputStream of the process doesnt get printed at all , the loop condition in StreamGobbler 'while ( (line = br.readLine()) != null)
    ' is never true.
    Also , in random cases i've seen the System.out.println("exitVAl "+exit); line executing before the System.out.println("Start Reading"); line , and i though proc.waitFor() would guarentee otherwise.

    thx guys for ur replies . The issue was because of some browser security system ( or so they said . ).However i'm still puzzled about the 'waiting for the stream to finish' part .
    paul.miner wrote:
    {I think the process is allowed to end with output still in the >>buffers, ..so this would be expected. You should be waiting for >>your .streams to finish, since that's what you really >>care .about. .Also, .you need to add synchronization between your >>threads so you can accurately retrieve "MAC". Also, do not break out >>of the loop when you find what you're looking for, you should >>continue .reading until the end of the stream.Wasn't I suppose to be reading out of the stream to prevent an overflow?Also the break is done there are multiple lines like 'Physical address .....: xxxxxxxxxx ' in the output , and the macid is the first one.About the ProcessBuilder , I'll look into it . Thx for your advice.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Why couldn't I use Runtime.exec(cmd)?

    I try to use Runtime.exec(cmd) but I can't do it. Could you give me a sample that use Runtime.exe(cmd).
    Please help me!

    import java.io.*;
    class RuntimeExec{
         private static boolean quit;
         public static void main(String[]args)throws IOException{
              if(args.length<1){
                   System.out.println("Type in program to run");
                   System.exit(1);
              quit = false;
              Runtime run = Runtime.getRuntime();
              Process newProcess = run.exec(args[0]);
              if(newProcess!=null){
                   BufferedReader br = new BufferedReader(new InputStreamReader(newProcess.getInputStream()));
                   PrintWriter os = new PrintWriter(newProcess.getOutputStream());
                   BufferedReader be = new BufferedReader(new InputStreamReader(newProcess.getErrorStream()));
                   if(br!=null)(new ReadThread(br)).start();
                   if(os!=null)(new WriteThread(os)).start();
                   if(be!=null)(new ErrorThread(be)).start();
                   try{
                        newProcess.waitFor();
                        newProcess.destroy();
                        quit = true;
                   }catch(InterruptedException ie){}
              }else
                   System.out.println("Error creating process");
              System.out.println("Done!");
              System.exit(0);     
         private static class ReadThread extends Thread{
              private BufferedReader is;
              public ReadThread(BufferedReader is){
                   this.is = is;
              public void run(){
                   String s;
                   while(!quit){
                        try{
                             s=is.readLine();
                             if(s!=null)
                             System.out.println(s);
                        }catch(IOException e){}
         private static class WriteThread extends Thread{
              private PrintWriter br;
              private BufferedReader ss;
              public WriteThread(PrintWriter br){
                   this.br = br;
                   ss = new BufferedReader(new InputStreamReader(System.in));
              public void run(){
                   String s;
                   while(!quit){
                        try{
                             s=ss.readLine();
                             if(s!=null)
                             br.println(s);
                        }catch(IOException e){}
         private static class ErrorThread extends Thread{
              private BufferedReader br;
              public ErrorThread(BufferedReader br){
                   this.br = br;
              public void run(){
                   while(!quit){
                        String s;
                        try{
                             s=br.readLine();
                             if(s!=null)
                             System.err.println(s);
                        }catch(IOException e){}
    Sorry about that stupid code, here is code that works... with deadlocks maybe??

Maybe you are looking for

  • How to get the present And Absent for Empoyee for any date..

    Hi Experts, I have a requirement to find the present and absecnt of  any PERNR  value from Infotype 2002 in the  Program For a particular Date..

  • Is there a way for an EJB to know who is calling it?

    Hi, I am wondering if an EJB could figure out the host machine and user which is invoking it. From a servlet, we could get those from the HTTP request getRemoteUser() call but could we figure those out within the EJB? Thanks in advance

  • Red Giant Trapcode plugins no longer work after updating to Premiere Pro CC 2014.1 (v8.1)

    I'm not sure why but after updating Premiere Pro CC to 2014.1 none of my previously installed Trapcode plugins work. I tried uninstalling Trapcode and then re-installing the latest Trapcode update (12.1.6) but it didn't fix the problem. I'm also runn

  • Smartform runtime error

    hi,     when i am executing the smartform a runtime error is raised in function module SSFCOMP_GENERATE_SMART_FORM and the error is err_comp ssf_err_main_width_changed 'A' 080 can anyone tell what is the error its throwing ?

  • Result row won't summarize

    Hi all, I have a report where I have column A, B, C and D. They all consists of formulas. The problem is in the overall result row (or the top node in a hierarchy). For column A and B I want the result row to use the formulas and this works fine. But