How are memory leaks possible in Java

Showing Answers 1 - 44 of 44 Answers

Nandu

  • Jun 13th, 2005
 

There is no certainty of memory leaks in java.

  Was this answer useful?  Yes

varun kanaujia

  • Jul 5th, 2005
 

If suggest answerthen much better  
Thanks in advanced

  Was this answer useful?  Yes

nitin k

  • Jul 9th, 2005
 

send me java projects with source code

  Was this answer useful?  Yes

Pankaj Sharma

  • Jul 12th, 2005
 

If any object variable is still pointing to some object which  
is of no use, then JVM will not garbage collect that object  
and object will remain in memory creating memory leak

Faisal Ghauri

  • Jul 24th, 2005
 

Perhaps memory leaks can occur because of thread deadlock. When thread A acquires a lock on object C and thread B acquires a lock on object D. Then thread A tries to acquire a lock on object D while thread B tries to acquire a lock on object C. Both thread A and B will remain in a blocked state and I think objects C and D will not become eligible to be garbage collected as they still have live threads attached to them. This can be avoided using synchronized methods or blocks in objects C and D. 
 

PChal

  • Aug 11th, 2005
 

 
When an object does not have any reference pointing to it then it is abandoned. Nothing can get to it or it cannot reach any other object. So it sits in the memory just like that. Since it is wastage of memory it is called memory leak

  Was this answer useful?  Yes

Srimant Misra

  • Aug 12th, 2005
 

Memory leaks can certainly happen in Java. Typically, a class that manages its own memory is prone to this. If there are obsolete references within such a class, the GC won't know whether these objects need to be collected and memory leaks could manifest themselves

  Was this answer useful?  Yes

saif

  • Aug 29th, 2005
 

Hello sir 
I m a basic learner of Java please guide me that how to make my basic concepts much more stronger 
I m in finl year of M.C.A. 
Thanking you 
saif

  Was this answer useful?  Yes

saif

  • Aug 29th, 2005
 

Hello sir 
please send me a Java project using SWINGS as i m a beginner and want to make a project. So plz send me an easy coding 
thanking you

  Was this answer useful?  Yes

usharani

  • Sep 7th, 2005
 

Hello sir, 
please send me a java project using SWINGS &RMI because I am learning the java. 
 
Thankingyou 
usha

  Was this answer useful?  Yes

Sumit Sengar

  • Sep 9th, 2005
 

Hello Saif, 
 
If u r a Java beginner I would suggest you to purchase Head First Java by Kaithy Serra. This is an excellent book to get excellent conceptulal grasp over java.

  Was this answer useful?  Yes

Dhananjay Singh

  • Sep 12th, 2005
 

hi!

 The memory can be leak through those objects that 

 can not  be garbage collected .

  Was this answer useful?  Yes

Rajnish Sasmal

  • Sep 14th, 2005
 

Dear Sir

Memory leaks are possible when we are creating Connection object,Statement objet and ResultSet object  for database connectivity and retrieving the set of rows from database and we are not closing those object.It is better if we write a code rs.close()(for ResultSet object),stmt.close()(for Statement object) and conn.close() ( for Connection object) to avoid the memory leaks.

Thanks and Regards

Rajnish Sasmal

Siemens,Calcutta

  Was this answer useful?  Yes

In languages providing automatic memory management, like Java, C# or LISP there can be memory leaks too. The memory management does not free an object that is strongly reachable. This is the case if still one or more (also strongly reachable) references exist for the object. (For example, storing an object in a Vector object in Java and later losing/forgetting about the index). The developer is responsible for cleaning up references after use. Nevertheless, automatic memory management is more convenient for developers, as they don't need to implement freeing routines or worry about the sequence in which cleanup is performed. Automatic memory management does impose a small performance overhead with all the extra checking.

  Was this answer useful?  Yes

Dastagiri

  • Oct 4th, 2005
 

when java code executes anative code then there will be posibility of memory leaks.

  Was this answer useful?  Yes

Devidas Sonawane

  • Oct 27th, 2005
 

Memory leaks possible in the following ways :1) When more than one threads present and no Synchronization 2) When java executes a native codes. 3) When API objects are not closed like resultSet.close  

  Was this answer useful?  Yes

Aneesh

  • Mar 2nd, 2006
 

In any language, application-level memory management problems revolve around the deallocation of memory. These problems fall into two categories: premature deallocation (corrupted pointers) and incomplete deallocation (memory leaks).

In the case of incomplete deallocation, there are two subcases: coding bugs and design bugs. Coding bugs are language dependent. In the case of C, this would involve free()ing less than was malloc()ed, while in C++ this might involve using delete in lieu of delete[]. Design bugs, on the other hand, do not depend on the language; instead, they involve simple programmer negligence.

In languages like C/C++, all memory management is handled by the programmer, so all of these problems can arise, even after the programmer has expended much effort to ensure the code is free of such defects. In fact, in C/C++ the more you try to avoid memory leaks, the more likely you are to create corrupted pointers, and vice versa. And, by nature the risk of such bugs increases with code size and complexity, so it's difficult to protect large C/C++ applications from these types of bugs.

In Java, on the other hand, the Java language and runtime together entirely eliminate the problems of corrupted pointers and code-level memory leaks. Here's how:

  • In Java, memory is allocated only to objects. There is no explicit allocation of memory, there is only the creation of new objects. (Java even treats array types as objects.)

  • The Java runtime employs a garbage collector that reclaims the memory occupied by an object once it determines that object is no longer accessible. This automatic process makes it safe to throw away unneeded object references because the garbage collector does not collect the object if it is still needed elsewhere. Therefore, in Java the act of letting go of unneeded references never runs the risk of deallocating memory prematurely.

  • In Java, it's easy to let go of an entire "tree" of objects by setting the reference to the tree's root to null; the garbage collector will then reclaim all the objects (unless some of the objects are needed elsewhere). This is a lot easier than coding each of the objects' destructors to let go of its own dependencies (which is a coding-level problem with C++).

So what about memory leaks caused by poor program design? In such designs, unnecessary object references originating in long-lived parts of the system prevent the garbage collector from reclaiming objects that are in fact no longer needed. Such errors typically involve a failure "in the large" to properly encapsulate object references among various parts of the code.

Another design flaw occurs "in the small," at the level of a faulty algorithm; the use of Collections objects in such cases will typically magnify the error.

As the technology improves, a suitably implemented JVM could help reduce the effects of such designed-in memory leaks by using the garbage collector to track object usage over time. The garbage collector could then rearrange objects in memory according to a freshness factor based on when they were last referenced, for example. Stale objects would become eligible for physical RAM swap-out (even though, for safety, they would still exist).

Ideally of course, programmers would design applications with objects' lifecycles in mind, rather than rely on clever features of state-of-the-art JVM implementations.

In conclusion: Design problems can be mitigated by letting go of object references in one's own classes as soon as one can (knowing that in Java there is no risk of damaging another part of the code).

abhishek verma

  • Jul 10th, 2006
 

Hi, One of the very comman cause of memory leak is DB connections. Some times what happenes is that we are opening the connection but either the close connection code is unreachable or not properly written. The basic rule to avoid this and to keep your connection close code in finally block.

  Was this answer useful?  Yes

rariedel

  • May 27th, 2008
 

How many? How many would you like?

Memory leaks may happen in Java (and any other garbage collected or non-garbage collected envirionment) when collecitons are used and the programmer inadvertently fails to remove object references from the collection when the object is no longer required.

  Was this answer useful?  Yes

vaneet

  • Jun 3rd, 2008
 

memory leaks is a misnomer as there is nothing as such that some memory is lost... It means that there might be some piece of code which we have unintentionally missed out , due to which the CPU keeps on consuming the storage space . This is a long process and might be going on for years before you encounter a problem of memory leak. eg.

// u have an object obj..which u anywaz will require to make null after your work is done.

{
A obj =  new A();
sout("djcbdkcj");
if(a == b)
sout("");                 // candidate for memory leak.
else
obj = null;

in this code, we have a memry leak., every time this piece of code is called, a new obejct gets created, but if the condition is met, we dont do anything with the created object.
This will gradually keep teh memory filling.

cn u gimme xample coz null ref does,nt alloc  memory ?/
isn't it
also by default null ref is 1ly created for new born object
isn't it
if i were wrong pz specs

  Was this answer useful?  Yes

desai298

  • Jul 26th, 2008
 

Use of arrays of primitives is supposed to eat up a lot of memory. Use of tools like Jprobe, Jprofile would help determine which kind of datastructures eat up lot of memory and lead in memory leaks.

  Was this answer useful?  Yes

priyadg_4

  • Oct 3rd, 2008
 

Memory leaks are possible in Java. There is a possibility that the garbage collector may never even run during an application's lifetime, even if it is explicitly invoked by calling System.gc(). The garbage collector won't be automatically run until a program needs more memory than is currently available. JVM will first attempt to make more memory available by invoking the garbage collector. If this attempt still doesn't free enough resources, then the JVM will obtain more memory from the operating system until it finally reaches the maximum allowed.
Usually hashtables and Vectors are common cause for memory leak. These should be nullified after the referencing is done.

  Was this answer useful?  Yes

Memory leaks happen when objects remain in heap and are not garbage collected as they are not dereferenced. There are many ways by which a memory leak could occur. Let's take the below chunk of code which would cause memory leak.


//Instance variable
 List list = new ArrayList<Integer>();

//method which demonstrates memory leaks
public void addAndRemoveObjects()
{
       for (int i = 0; i < 100; i++) {
            list.add(i);
       }
       System.out.println("Äfter addition " + list.size());
       // do some operation with the filled ArrayList...

       for (int i = 99; i > 0; i--) {
              list.remove(i);
       }
       System.out.println("Äfter deletion " + list.size());
}

When the method addAndRemoveObjects() is invoked from a block, every time 100 objects are added, only 99 objects are removed. 

CAREFULLY OBSERVE THE INDEX OF THE FOR LOOP WHICH REMOVED THE DATA FROM LIST. " for (int i = 99; i > 0; i--)" . There has been an error in the index i > 0 is wrong. It should have been i >= 0... When i > 0, we are leaving behind one object every time we call this method which adds and removes. 

This way every time the method addAndRemoveObjects () is invoked, we're leaving behind one object in the heap thus causing OOM to occur. 

Note:- This OOM is due to Java heap space.

  Was this answer useful?  Yes

rne18145

  • Nov 2nd, 2010
 

The term 'Memory Leak' in Java has a slightly different meaning to languages like C/C++. In C/C++, a memory leak would mean that some memory used by the program has not been given back to the OS even if the program terminates. To claim the memory back, you'll have to reboot your system. However, in Java, a memory leak just refers to memory that is occupied unnecessarily during execution. This means once the program terminates, all occupied memory is given back to the OS.


In Java, typically, this happens when static Maps or Collections contain unnecessary data that is not dereferenced as and when their requirement is over.

  Was this answer useful?  Yes

Imagine you have an implementation of a Stack data structure in Java where values can be pushed onto the stack and then popped off. The naive implementation for the "pop" operation might look like this:

  
Object pop() {
    return this.stack[this.lastItem--];
}


Now imagine you pushed a large number of items onto the stack and then popped each one off and processed it. Even though the values previously pushed onto the stack are no long accessible, they still exist in the this.stack array. Thus, they a leaked

  Was this answer useful?  Yes

bikash

  • Jul 20th, 2011
 

Improper handling of pointers leads to memory leaks and reliability issues.

  Was this answer useful?  Yes

sampra

  • Mar 13th, 2012
 

when we have object in momory and that object is not gets called at runtime.this is memory leckage

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions