In-depth analysis of java class System

System is a class, this class is primarily System is a collection of attributes associated with the systems and methods, and its internal methods are all static, so we directly use the System directly calls like, for example, we used a System.out. print. In this article we will analyze the System class.

A, System Overview

System is the meaning of the system. So it's certainly the main operating system and related information. This class java.lang package is located. We may have a doubt, we have never seen System is instantiated, it is because inside the System class constructor is private and can not be accessed externally and, therefore, can not be instantiated.

He mainly has the following functions:

Access (1) system information, such as the properties and external environment variables

(2) garbage collection related operation

(3) the standard input and output

(4) other commonly used operations, such as arrays copy

Then we test these functions with a description:

Two, System Demo

1, acquisition method set properties

That is how to get our System attributes of the system, or say which method is called to get the properties.

(1) contains (Object value), containsKey (Object key): determining whether a given keyword parameters or attributes defined in the attribute table, returns True or False;

(2) getProperty (String key), getProperty (String key, String default): The property parameter acquisition

(3) list (PrintStream s), list (PrintWriter w): output attribute table of contents in the output stream;

(4) size (): returns the number of attributes of the current key attributes defined in the table.

Of course, we can set properties:

(1) put (Object key, Object value): value of attribute keywords and additional keywords to the property sheet;

(2) remove (Object key): delete the keyword from the attribute table.

2, property acquisition system

Above we can use other methods to call directly System.contains, here we can enter the following parameters to obtain system information.

Features description
java.version Java Runtime Environment version
java.vendor Java Runtime Environment supplier
java.vendor.url Java vendor's URL
java.home Java installation directory
java.vm.specification.version Java Virtual Machine specification version
java.vm.specification.vendor Java virtual machine specification vendor
java.vm.specification.name Java Virtual Machine specification name
java.vm.version Java virtual machine implementation version
java.vm.vendor Java virtual machine implementation vendor
java.vm.name Java virtual machine implementation name
java.specification.version Java Runtime Environment specification version
java.specification.vendor Java Runtime Environment specification supplier
java.specification.name Java Runtime Environment specification name
java.class.version Java class format version number
java.class.path Java class path
java.library.path The search path when loading the library list
java.io.tmpdir The default temporary path
java.compiler Name JIT compiler to use
java.ext.dirs One or more extended path of directories
os.name The name of the operating system
os.arch Operating System Architecture
os.version Operating system version
file.separator File separator (the "/" in UNIX systems)
path.separator Path separator (in the UNIX system ":")
line.separator Line separators (on UNIX systems is "/ n")
user.name The user's account name
user.home The user's home directory
user.dir The user's current working directory

Then use the code to test some of the more typical it:

public class SystemTest {
	public static void main(String[] args) {
		System.out.println("Java 运行时环境版本         :" + System.getProperty("java.version"));
		System.out.println("Java 运行时环境供应商     :" + System.getProperty("java.vendor"));
		System.out.println("Java 运行时环境规范版本    :" + System.getProperty("java.specification.version"));
		System.out.println("Java 运行时环境规范供应商:" + System.getProperty("java.specification.vendor"));
		System.out.println("Java 运行时环境规范名称    :" + System.getProperty("java.specification.name"));
		System.out.println("操作系统的名称:" + System.getProperty("os.name"));
		System.out.println("操作系统的架构:" + System.getProperty("os.arch"));
		System.out.println("操作系统的版本:" + System.getProperty("os.version"));
		System.out.println("用户的账户名称          :" + System.getProperty("user.name"));
		System.out.println("用户的主目录              :" + System.getProperty("user.home"));
		System.out.println("用户的当前工作目录  : " + System.getProperty("user.dir"));
	}
}
复制代码

Of course, we run the console have the results:

Here is just a part of the selection of test parameters have been listed, and the other can measure themselves.

Third, the common operation

1, the array copy arraycopy

public class SystemTest {
	public static void main(String[] args) {
		int[] arr1 = {1,2,3,4,5 };
        int[] arr2 = { 6,7,8,9,10};
        /*
         * 第一个参数arr1:被复制的数组
         * 第二个参数1:arr1中要复制的起始位置
         * 第三个参数arr2:目标数组
         * 第四个参数0:目标数组的复制起始位置
         * 第五个参数3:目标数组的复制结束位置
         */
        System.arraycopy(arr1, 1, arr2, 0, 3);
        for (int i = 0; i < 5; i++)
            System.out.print(arr2[i] + " ");
	}
}
复制代码

2, access to the system time

public class SystemTest {
	public static void main(String[] args) {
		System.out.println(System.currentTimeMillis());
        System.out.println(System.nanoTime());
	}
}
//输出:1565841056267(时间戳)
//输出:1130607059454400
复制代码

Fourth, the garbage collection related operations: System.gc

This sentence shows that run the garbage collector. java virtual machine recovery at the system garbage, objects such as unused.

public class SystemTest {
	public static void main(String[] args) {
		User user = new User();//新建一个对象
		System.out.println(user.toString());
		user=null;//将引用置为空
		System.gc();//垃圾回收
		System.out.println(user.toString());
	}
}
复制代码

We look at the results of operational analysis again

We can see that, after completing performing garbage collection, then enter User information when unable to find the object, and therefore reported a null pointer exception.

We enter the interior System.gc look and see what the internal execution operation,

public static void gc() {
      Runtime.getRuntime().gc();
}
复制代码

Here we can see that in fact performed Runtime garbage collection operation. We are entering will find out that garbage collection is done Runtime.

Fifth, source code analysis

1, initialization

We enter the System source code, you can see first described by this:

/* register the natives via the static initializer.
 * VM will invoke the initializeSystemClass method to complete
 * the initialization for this class separated from clinit.
 * Note that to use properties set by the VM, see the constraints
 * described in the initializeSystemClass method.
*/
private static native void registerNatives();
static {
    registerNatives();
}

/** Don't let anyone instantiate this class */
private System() {}
复制代码

The above is what does that mean?

First: registerNatives () method is a method of entry, registration became natives, that is to say the method will make vm to the completion of initialization by calling initializeSystemClass method.

Then: constructor is arranged to private, that we can not instantiate that class, comment also has been described.

Since System operation is initiated by initializeSystemClass, let us enter into this class to see.

private static void initializeSystemClass() {
    	//第一步:初始化props
        props = new Properties();
        initProperties(props);  // initialized by the VM
    	//第二步:vm保存删除一些系统属性
        sun.misc.VM.saveAndRemoveProperties(props);
    	//第三步:获取系统分隔符
        lineSeparator = props.getProperty("line.separator");
    	//第四步:初始化系统的一些配置
        sun.misc.Version.init();
    	//第五步:输入输出流初始化
        FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
        FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
        FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
        setIn0(new BufferedInputStream(fdIn));
        setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding")));
        setErr0(newPrintStream(fdErr, props.getProperty("sun.stderr.encoding")));
        loadLibrary("zip");
        //第六步:设置平台相关的信号处理
    	Terminator.setup();
    	//第七步:初始化系统环境
        sun.misc.VM.initializeOSEnvironment();
    	//第八步:把自己添加到线程组
        Thread current = Thread.currentThread();
        current.getThreadGroup().add(current);
        //第九步:初始化
    	setJavaLangAccess();
        sun.misc.VM.booted();
 }
复制代码

By initializeSystemClass, we have been able to understand how the System is initialized, for each step, we can continue the research to observe the specific implementation, not go into details here.

2, class attributes

Class properties it is mainly input and output streams

public final static InputStream in = null;
public final static PrintStream out = null;
public final static PrintStream err = null;
复制代码

3, class methods

Here certainly not all methods say again, here are a few of the more important ways.

(1) getProperty: Get System Properties

public static String getProperty(String key) {
    	//校验key的值
        checkKey(key);
    	//检查参数是否安全
        SecurityManager sm = getSecurityManager();
        if (sm != null) {
            sm.checkPropertyAccess(key);
        }
		//获取系统属性
        return props.getProperty(key);
}
复制代码

Here we find, in fact, obtain operational attributes most critical is the last sentence props.getProperty (key). We look into this method:

    public String getProperty(String key) {
        Object oval = super.get(key);
        String sval = (oval instanceof String) ? (String)oval : null;
        return ((sval == null) && (defaults != null)) ? defaults.getProperty(key) : sval;
    }
复制代码

That fact has been a callback defaults.getProperty (key), so that the parent has been kept to call. Finally, return a String.

(2) checkKey: verification key

private static void checkKey(String key) {
        if (key == null) {
            throw new NullPointerException("key can't be null");
        }
        if (key.equals("")) {
            throw new IllegalArgumentException("key can't be empty");
        }
}
复制代码

Which was simply to see if it is empty.

(3) setProperties: set system properties

   public static void setProperties(Properties props) {
        SecurityManager sm = getSecurityManager();
        if (sm != null) {
            sm.checkPropertiesAccess();
        }
        if (props == null) {
            props = new Properties();
            initProperties(props);
        }
        System.props = props;
    }
复制代码

The core is the last line, but in front of first examined whether the system is safe property, but also an initialization according to this property. We enter initProperties.

private static native Properties initProperties(Properties props);
复制代码

This is a native method.

(4) exit (): Exit the current jvm

public static void exit(int status) {
     Runtime.getRuntime().exit(status);
}
复制代码

In fact, exit the method is called the runtime.

(5) Other methods

 public static native long currentTimeMillis();
 public static native long nanoTime();
 public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);
public static native int identityHashCode(Object x);
复制代码

We often find that these methods of operations is actually native.

(6) security management mechanism

There are three methods related

public static void setSecurityManager(final SecurityManager s) {
    try {
        s.checkPackageAccess("java.lang");
    } catch (Exception e) {
    }
    setSecurityManager0(s);
}
复制代码

the second:

private static synchronized void setSecurityManager0(final SecurityManager s) {
    SecurityManager sm = getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new RuntimePermission ("setSecurityManager"));
    }
    if ((s != null) && (s.getClass().getClassLoader() != null)) {
        AccessController.doPrivileged(new PrivilegedAction() {
        	public Object run() {
            	s.getClass().getProtectionDomain().implies(SecurityConstants.ALL_PERMISSION);
            	return null;
        	}
    	});
    }
    security = s;
    InetAddressCachePolicy.setIfNotSet(InetAddressCachePolicy.FOREVER);
}
复制代码

There is one final

public static SecurityManager getSecurityManager() {
    return security;
}
复制代码

OK. Source code analysis will first stop here, for the System class to know its basic internal implementation and common operations can be.

Guess you like

Origin juejin.im/post/5d550b466fb9a06ad0056890