0

I am using Java to Program Linked List.

In order to delete a node from linkedList, I am just pointing to the next pointer

For Ex: 3->4->5 is my linked list. Now I am deleting 4 so it will be like 3->5 and link to 4 will be deleted.

But in C++ there will be free() command to delete the memory space occupied by 4.

Will this memory space be made free in Java?

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Vijay Manohar
  • 473
  • 1
  • 7
  • 22
  • 1
    Java has a garbage collector. Once you no longer reference something anywhere in your code, it will get cleaned up automatically (although not necessarily immediately). – resueman Jan 12 '16 at 18:32
  • 1
    Unlike C++, we do not have to free the memory used by an object explicity. Java makes use of Garbage Collector to free the memory occupied by objects that are no longer referenced in your code (in your case its the node 4) – Kakarot Jan 12 '16 at 18:35

3 Answers3

2

Java, unlike C++, has a garbage collector to get rid of unreferenced places in memory, So yes it will be made free (although not necessarily immediately).

Vasil Lukach
  • 3,658
  • 3
  • 31
  • 40
paulz
  • 382
  • 1
  • 3
  • 10
0

This algorithm you can use for your problem and for releasing the unclaimed memory we have garbage collector named as System.gc() in Java. You can use this guy to do the job.

public boolean delete(final int searchValue)
{
    Node tmpNode = head;
    Node prevNode = null;
    boolean deletedANode = false;

    while (tmpNode != null)
    {
        if (tmpNode.data == searchValue)
        {
            if (tmpNode == head)
            {
                head = head.next;
            }
            else
            {
                prevNode.next = tmpNode.next;
            }

            deletedANode = true;
        }
        else
        {
            // only advance the prevNode when there's no match.
            prevNode = tmpNode;
        }

        tmpNode = tmpNode.next;
    }

    return deletedNode;


}
  • Calling `System.gc()` isn't necessary to have the memory get reclaimed though, and it doesn't guarantee to immediately reclaim it either. I don't really see a point to calling it here. Also, you put it after a `return`, so it won't compile right now. – resueman Jan 12 '16 at 19:11
0

A little known fact is that Java actually has 4 garbage collectors, not just one.

Which garbage collector arguments you specify to the JVM can impact your applications performance. The 'parallel' garbage collector is on by default, though the newer G1 garbage collector might be more suitable if your application has a heap size of greater than 4gb.

In general doing any tuning of garbage collection should be done absolute last and you should monitor the garbage collection logs as a starting point. A great right up on how to tune GC performance can be found here

james_s_tayler
  • 1,823
  • 1
  • 15
  • 20