[java] Runtime類解析
概述
每一個java application都有一個Runtime類的單例,這個例項允許應用程式訪問一些程式所執行的環境的介面。此類不能被應用程式例項化。
getRuntime方法
程式當前的runtime例項可以通過getRuntime方法得到,程式碼如下:
private static Runtime currentRuntime = new Runtime(); /** * Returns the runtime object associated with the current Java application. * Most of the methods of class <code>Runtime</code> are instance * methods and must be invoked with respect to the current runtime object. * * @return the <code>Runtime</code> object associated with the current * Java application. */ public static Runtime getRuntime() { return currentRuntime; }
比較有意思的是,這裡Runtime類的例項化並沒有對執行緒安全做任何特殊處理,因為它採取了hungry模式實現單例,初始化時靜態的currentRuntime就會被建立。意味著虛擬機器不管程式設計師使不使用這個例項,但是它都預先將它初始化了。
exec方法
exec方法的作用是:用指定的環境和工作目錄在指定的程序中執行指定的字串命令,也可以說就是執行一個另外的程式。實現如下:
public Process exec(String command, String[] envp, File dir) throws IOException { if (command.length() == 0) throw new IllegalArgumentException("Empty command"); StringTokenizer st = new StringTokenizer(command); String[] cmdarray = new String[st.countTokens()]; for (int i = 0; st.hasMoreTokens(); i++) cmdarray[i] = st.nextToken(); return exec(cmdarray, envp, dir); }
command會被一個叫做StringTokenizer的類分解為token。然後呼叫了另一個exec方法
public Process exec(String[] cmdarray, String[] envp, File dir)
throws IOException {
return new ProcessBuilder(cmdarray)
.environment(envp)
.directory(dir)
.start();
}
這個exec方法new了一個ProcessBuilder例項,然後再根據傳入的命令,和當前的環境以及目錄,去執行這個命令,同時,返回了一個Process的例項,我們可以使用這個物件控制Java程式與新執行的程序進行互動。
記憶體管理方法
Runtime類提供了幾個可以訪問記憶體資訊的方法,這些方法無一例外都是native方法
freeMemory():該方法返回Java虛擬機器中的空閒記憶體,以位元組為單位。
public native long freeMemory();
totalMemory():該方法用於返回Java虛擬機器中的記憶體總量。
public native long totalMemory();
maxMemory():該方法用於返回Java虛擬機器試圖使用的最大記憶體量。
public native long maxMemory();
一些有意思的方法
availableProcessors方法
返回Java虛擬機器可用的處理器數量。
public native int availableProcessors();
gc方法
執行垃圾回收器。呼叫此方法是建議Java虛擬機器去回收未使用的物件,以便使它們當前佔用的記憶體能夠快速重用。當控制元件從方法呼叫返回時,虛擬機器已經盡最大努力回收所有丟棄的物件。注意,並不是強制回收,這與System類裡面的gc方法是一樣的。
public native void gc();
addShutdownHook方法
public void addShutdownHook(Thread hook) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new RuntimePermission("shutdownHooks"));
}
ApplicationShutdownHooks.add(hook);
}
在java虛擬機器當中註冊一個新的shutdown hook, 所謂shutdown就是指的虛擬機器關閉的時候。這個方法的意思就是當jvm關閉的時候,會執行系統中已經設定的所有通過方法addShutdownHook新增的鉤子,當系統執行完這些鉤子後,jvm才會關閉。所以這些鉤子可以在jvm關閉的時候進行記憶體清理、物件銷燬等操作。