How Java different data types are stored in memory __JVM

Source: Internet
Author: User
Tags class definition wrapper
转载自http://www.open-open.com/lib/view/open1415453057980.html
1, Java Memory management is the allocation and release of objects

allocation : The allocation of memory is done by the program, and the programmer needs to request the memory space for each object with the keyword new (except for the base type), and all objects are allocated space in the heap (Heap).

Release : The release of an object is determined and executed by the garbage collection mechanism, this simplifies the programmer's work, but adds to the JVM's work, because, in order for the GC to properly release the object, the GC must monitor the running state of each object, including the object's application, references, references, assignments, etc. GC has to be monitored.


2. Memory Leak (Java Memory leak solution)

Memory leaks exist in some of the allocated objects, with two characteristics, the memory object's reference is still present, the object is useless, the program will not use objects, these objects can be called Java memory leaks, these objects are not collected by GC, but Occupy memory.


3, the memory area of the JVM composition (permanent Generation space (permanent Save area), Heap space (heap area), Java Stacks (Java stack)


permanent Save area: mainly save class and meta information, class is placed in the permanent storage area for the first time, class needs to store content mainly including methods and static properties.

Stack Memory: The base variable type defined in the function and the reference variables of the object are allocated in the stack memory of the function

Heap Memory: The object that is used to store the new (contains only the individual member variables, not the member method). The member variables of the class are in the objects in the heap, and the base types and reference types are stored in the heap as a whole in the space of the object. The different objects in the same class have their own member variables, stored in their own heap, but the objects share the methods of the class, not without creating an object that copies the member methods once, the array, and the instance variables of the object.


In a function, when a variable is defined, Java allocates the memory space for the variable in the stack, and when the scope of the variable is exceeded, Java automatically frees the memory space allocated by the variable. The memory allocated in the heap is managed by the automatic garbage collector of the JVM. A method in a class is shared by a class object, and when an object uses a method, the method is pushed into the stack and the method does not use no memory consumption.



Comparison of heap and stack

Heap: The memory size can be dynamically allocated, and the lifetime does not have to be told to the editor in advance because it dynamically allocates memory at runtime. But it is because of the runtime dynamic allocation of memory, so the access speed is relatively slow.


Stack:
stack data can be shared, access speed is relatively fast. However, the data size generation cycle in the stack must be determined and lacks flexibility.



4. How the data in Java is stored in memory Basic data Types

For example, when we define an int data, int a=3; Here's A is a reference to the int type, point to the literal value of 3, the value of the data is known by the size, lifetime known (the word value defined in a program block, the program block launched, the field value disappears, for the most reason for speed, it exists in the stack).


Stack of data sharing, while defining int a=3;int b=3; the compiler processes int = 3 First, it creates a reference to a in the stack, and then looks for an address that has a literal value of 3, does not find it, opens an address that holds the face value of 3, and then points A to the address of 3. then the int b = 3 is processed, and after the B-reference variable is created, the B is pointed directly to the address of 3 because it already has 3 of the literal value on the stack. In this way, there is a case where A and B both point to 3.
Object

In Java, create a two-step declaration and instantiation of an object including an object

<span style= "FONT-SIZE:14PX;"    >public class Rectangle {
double width;
Double height;

Public Rectangle (double W, double h) {
w = width;
h = height;
}
}

</span>
memory model when declaring an object: Using rectangle rect, declare the rect of an object, allocate memory space for the object's reference variable rect, but the rectangle value is null, the RECT is a null object, and the empty object cannot be used because it does not reference any entities.

Object Instantiation is the memory model : When executing rect=new Rectangle (3,5), two things are done: Allocate memory for the class's member variable Width,height in heap memory and initialize it to the default values for each data type , followed by an explicit initialization (the initialization value at the time of the class definition), and the last call to the constructor method to assign a value to the member variable. A reference to the object in the heap memory (equivalent to the first address) is rect to the reference variable, and the object in the heap memory can then be referenced by Rect.


Packing class

The wrapper class corresponding to the basic data type is no different from the normal object.

String is a special wrapper class that can be created in the following two ways

string S1 = new string ();
String s2 = "abc";
First KindIn the same way as the normal object creation process

The second type of Java internally divides string s2 = "ABC" into several steps:

1, first define an object reference variable named str to the String class: String str;

2, in the stack to find there is no store value of "ABC" address, if not, create a deposit with the "ABC" address, then the object o of the new string class, and point O's string value to the address, and note the object o to this reference next to the stack address. If you already have an address with the value "ABC", look for the object o and return to the address of O.

3. Point STR to the address of object o. It is noteworthy that the string values in the generic string class are stored directly. But like string str = "abc"; in this case, its string value holds a reference to the data in the stack.

Note: New objects are created in the heap by using new () in string, and their strings are stored separately, and are not shared with the data in the stack, even if they are the same as the data in the stack.


Array

Create an array, save in the heap, create a reference in the stack, and manipulate the array by that reference. X=new int[3]; The heap memory is allocated three space to hold int data, the first address of heap memory is put into stack memory, each array element is initialized to 0. Static Variables

Variables and methods decorated with static, in effect, specify the "fixed position" of these variables and methods in memory (which can be understood as the shared memory space of all objects), the static representation of memory sharing, or each of its instances pointing to the same memory address. Using the static modifier, you tell the JVM that it is static and that its references point to the same location.

When was the static variable and the method initialized? For two different class attributes, the static property and the instance property, the timing of initialization is different. The instance property is initialized when the instance is created, and the static property is initialized when the class is loaded, which is the first time the class is used, and is not initialized again for the creation of subsequent instances.

public class Student {
	 static int a= 0;

	Student () {
		System.out.print (a++);
	}
	public static void Main (string[] args) {
		Student s = new Student ();
		Student S1 = new Student ();
		Student s2 = new Student ();
		Student s3 = new Student ();
	}
}
Output Result: 0123
For each object created, a is added, because a is static-decorated statics, and static-decorated variables and methods are stored in the shared memory space of all objects, with each instance pointing to the same memory address.

public class Student {
	int a= 0;

	Student () {
		System.out.print (a++);
	}
	public static void Main (string[] args) {
		Student s = new Student ();
		Student S1 = new Student ();
		Student s2 = new Student ();
		Student s3 = new Student ();
	}
}
Output result: 0000

Compare the above two output results.


5. Java Memory Management Instance

public class Dog {
	Collar C;
	String name;

	The 1.main () method is on the stack public
	static void Main (string[] args) {
		//2. Create reference variable D on stack, but Dog object does not exist
		Dog D;
		3. Create a new Dog object and assign it to the D reference variable
		d = new Dog ();
		4. Pass a copy of the reference variable to the Go () method
		D.go (d);
	}

	5. Place the Go () method on the stack and use the Dog parameter as a local variable
	void Go (Dog Dog) {
		//6. Creates a new Collar object on the heap and assigns it to the DOG instance variable
		c = new Collar (); c15/>}

	//7. Add SetName () to the stack and use the Dogname parameter as its local variable
	void SetName (String dogname) {
		//8. The instance object of name also refers to the string object
		name = Dogname;
	9. After the execution of the program, the SetName () will be completed and cleared from the stack, and the local variable dogname will also disappear, although the string it references is still on the heap
}
The following sections refer to the original blog post.





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.