How Java optimizes memory usage (i)

Source: Internet
Author: User
Tags java throws

What is the impression that the Java system gives people? Account for Memory! Say it, there will be more than n people stand up to defend Java, and a bunch of performance test reports to prove this. In fact, in theory, the Java system is not more memory than the system developed in other languages, then why there are so many n reasons to prove that it does occupy memory? Two words, bad habits.
(1) Do not use the new Boolean ().
In many scenarios, a Boolean type is required, such as the Boolean type set and get in JDBC are passed through a Boolean wrapper, and most ORM uses a Boolean to encapsulate the Boolean type, for example:
Ps.setboolean ("isClosed", New Boolean (true));
Ps.setboolean ("isClosed", New Boolean (isClosed));
Ps.setboolean ("isClosed", New Boolean (i==3));
Typically, the number of Boolean instances constructed in these systems is quite large, so the system is filled with a lot of Boolean instance small objects, which are quite memory-intensive. The Boolean class is actually just two instances long enough, an instance of true, an instance of false.
The Boolean class provides two static variables:
public static Final Boolean true = new Boolean (true);
public static Final Boolean false = new Boolean (false);
Just take these two variables when you need them,
Like what:
Ps.setboolean ("isClosed", boolean.true);
So what if you want to create a Boolean based on a Boolean variable, like 2 or 3? You can use the static method provided by Boolean: Boolean.valueof ()
Like what:
Ps.setboolean ("isClosed", Boolean.valueof (isClosed));
Ps.setboolean ("isClosed", Boolean.valueof (i==3));
Because the internal implementation of valueof is: return (b? True:false);
So you can save a lot of memory. It is believed that if the Java specification directly prescribes a Boolean constructor as private, this will never happen again.
(2) Do not use new Integer.
Similar to Boolean, there are many occasions when an integer is used to encapsulate int in Java development, and usually the values represented by int are usually very small. The instantiation of the integer is optimized in the SUN SDK, and the integer class caches 128 to 127 of the 256 state integers, and if you use integer.valueof (int i), the incoming int range is exactly within this, returning a static instance. This will also greatly reduce the memory footprint if we use integer.valueof instead of the new integer. If your system is to be used in a different SDK (such as the IBM SDK), then you can do it yourself, such as integerutils.valueof (), so you can use this feature in any SDK.
(3) Add stringbuffer instead of strings. I'm not going to talk about this because I've been told N times. I just want to put a joke is not a joke, I look at a domestic "famous" Java development of the source of the web system, unexpectedly found that a large number of the use of string addition, a method of assembling SQL statements to construct up to nearly 100 string instances. No words in it!
(4) Excessive use of hash tables, developers with certain development experience will often use the hash table (hash table in the JDK is an implementation is HashMap) to cache some data, thereby improving the speed of the system. For example, the use of HashMap cache some material information, personnel information and other basic information, which improves the system speed, but also increased the system's memory, especially when the cache of more data. In fact, we can use the concept of caching in the operating system to solve this problem, that is, to allocate a cache of a certain size cache container, according to a certain algorithm to eliminate the need to continue to cache the object, on the one hand, because of the object cache and improve the system's operational efficiency, It also reduces the memory footprint of the system because the cache container is not infinitely expanded. Now there are many open source cache implementation projects, such as Ehcache, Oscache, etc., these projects have implemented FIFO, MRU and other common caching algorithms.
(5) Avoid too deep class hierarchies and too deep method calls. Because both are very memory-intensive (especially the method call is a big consumer of stack space).
(6) A variable is defined and instantiated only when it is used.
(7) Try to avoid using static variables, the private constants within the class can be replaced by final.

Java Memory management ideas (mainly from thinking in Java)

Java Memory management features
One of the biggest advantages of Java is the removal of pointers, which are automatically managed by the garbage collector to recycle memory. Programmers do not need to call functions to free memory.

1. The memory management of Java is the problem of allocating and releasing objects.
In Java, programmers need to request memory space for each object through the keyword new (except for the base type), and all objects allocate space in the heap.
The release of an object is determined and executed by the GC.
In Java, the allocation of memory is done by the program, and the release of memory is done by GC, this two-line method simplifies the work of programmers. But it also adds to the JVM's work. This is one of the reasons why the Java program is running slower.

GC Free Space Method:
Monitor the running state of each object, including the application, reference, reference, assignment, etc. of the object. When the object is no longer referenced, the object is disposed.


2. Memory management structure
Java uses a graph-by-diagram approach to memory management, and for every moment of the program we have a graph representation of the JVM's memory allocations.

Consider the object as a vertex of the directed graph, consider the reference relationship as a directed edge of the graph, and have a directed edge from the referrer to the cited object. In addition, each thread object can be used as the starting vertex of a graph, for example, when most programs are executed from the main process, the graph is a root tree that starts with the main process vertex. In this graph, the object that the root vertex can reach is a valid object, and the GC will not reclaim those objects. If an object (connected sub-graph) and this root vertex are unreachable (note that the graph is a forward graph), then we think that this (these) objects are no longer referenced and can be recycled by GC.

3. The advantages and disadvantages of using a graph to manage memory
Java uses a graph-like approach to memory management, which eliminates the problem of reference loops, such as having three objects and referencing each other, so that GC can reclaim them as long as they are unreachable from the root process.
The advantage of this approach is that the precision of managing memory is high, but the efficiency is low.

+ +:
Another common memory management technique is the use of counters, such as the COM model, which uses counter-mode management artifacts, which are low-precision rows (difficult to handle circular references) compared to a forward graph, but perform efficiently.

★java of memory leaks
Java is a GC to reclaim memory, but there is a leak problem, just a little smaller than C + +.

1. Comparison with C + +
The allocation and recycling of all objects in C + + needs to be managed by the user. That is, you need a management point and a management edge. If there are unreachable points, the memory allocated to that point cannot be reclaimed, causing a memory leak. The existence of useless object references can naturally lead to memory leaks.
Java is managed by a GC to manage memory reclamation, and the GC reclaims memory space occupied by unreachable objects. So, the memory leaks that Java needs to consider are primarily those that are referenced but useless-that is, to manage the edges. Referenced but useless object, the program references the object, but it is no longer used in the future. The memory space it occupies is wasted.
If there is a reference to the object, the object is defined as "active" and is not freed.

2. Java Memory leak handling
Handling Java's memory leak problem: Verify that the object is no longer being used.
A typical practice--
To set the object data member to NULL
Removes the object from the collection
Note that when a local variable is not required, it is not required to be significantly set to NULL, because these references are automatically cleaned up when a method finishes executing.

Example:
List mylist=new ArrayList ();
for (int i=1;i<100; i++)
{
Object O=new object ();
Mylist.add (o);
O=null;
}
At this point, all object objects are not freed because they are referenced by the variable mylist.

When MyList is no longer used, it is set to NULL, releasing all the objects it references. The GC then reclaims the memory consumed by these objects.

★ Action on GC
The operation of the GC does not necessarily achieve the effect of managing memory.

The GC is basically transparent and invisible to programmers. We have only a few functions that can access the GC, such as the function that runs the GC System.GC (), System:
However, as defined by the Java language Specification, the System.GC () function does not guarantee that the JVM's garbage collector will execute. Because different JVM implementations may use different algorithms to manage the GC. Typically, a GC's thread has a lower priority level.


There are a number of policies that the JVM calls the GC, some of which are used to a certain extent, the GC starts to work, there are timed executions, there is a gentle execution of the GC, and some interrupt-execution GC. But generally speaking, we don't need to care about this. Unless the GC's execution affects the performance of the application on certain occasions, such as a web-based real-time system, such as a network game, where the user does not want the GC to suddenly interrupt application execution for garbage collection, then we need to adjust the GC's parameters so that the GC can free up memory in a gentle manner. For example, by decomposing garbage collection into a series of small steps, the sun-provided hotspot JVM supports this feature.

★ Memory Leak Detection
There are several professional tools on the market to check the Java memory leaks, they basically work the same principle, all through the monitoring of the Java program runtime, all object application, release and other actions, the memory management of all the information to statistical, analysis, visualization. The developer will use this information to determine if the program has a memory leak problem. These tools include Optimizeit Profiler,jprobe profiler,jinsight, Rational company Purify, etc.

In the process of running, we can always observe the use of memory, in this way, we can quickly find those who have not been released for a long time, and no longer use the object. We check the life cycle of these objects to see if they are memory leaks.

★ Soft Reference
Feature: This type of memory is only recycled when memory is insufficient and is guaranteed to be set to NULL before Java throws an OutOfMemory exception.
Ensure maximum use of memory without causing outofmemory exceptions.
At some point, the use of soft references can reduce the operational efficiency and performance of the application, for example: the initialization of objects that apply soft references is time consuming, or the state of an object changes during the course of a program, causing varying degrees of inconvenience to recreating objects and initializing objects.

Use:

Can be used to implement the cache of some common resources, implement the function of the cache
Handle some memory-intensive and long-declared periods, but use this technique as much as possible when using objects that are not very frequent

The experience of memory management in ★java programming

1. The most basic suggestion is to release the reference to the useless object as soon as possible. Such as:...
A = new A ();
Apply a object
A = null; When you use object A, you actively set it to empty
....
Note: If a is the return value of the method, do not do so, otherwise the return value you get from the method is always empty, and this error is not easy to find, exclude 2. Use the Finalize function as little as possible. It will increase the workload of the GC.
3. If you need to use a frequently used picture, you can use the Soft app type. It keeps the picture in memory as much as possible.
4. Note the collection data types, including arrays, trees, graphs, linked lists, and other data structures, which are more complex for GC to recycle.
5. Try to avoid creating and initializing a large number of objects in the class's default constructor to prevent unnecessary memory wasting when invoking their own class constructors
6. Try to avoid forcing the system to recycle garbage, increase the system to do garbage collection of the final time
7. Try to avoid explicitly requesting array space
8. Try to do the remote method call class application development uses the instantaneous value variable, unless the remote caller needs to get the value of the instantaneous value variable.
9. Try to use object pooling techniques to improve system performance in the right scenario.

How Java optimizes memory usage (i)

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.