Analysis of Java static memory and dynamic memory allocation

Source: Internet
Author: User
Tags object object

1. Static memory

Static memory is the memory allocated by the compiler when the program starts running, and its allocation is done at the beginning of the program's compilation, without consuming CPU resources.

A variety of variables in the program, at compile time the system has allocated the required memory space, when the variable is used within the scope, the system will

Automatically frees up the memory space that is occupied.

The allocation and release of variables is not necessary for the programmer to consider themselves.

eg
Base type, array

2. Dynamic memory

Dynamic memory allocation is used when the user cannot determine the size of the space, or if the space is too large to be allocated on the stack.

3. Differences

A) static memory allocations are completed at compile time and do not consume CPU resources; When dynamic memory allocation is run, both allocation and deallocation consume CPU resources.

b) Allocation on the static stack (stacks); There is an allocation on the heap in the dynamic.

c) Dynamic memory allocation requires pointers and reference type support, which is not required statically.

d) Static memory allocations are allocated on a schedule and are the responsibility of the compiler; Dynamic memory allocation is on demand and is the responsibility of the programmer.

4. Example Description

Class A{int I;int J;} Class Testmemo{public static void Main (string[] args) {A aa = new A ();//(A *) malloc (sizeof (a));//New A (); Dynamic allocation of an area in the heap, being Made a object//AA itself memory is allocated in the stack//heap memory address assigned to aa//AA to point to the memory in the heap, AA represents the memory in the heap//AA.I represents: AA This static pointer variable points to the dynamic memory of the A object of the I this member//AA.J represents: AA This static pointer variable points to the dynamic memory of the A object in the J of this member AA.I = 10; AA.J = 20; System.out.printf ("%d,%d\n", AA.I, AA.J);//int i = 10;}}

5. The amount of memory the object occupies

The size of the basic data type is fixed, and here is not much to say. For non-basic types of Java objects, its size is debatable.

In Java, the size of an empty object object is 8byte, which is just the size of an object that holds no attributes in the heap. Look at the following statement:

Object OB = new Object ();

This completes the life of a Java object in the program, but it occupies a space of: 4byte+8byte. 4byte is the space required to save references in the Java stack as described in the above section. And that 8byte is information about the objects in the Java heap.

Because all Java non-primitive types of objects require default inheritance of object objects, the size of any Java object must be greater than 8byte.

With the size of the object, we can calculate the size of the other objects.

Class NewObject {    int count;    Boolean flag;    Object ob;}

Its size is: Empty object size (8byte) +int size (4byte) +boolean size (1byte) + NULL objects reference size (4byte) =17byte. However, because Java is divided by an integer multiples of 8 for object memory allocations, the nearest 8 integer times greater than 17byte is 24, so the size of this object is 24byte.

It is important to note the size of the wrapper type for the base type. Because this type of packaging has become an object, they need to be treated as objects. The size of the wrapper type is at least 12byte (the space required to declare an empty object), and 12byte does not contain any valid information, and since the Java object size is an integer multiple of 8, the size of a basic type wrapper class is at least 16byte. This memory consumption is very scary, it is using the basic type of N times (n>2), some types of memory consumption is more exaggerated (just think about it). Therefore, it is possible to use the packing class sparingly. After JDK5.0, the Java virtual opportunity is optimized for storage by adding automatic type swapping.

※ Relevant knowledge points supplement

①. Data type

In a Java virtual machine, a data type can be divided into two categories: the base type and the reference type. A variable of the underlying type holds the original value, that is, the value he represents is the value itself, whereas a variable of the reference type holds the reference value. A reference value represents a reference to an object, not the object itself, where the object itself resides at the address represented by the reference value.
Basic types include: byte,short,int,long,char,float,double,boolean,returnaddress
Reference types include: Class types, interface types, and arrays.

②. Heap and Stack

The stack is the unit of the runtime, and the heap is the unit of storage.
Stack solves the problem of how the program executes, or how the data is handled, and what the heap solves is the problem of data storage, that is, where the data is placed and where it is placed.
It is easy to understand that a thread in Java has a line stacks corresponding to it, because different thread execution logic differs and therefore requires a separate line stacks. The heap is shared by all threads. The stack is a running unit, so the information stored in it is related to the current thread (or program). This includes local variables, program run states, method return values, and so on, while the heap is only responsible for storing object information.

Why do you want to differentiate the heap from the stack? Is it possible to store data in the stack?

From the point of view of software design, the stack represents the processing logic, and the heap represents the data. This separation makes the processing logic clearer. The idea of divide and conquer. This idea of isolation and modularity is reflected in every aspect of software design.

The separation of the heap from the stack allows the contents of the heap to be shared by multiple stacks (and can also be understood as multiple threads accessing the same object). The benefits of this sharing are many. On the one hand, this kind of sharing provides an effective way of data interaction (for example: Shared memory), on the other hand, the shared constants and caches in the heap can be accessed by all stacks, saving space.

Stack because of the needs of the runtime, such as saving the context of the operation of the system, the address segment needs to be divided. Because the stack can only grow upward, it restricts the ability to store content on the stack. While the heap is different, the objects in the heap can grow dynamically as needed, so the stack and heap splits make the dynamic growth possible, and only one address in the heap is required to be recorded in the corresponding stack.

Object-oriented is the perfect combination of stacks and stacks. In fact, the object-oriented approach to the implementation of the previous structured program is not any different. However, the introduction of object-oriented, so that the way to think about the problem has changed, and closer to the natural way of thinking. When we take the object apart, you will find that the object's properties are actually data, stored in the heap, and the object's behavior (method) is running logic, placed in the stack. When we write the object, we write the data structure, and also write the logic of the processing.

What is stored in the heap? What is stored in the stack?
The object is stored in the heap.
The stack is a reference to the base data type and the objects in the heap.
The size of an object is not estimated, or can be dynamically changed, but in the stack, an object only corresponds to a 4btye reference (the benefit of stack separation:)).
Why not put the basic type in the heap? Because the space it occupies is typically 1~8 bytes-it takes less space, and because it is a basic type, there is no dynamic growth-fixed length, so storage in the stack is enough, if there is no meaning to put him in the heap (it will be wasted space, explained later). It can be said that the basic type and object references are stored in the stack, and are a number of bytes, so when the program runs, they are handled in a uniform manner. But the basic type, the object reference, and the object itself are different, because one is the data in the stack, one is the data in the heap. One of the most common problems is the problem with parameter passing in Java.

Stacks and stacks are the most fundamental things that a program runs. A program can run without a heap, but not without a stack. The heap is a data storage service for the stack, and the heap is a shared memory. However, it is the idea of the separation of heaps and stacks that makes Java garbage collection possible.
Java, the size of the stack is set by-XSS, when the stack of data stored in a long time, you need to adjust this value appropriately, otherwise there will be Java.lang.StackOverflowError exception. The common occurrence of this exception is the inability to return recursion because the information saved in the stack is the record point returned by the method.

What about parameters in Java passing simultaneous values? Or a reference?

Do not attempt to analogy with C, there is no concept of pointers in Java
The program runs always on the stack, so when parameters are passed, there is only a problem passing the base type and object references. The object itself is not passed directly.
But how is the illusion of citation caused? In the run stack, the basic type and the reference are treated the same, and are all passed values, so if it is a reference to a method call, it can also be understood as a value invocation of "reference value", that is, the processing of the reference is exactly the same as the base type. However, when the called method is entered, the value of the reference being passed is interpreted (or found) by the program to the object in the heap, which corresponds to the actual object. If you modify at this point, you are modifying the reference to the corresponding object instead of the reference itself, that is, the data in the heap is modified. So this is a change that can be maintained.
objects, in a sense, are made up of basic types. You can look at an object as a tree, the object's properties, if it is an object, is still a tree (that is, a non-leaf node), and the base type is the leaf node of the tree. When a program parameter is passed, the passed value itself cannot be modified, but if the value is a non-leaf node (that is, an object reference), you can modify all the content underneath the node.

Summary is only the value of the pass! The pass-through object is just the value of the referenced address of the incoming object!
However, when the object is modified within the method, it is the object itself, not the change of the address.

③. Reference type

Object reference types are divided into strong references, soft references, weak references, and virtual references.

Strong reference: Is that we generally declare the object is the virtual machine generated by the reference, the strong reference environment, garbage collection needs to strictly determine whether the current object is strongly referenced, if strongly referenced, it will not be garbage collected

Soft references: Soft references are generally used as caches. The difference from strong references is that when a soft reference is garbage collected, the virtual opportunity determines whether to recycle the soft reference based on the remaining memory of the current system. If the remaining memory is strained, the virtual opportunity reclaims the space referenced by the soft reference, and if the remaining memory is relatively rich, it will not be recycled. In other words, when a virtual machine occurs outofmemory, there must be no soft reference present.

Weak references: Weak references are similar to soft references, and are used as caches. However, unlike soft references, a weak reference is bound to be reclaimed when it is garbage collected, so its life cycle only exists during a garbage collection cycle.

Strong references Needless to say, our system is generally used as a strong reference. Soft references and weak references are relatively rare. They are generally used as caches, and generally are cached when the memory size is limited. Because if the memory is large enough, you can use the strong reference directly as the cache, while the controllability is higher. As a result, they are commonly used in the desktop application system cache.

Analysis of Java static memory and dynamic memory allocation

Related Article

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.