KickJava   Java API By Example, From Geeks To Geeks.

Java > Java SE, EE, ME > java > lang > Runtime

java.lang
Class Runtime

java.lang.Object
  extended by java.lang.Runtime
See Also:
Top Examples, Source Code, getRuntime()

public void addShutdownHook(Thread hook)
See Also:
exit(int), halt(int), removeShutdownHook(java.lang.Thread), RuntimePermission, SecurityException, IllegalStateException, IllegalArgumentException, System.err, ThreadGroup, uncaughtException, System.exit
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[58]ShutdownHook example
By Anonymous on 2004/03/09 06:20:30  Rate
import java.io.*; 
  
  
 public class ShutdownDemo  {  
  
  
 private FileWriter fw_log; 
 private BufferedWriter bw_log; 
  
  
 // constructor that opens the log file 
  
  
 public ShutdownDemo (  )  throws IOException  {  
     fw_log = new FileWriter ( "log.txt" ) ; 
     bw_log = new BufferedWriter ( fw_log ) ; 
  
  
     // register the shutdown hook 
  
  
     Runtime.getRuntime (  ) .addShutdownHook ( new Thread (  )   {  
   public void run (  )   {  
       endApp (  ) ; 
    }  
      }  ) ;; 
  }  
  
  
 // do some application processing and write to the log file 
  
  
 public void processApp1 (  )  throws IOException  {  
     bw_log.write ( "testing" ) ; 
     bw_log.newLine (  ) ; 
  }  
  
  
 // do some application processing resulting in an exception 
  
  
 public void processApp2 (  )   {  
     throw new RuntimeException (  ) ; 
  }  
  
  
 // close the log file 
  
  
 public void endApp (  )   {  
     try  {  
   bw_log.close (  ) ; 
      }  
     catch  ( IOException e )   {  
   System.err.println ( e ) ; 
      }  
  }  
  
  
 public static void main ( String args [  ]  )  throws IOException  {  
  
  
     // create an application object 
  
  
     ShutdownDemo demo = new ShutdownDemo (  ) ; 
  
  
     // do some processing 
  
  
     demo.processApp1 (  ) ; 
  
  
     // do some more processing that results in an exception 
  
  
     demo.processApp2 (  ) ; 
  }  
  }  
 


[1878]Writing Java shutdown hooks
By Anonymous on 2007/05/03 10:41:29  Rate
Shutdown hooks are a Java feature that let you have a piece of Java code run whenever the JVM terminates under one of the following conditions: 
  
  
 *The program exits normally, such as when the last non-daemon thread exits or when the Runtime.exit (  )  method is invoked.  
 *The virtual machine is terminated in response to a user interrupt, such as typing CTRL-C, or a system-wide event, such as user logoff or system shutdown  ( for example, the JVM receives one of the interrupt signals SIGHUP  ( Unix Only ) , SIGINT, or SIGTERM ) .  
  
  
 Shutdown hooks will not be run if 
 *Runtime.halt (  )  method is called to terminate the JVM. Runtime.halt (  )  is provided to allow a quick shutdown of the JVM.  
 *The -Xrs JVM option is specified.  
 *The JVM exits abnormally, such as an exception condition or forced abort generated by the JVM software.  
  
  
 A shutdown hook is a Java class that extends java.lang.Thread and is installed with the Runtime.addShutdownHook (  )  method. Your application may install multiple shutdown hooks. On JVM termination, each shutdown hook will be started and will run concurrently, so the normal rules of thread synchronization apply. You can write shutdown hooks to do anything that a normal thread would do; the JVM will treat them like any other. Generally we write a shutdown hook to do any last-minute tidying, such as flushing memory buffers, closing files, or displaying an exit message. The JVM will always wait until all shutdown hooks have completed before continuing with the rest of the shutdown sequence, so it is important that your shutdown hooks do actually complete. 
  
  
 The following example shows how to write and install a Java shutdown hook. 
  
  
 class ExampleShutdownHook  {  
     public static void main ( String [  ]  args )   {  
         // Java code to install shutdown hook: MyShutdown 
         MyShutdown sh = new MyShutdown (  ) ; 
         Runtime.getRuntime (  ) .addShutdownHook ( sh ) ; 
      }  
  }  
  
  
 // Example shutdown hook class 
 class MyShutdown extends Thread  {  
     public void run (  )   {  
         System.out.println ( "MyShutdown hook called" ) ; 
      }  
  }  
  
  
 If at any time during the application you decide the shutdown hook is no longer required, it can be removed with the Runtime.removeShutdownHook (  )  method,  ( or Runtime.getRuntime (  ) .removeShutdownHook ( sh ) ; for the above shutdown hook example ) .  
  
  
 


public int availableProcessors()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[460]Get number of available processors
By Neelkanta on 2004/09/06 09:45:38  Rate
import java.lang.*; 
  
  
 public class ProcessorNumber 
  {  
    public static void main ( String args [  ]  )  
     {  
    System.out.println ( Runtime.getRuntime (  ) .availableProcessors (  )  ) ; 
     }  
  } 


public Process exec(String command)
             throws IOException
See Also:
ProcessBuilder, exec(String[], String[], File), IllegalArgumentException, NullPointerException, checkExec, SecurityException, exec
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[631]Run Microsoft Excel
By orina { at } telkom { dot } net on 2004/01/29 15:47:23  Rate
  Runtime run = Runtime.getRuntime (  ) ; 
   try {  
            run.exec ( "C:\\Program Files\\Microsoft Office\\Office\\excel.exe" ) ; 
      } catch ( IOException ie )  
      {  
       System.err.println ( ie ) ; 
      }  
    }  
 


[1347]Execute a commad and get the return value
By shamaz on 2005/04/26 10:25:59  Rate
public static final int ERROR_CODE = -1; 
  
  
 // this function execute a commad and get the return value. 
  
  
     public static int execute ( String command, boolean throwsErrors )  throws IOException, InterruptedException 
      {  
         Runtime run = Runtime.getRuntime (  ) ; 
         Process p = null; 
  
  
         try 
          {  
             p = run.exec ( command ) ; 
             p.waitFor (  ) ; 
          }  
         catch ( IOException ioe )  
          {  
             if  ( throwsErrors )  
                throw ( ioe ) ; 
             System.err.println ( ioe ) ; 
             System.err.println ( "There was an IO error while executing:" ) ; 
             System.err.println ( command ) ; 
             return ERROR_CODE; 
          }  
         catch ( InterruptedException ie )  
          {  
             if  ( throwsErrors )  
                throw ( ie ) ; 
             System.err.println ( command+" was interrupted\n"+ie ) ; 
             return ERROR_CODE; 
          }  
          
         return p.exitValue (  ) ; 
      } 


public Process exec(String command,
                    String[] envp)
             throws IOException
See Also:
ProcessBuilder, exec(String[], String[], File), IllegalArgumentException, NullPointerException, checkExec, SecurityException, exec
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[1809]Start a Dial-up connection on the Win plateform
By Anonymous on 2006/08/23 12:23:16  Rate
public class Dialup  {  
    public static void main ( String [  ]  args )  throws Exception  {  
      Process p = Runtime.getRuntime (  ) .exec ( "rundll32.exe rnaui.dll,RnaDial MyConnection" ) ; 
      p.waitFor (  ) ; 
      System.out.println ( "Done." ) ; 
       }  
     } 


[1813]Execute Execute VB Script
By Anonymous on 2006/08/23 12:27:30  Rate
// Win9x 
 Runtime.getRuntime (  ) .exec ( "start myscript.vbs" ) ; 
  
  
 // WinNT 
 Runtime.getRuntime (  ) .exec ( "cmd /c start myscript.vbs" ) ;


[1820]Cure for Winsock errors in child process
By Anonymous on 2006/09/19 08:35:31  Rate
If a process you create requires Winsock usage, you may find it will fail with the error number 10106. 
  
  
 This is caused because Winsock requires the "SystemRoot" environmental variable to be set to your root Windows directory  ( usually C:\WINNT or C:\WINDOWS ) 


public Process exec(String command,
                    String[] envp,
                    File dir)
             throws IOException
See Also:
ProcessBuilder, IllegalArgumentException, NullPointerException, checkExec, SecurityException, StringTokenizer, exec
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Process exec(String[] cmdarray)
             throws IOException
See Also:
ProcessBuilder, IndexOutOfBoundsException, NullPointerException, checkExec, SecurityException, exec
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[617]Send mail from shell
By Anonymous on 2004/05/10 08:49:47  Rate
try  {  
     String command = "/bin/echo"; 
     command += " 'FirstLine\nSecond Line'"; 
     command +=" | /usr/bin/mail"; 
     command +=" -a 'From: someone'"; 
     command +=" -s 'Subject'"; 
     command +=" mail@somewhere.com"; 
     Process send = Runtime.getRuntime (  ) .exec ( new String [  ]   { "/bin/sh","-c",command  }  ) ; 
  }  catch  ( IOException e )   {  
     System.out.println ( e.toString (  )  ) ; 
  }  
 


[1810]Launch a Unix script
By Anonymous on 2006/08/23 12:23:52  Rate
String [  ]  cmd =  { "/bin/sh", "-c", "ls  >  hello" } ; 
 Runtime.getRuntime (  ) .exec ( cmd ) ;


public Process exec(String[] cmdarray,
                    String[] envp)
             throws IOException
See Also:
ProcessBuilder, IndexOutOfBoundsException, NullPointerException, checkExec, SecurityException, exec
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[1814]Run any program using the Windows file association mechanism
By Anonymous on 2006/08/23 12:28:10  Rate
Runtime.getRuntime (  ) .exec 
    ( "rundll32 SHELL32.DLL,ShellExec_RunDLL " + file.getAbsolutePath (  )  ) ;


public Process exec(String[] cmdarray,
                    String[] envp,
                    File dir)
             throws IOException
See Also:
ProcessBuilder, IndexOutOfBoundsException, NullPointerException, checkExec, SecurityException, ProcessBuilder.start()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[1811]Execute external program with arguments
By Anonymous on 2006/08/23 12:25:31  Rate
If you need to pass arguments, it's safer to a String array especially if they contain spaces. 
  
  
 String [  ]  cmd =  {  "myProgram.exe", "-o=This is an option"  } ; 
 Runtime.getRuntime (  ) .exec ( cmd ) ;


[1812]Open a PDF file in Windows and Mac
By Anonymous on 2006/08/23 12:26:47  Rate
Windows only 
 ============ 
 public class ShowPDF  {  
    public static void main ( String [  ]  args )  throws Exception  {  
      Process p = Runtime.getRuntime (  ) .exec ( "rundll32 url.dll,FileProtocolHandler mypdf.pdf" ) ; 
      p.waitFor (  ) ; 
      System.out.println ( "Done." ) ; 
       }  
     }  
  
  
 Mac only 
 ======== 
 public class ShowPDF  {  
   public static void main  ( String [  ]  args )  throws Exception {  
     Process p = Runtime.getRuntime (  ) .exec ( "open /Documents/mypdf.pdf" ) ; 
    }  
  } 


public void exit(int status)
See Also:
halt(int), runFinalizersOnExit(boolean), removeShutdownHook(java.lang.Thread), addShutdownHook(java.lang.Thread), SecurityManager.checkExit(int), SecurityException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public long freeMemory()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public void gc()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


@Deprecated
public InputStream getLocalizedInputStream(InputStream in)
See Also:
InputStreamReader.InputStreamReader(java.io.InputStream), BufferedReader.BufferedReader(java.io.Reader)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


@Deprecated
public OutputStream getLocalizedOutputStream(OutputStream out)
See Also:
PrintWriter.PrintWriter(java.io.OutputStream), OutputStreamWriter.OutputStreamWriter(java.io.OutputStream), BufferedWriter.BufferedWriter(java.io.Writer)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public static Runtime getRuntime()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public void halt(int status)
See Also:
removeShutdownHook(java.lang.Thread), addShutdownHook(java.lang.Thread), exit(int), checkExit, SecurityException, System.exit
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public void load(String filename)
See Also:
SecurityManager.checkLink(java.lang.String), SecurityException, getRuntime(), NullPointerException, UnsatisfiedLinkError, loadLibrary(String)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public void loadLibrary(String libname)
See Also:
SecurityManager.checkLink(java.lang.String), SecurityException, NullPointerException, UnsatisfiedLinkError
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public long maxMemory()
See Also:
Long.MAX_VALUE
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[480]Check max memory
By miller-catherine { at } usa { dot } net on 2003/10/30 07:29:24  Rate
public final class MaxMemory 
  {  
     public static void main ( final String args [  ]  )  
      {  
         System.out.println (  
             "Max Memory " + Runtime.getRuntime (  ) .maxMemory (  )  ) ; 
      }  
  } 


public boolean removeShutdownHook(Thread hook)
See Also:
exit(int), addShutdownHook(java.lang.Thread), RuntimePermission, SecurityException, IllegalStateException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public void runFinalization()
See Also:
Object.finalize()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


@Deprecated
public static void runFinalizersOnExit(boolean value)
See Also:
SecurityManager.checkExit(int), gc(), exit(int), SecurityException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public long totalMemory()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[210]Calculating Memory Used by Objects
By Anonymous on 2005/02/16 20:51:39  Rate
//Calculating Memory Used by Objects 
 class MemoryTest  {   
  
  
   protected static final long COUNT = 100;  
  
  
   public static void main ( String [  ]  arg )   {   
     long start, end, difference;  
     Object [  ]  array = new Object [ COUNT ] ;  
     long i;  
  
  
     Runtime.getRuntime.gc (  ) ; // let's hope the  
                      // garbage collector runs  
     start = Runtime.getRuntime (  ) .totalMemory (  ) ;  
        for  ( i = 0; i  <  count; i++ )   {   
        array [ i ]  = new object (  ) ;  
        }   
     runtime.getruntime.gc (  ) ;  
     end = runtime.getruntime (  ) .totalmemory (  ) ;  
  
  
     difference =  ( end - start )  / count;  
  
  
     system.out.println ( "Approximately " + difference  
        + " bytes used by 1 java.lang.Object with  
                               default constructor" ) ;  
    }   
  
  
  }  


[505]_
By cu44 on 2005/02/16 20:51:22  Rate
import java.lang.Runtime; 
 //Fixed version of MemoryTest 
 //Calculating Memory Used by Objects  
  
  
 class MemoryTest  {    
  
  
   protected static final int COUNT = 100;   
  
  
   public static void main ( String [  ]  arg )   {    
     long start, end, difference;   
     Object [  ]  array = new Object [ COUNT ] ;   
    int i;   
  
  
     System.gc (  ) ; // let's hope the   
       //totalMemory (  )  -- Returns the total amount of memory in the Java virtual machine.   
      //Should not of been used in prior example. will also return fixed value 
     start = Runtime.getRuntime (  ) .freeMemory (  ) ;   
  
  
     System.out.println ( "starting memory " +start ) ; 
        for  ( i = 0; i  <  COUNT; i++ )   {    
        array [ i ]  = new Object (  ) ;   
        }    
   System.gc (  ) ;   
     //get amount of remaining free memory available after creating 100 objects 
     end = Runtime.getRuntime (  ) .freeMemory (  ) ;   
  
  
     System.out.println ( "ending memory " +end ) ; 
  
  
    //subtract starting free memory from ending free memory and divide by 100  ( amount of objects )  
    //Other version will take a fixed value and subtract from itself == 0 and divide by 100 == 0 
     difference =  ( start - end )  / COUNT;   
  
  
     System.out.println ( "Approximately " + difference + " bytes used by 1 java.lang.Object with default constructor" ) ;   
    }    
  
  
  } 


public void traceInstructions(boolean on)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public void traceMethodCalls(boolean on)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  

Popular Tags