简体   繁体   中英

How Java manage memory efficiently

Strings are immutable in java ie every time we make changes in string object it creates a new instance and the old object become unreferenced ie waste. so in a big program there will be so many unreferenced objects which can not be access. Does java manage this? how? for example-

String s="abc";
s=s.concat("def");

now object "abc" can not be referenced at all but as strings are immutable it will still exist in the memory pool.

First of all, it sounds like you need a crash source in Java and garbage collection. With that said, there's a few basic points to clear up:

1) Just because an object is immutable does not mean its memory is leaked. If no references exist to an immutable object, it is just as eligible for garbage collection as any other objects.

2) String constants are an exception to this because they are always interned by the JVM. This means that string constants are kept in a special memory pool, and any time a string is created, this pool is first checked to see if that string already exists. If it does, a reference to it is returned. (You can force non-constant strings to join the pool using the String.intern() method).

3) The amount of memory these strings occupy is so minimal that you should essentially never worry about it.

Java has automatic garbage collector which keeps running in background.This garbage collector keep checking for unused object and once it detect/find any such object it destroy it ie free the memory/resources used by that particular object.This is taken care by JVM so you need not worry about it.However if you want you can instruct JVM to do garbage collection .After that JVM can schedule garbage collection accordingly

To know how garbage collection works check the below link:

http://javarevisited.blogspot.in/2011/04/garbage-collection-in-java.html

http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html

Memory management in java is done by JVM ie Garbage Collector in JVM

All objects are stored in heap when they have reference like

MyCode ref=new MyCode();

Garbage collector validate that object for Garbage collection in two cases

  1. If reference to object becomes null
ref=null;
  1. When Island of Isolation happens

http://www.geeksforgeeks.org/island-of-isolation-in-java/

Memory management is some what different regarding String objects as above answers have already explained it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM