“This is the second day of my participation in the November Gwen Challenge. See details of the event: The last Gwen Challenge 2021”.

preface

  • Constant pools are specifically explained in the JVM model. Why do you need constant pools? Just as we always need some labels in our daily life, the constant is a fixed variable. So we can use it as a benchmark

Problem description

  • It says that toonew StringIs constantly opening up space to store content. But String is so widely used that it can easily cause OOM
public static void main(String[] args) throws InterruptedException { List<String> list = new ArrayList<>(); for (int i = 0; i < 200000; i++) { String text = new String("abcsdlkfjsldkfjsalkdjflkasjdflaksjdfl; kasdjgl; kasjgasldk; djgsadlkjgsadlkdjgfas; lkdfjsaf"); list.add(text); } System.out.println(list.size()); }Copy the code
  • The above procedure continuously creates a string and adds it to the collection. If you want to make it easier to get OOM you can make the string bigger and loop bigger.
  • In addition, we also need to adjust the maximum heap memory of the program through IDEA.

  • Then we launch the app, and OOM will appear. The following error is that the GC count exceeds the limit.
  • The way we understand GC here is that there are too many objects in the heap. GC is too frequent because it uses a lot of memory and is the object being used. So every time you GC, you don’t delete any objects
  • This also reflects the disadvantages of new

parsing

  • Because we keep adding new objects to the heap. The space in the heap is efficient again and there’s bound to be a problem. You might say I’ve got a lot of heap space to take up all that space
  • But what if my program keeps looping through new objects. Actually, let’s take a closer look at our code above. We are constantly new the same content in the heap. It’s like you’ve been writing nihao on different pieces of paper
  • Let’s say you write 100 sheets of paper. So what does that mean? So Java provides us with constant pools. The constant pool is dedicated to storing the contents of strings. Because most of our String will repeat itself

To optimize the

  • Now let’s put the codenew StringUse double quotation marks instead. Run the program again and see what happens
public static void main(String[] args) throws InterruptedException { List<String> list = new ArrayList<>(); for (int i = 0; i < 200000; i++) { String text = "abcsdlkfjsldkfjsalkdjflkasjdflaksjdfl; kasdjgl; kasjgasldk; djgsadlkjgsadlkdjgfas; lkdfjsaf"; list.add(text); } System.out.println(list.size()); }Copy the code
  • The program will execute successfully. You can see the memory usage if you use other tools like VisualVM

conclusion

  • Although we use double quotes to construct strings. But we need to know where the constructed strings are located in the JVM. This will avoid the problem of determining equality