jdk中用到单例模式的不多。
反正我是一个也没想出来。。只能“他山之玉,可以攻石”了。。
Java.lang.Runtime
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类吧。
概述:
Runtime类封装了运行时环境,每个Java应用程序有唯一Runtime实例。
可以通过操作Runtime类去影响虚拟机的状态和行为
Api:
在Runtime的api中发现了gc方法。可是我们时常使用的不是System.gc()吗。。。
所以笔者去阅读了二者的代码
/**
* Runs the garbage collector.
* Calling this method suggests that the Java virtual machine expend
* effort toward recycling unused objects in order to make the memory
* they currently occupy available for quick reuse. When control
* returns from the method call, the virtual machine has made
* its best effort to recycle all discarded objects.
* <p>
* The name <code>gc</code> stands for "garbage
* collector". The virtual machine performs this recycling
* process automatically as needed, in a separate thread, even if the
* <code>gc</code> method is not invoked explicitly.
* <p>
* The method {@link System#gc()} is the conventional and convenient
* means of invoking this method.
*/
public native void gc();
/**
* Runs the garbage collector.
* <p>
* Calling the <code>gc</code> method suggests that the Java Virtual
* Machine expend effort toward recycling unused objects in order to
* make the memory they currently occupy available for quick reuse.
* When control returns from the method call, the Java Virtual
* Machine has made a best effort to reclaim space from all discarded
* objects.
* <p>
* The call <code>System.gc()</code> is effectively equivalent to the
* call:
* <blockquote><pre>
* Runtime.getRuntime().gc()
* </pre></blockquote>
*
* @see java.lang.Runtime#gc()
*/
public static void gc() {
Runtime.getRuntime().gc();
}
可以看到System的gc方法实质是调用了Runtime实例的gc方法。
而Runtime的gc方法则是一个本地方法。
感觉这篇和单例模式倒是没啥关系。哎。随缘随缘。