Erveon
Erveon

Reputation: 116

Java Garbage Collecting instance upon removal from map?

I've been trying to be more and more memory focused, and have a question about garbage collecting.

In this case Profile would be a class we have in our program, but the profile would only be necessary when the user is actually logged in.

Map<UUID, Profile> profiles;

public ProfileManager() {
    profiles = new HashMap<UUID, Profile>();
}

public void login(UUID uuid) {
    profiles.put(uuid, new Profile(uuid));
}

public void logout(UUID uuid) {
    if(profiles.containsKey(uuid))
        profiles.remove(uuid);
}

My question is, would it garbage collect the removed profile? It isn't set to null, but rather not referenced anymore. I'm not exactly sure how this is handled. I'd like to think that because it isn't referenced anymore, it'd be garbage collected, but then again, the Profile isn't null.

Thank you.

Upvotes: 0

Views: 94

Answers (3)

rocketblast
rocketblast

Reputation: 156

The Profile object will become eligible for garbage collection when you remove it from the map, iff nothing else references it. After that the garbage collector may or may not garbage collect it right away depending on how long the object has been referenced.

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

However for your purposes I suggest you simply remove it from the map, make sure it's not referenced anywhere else, and then don't worry about the finer details of how the garbage collector works.

Upvotes: 2

Partha
Partha

Reputation: 122

Use java.lang.System.gc(),this method runs the garbage collector.Calling this method suggests JVM(Java Virtual Machine) to start garbage collection, this method might clear the object might not too, that decision is left to the JVM. The JVM operation might vary according to the OS platforms.So only thing you can possibly do is suggest the JVM to garbage collect.

Upvotes: 0

Abhishek Singh
Abhishek Singh

Reputation: 1

The Profile object should be garbage collected however we don't know when GC will run hence it may possible that you may still have access to removed Profile object. But as soon as GC run and it find any unreferenced object then it will remove from the heap.

https://dzone.com/articles/jvm-and-garbage-collection

Upvotes: 0

Related Questions