Effects of the static variable in memory for singleton

Effects of the static variable in memory for singleton

It related to the Java memory into knowledge

Stack Memory Stack: store local variables method, once the local variable goes out of scope, it will immediately disappear from the stack memory.
Heap Heap: initialize objects stored in the heap memory of them, heap memory object has a hexadecimal address value, wherein the data have default values.
Method Area Method Area: storing .class information, the method comprising the information. (However, the implementation of the specific method in the stack memory)

Static method area Static Method Area: an area of memory in the process of the region as static variables and static methods division.

Static variables

Dynamic variables is built on during program execution, with the need to call a function dynamically allocates storage space, call the variable storage space occupied by the end of the release.
Therefore, the static variables static, refers to the storage space is assigned in the process of operation of the whole program, then the variable is not required dynamic allocation of subsequent calls. And only after the entire program is complete, a static member variables will be destroyed GC. According to the class name when accessing static variables, and the whole subject has nothing to do, and only the relevant categories.

All classes of objects of a class share static variables, JVM encountered static member, it will point to its static area, rather than in rather than trying to re-initialize a new one. So for some tools similar SharedPreferences require repeated use, and use the same variable does not need to be changed, use more static keyword (if necessary with the final keyword ) contribute to effective memory consumption.

The following code demonstrates:

private static SharedPreferencesUtil sp = new SharedPreferencesUtil();

Singleton

In fact, Singleton is also a member of static basis.
Where the lazy man's singleton advantage relative to static members that can be initialized again need to use the time, save some resources.

private static SharedPreferencesUtil Instance;
private SharedPreferencesUtil() {
	//构造器私有化,阻止其他类初始化该类对象
}

public static SharedPreferencesUtil getInstance() {
	if(Instance == null){
		synchronized{
			if(Instance == null){
				Instance = new SharedPreferencesUtil():
			}
		}
	}
    return Instance;
}

Hungry man single-case model compared to static members, inheritance, more than other forms of
code demonstrates the following:

private static SharedPreferencesUtil Instance = new SharedPreferencesUtil();
private static SharedPreferences sharedPreferences;

private SharedPreferencesUtil() {
	//构造器私有化,阻止其他类初始化该类对象
}

public static SharedPreferencesUtil getInstance() {
    return Instance;
}
Released two original articles · won praise 0 · Views 59

Guess you like

Origin blog.csdn.net/weixin_41429728/article/details/104099738