Object pool for Java wrapper and string

As we all know, sometimes Java uses object pools as wrappers and string types, and sometimes it doesn't

For example:

Integer i1 = 1;
Integer i2 = 1;
Integer i3 = new Integer(1);
String s1 = "String";
String s2 = "String";
String s3 = new String ("String");
System.out.println("(i1 == i2) " + (i1 == i2));
System.out.println("(i2 == i3) " + (i2 == i3));
System.out.println("(s1 == s2) " + (s1 == s2));
System.out.println("(s2 == s3) " + (s2 == s3));

Execution result:

(i1 == i2) true
(i2 == i3) false
(s1 == s2) true
(s2 == s3) false

As you can see, boxing primitives gets objects from the pool, and creating strings from string literals also gets objects from the pool These objects are actually the same object (operator = = returns true for them)

Other mechanisms for creating wrappers and strings do not get objects from the pool Objects created in these ways are actually different objects (operator = = returns false for them)

What puzzles me is the fact that the pool part is used

If it's a memory problem, why not always use the pool? If it's not a memory problem – why use it?

The question is – what is the reason for this behavior (= partial use of the pool)?

This problem is quite theoretical, but it has practical applications - it can help understand how to use custom object pools correctly, and of course, it can understand that Java always works well

Solution

It is a speed problem. Allocating a new integer each time will be expensive in time and memory But in the same way, too much allocation at startup will occupy a lot of memory and time

Sadly, it can lead to some counterintuitive behavior you find

The result is that we have this strange compromise The reasons for this behavior are discussed in the Java standard (5.7)

TL; doctor

It's impossible to make it work perfectly, and it's strange not to make it work at all So we let it work "most of the time"

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>