Klausos Klausos
Klausos Klausos

Reputation: 16050

Remove an object from the memory in Java

I created a graph that contains nodes and arcs. When I close the SWING application and manually update the structure of a graph (i.e. remove some nodes and arcs), the old structure of the graph is not deleted from the memory. For instance:

ArrayList<Node> nodes = new ArrayList<Node>();
ArrayList<Arc> arcs = new ArrayList<Arc>();
nodes.add(new Node("N1"));
nodes.add(new Node("N2"));
nodes.add(new Node("N3"));
arcs.add(new Arc("N1","N2"));
arcs.add(new Arc("N2","N3"));
Graph g = new Graph(nodes,arcs);

In the Node class I have:

@Override
public String toString() {
    return super.toString() + 
           (isNotConnected() ? " IS NOT CONNECTED" : "" );
}

Then I close the application, remove the node "N3" and arc ("N2","N3") and run the application again. It says that N3 IS NOT CONNECTED. But I deleted N3!!! To close the application, I´m using:

frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

Also, I tried to use g = null, but it didn´t help as well.

UPDATE:

public class Node {
    private List<Arc> incoming = new ArrayList<Arc>();
    private List<Arc> outgoing = new ArrayList<Arc>()

    protected Node(String name) {
        super(name);
    }

// ...

    public boolean isNotConnected() {
        return incoming.isEmpty() && outgoing.isEmpty();
    }

    public void addIncoming(Arc arc) {
        this.incoming.add(arc);
    }

    public void addOutgoing(Arc arc) {
        this.outgoing.add(arc);
    }

}

Upvotes: 0

Views: 404

Answers (2)

alf
alf

Reputation: 8513

It's very unlikely that anything is "not deleted from the memory"—each new run is a new JVM, and it means absolutely clean sheet, no history from the previous run.

So I'd rule this possibility out. What's left then?

  • You can have a bug in the isNotConnected() method — not likely, as I hope you got the super.toString() right.
  • You can have an older code running. It can be easily diagnosed by changing any string you print, e.g. going from "NOT CONNECTED" to "not connected" — no change in logic, but easy to spot in the logs.
  • You can have one more point in the code where you create N3
  • Etc, etc.

What's important here is that you should never blame the magical non-cleaning memory before you have ruled out all other possibilities.

Have fun!

Upvotes: 2

AlexR
AlexR

Reputation: 115328

It is impossible. You do not detect your problem correctly. Probably you do not compile your code every time and run the old binaries.

Upvotes: 1

Related Questions