How to delete object inside method? [duplicate] - java

I want to delete an object I created, (a oval which follows you), but how would I do this?
delete follower1;
didn't work.
EDIT:
Okay, I'll give some more context. I'm making a small game with a oval you can control, and a oval which follows you. Now I've got files named: DrawPanel.class, this class draws everything on the screen, and handles collisions, sounds, etc. I got an enemy.class, which is the oval following the player. I got an entity.class, which is the player you can control. And if the player intersects with the follower, I want my player object to get deleted. The way I'm doing it:
public void checkCollisions(){
if(player.getBounds().intersects(follower1.getBounds())){
Follower1Alive = false;
player.health = player.health - 10;
}
}

You should remove the references to it by assigning null or leaving the block where it was declared. After that, it will be automatically deleted by the garbage collector (not immediately, but eventually).
Example 1:
Object a = new Object();
a = null; // after this, if there is no reference to the object,
// it will be deleted by the garbage collector
Example 2:
if (something) {
Object o = new Object();
} // as you leave the block, the reference is deleted.
// Later on, the garbage collector will delete the object itself.
Not something that you are currently looking for, but FYI: you can invoke the garbage collector with the call System.gc()

Your C++ is showing.
There is no delete in java, and all objects are created on the heap. The JVM has a garbage collector that relies on reference counts.
Once there are no more references to an object, it becomes available for collection by the garbage collector.
myObject = null may not do it; for example:
Foo myObject = new Foo(); // 1 reference
Foo myOtherObject = myObject; // 2 references
myObject = null; // 1 reference
All this does is set the reference myObject to null, it does not affect the object myObject once pointed to except to simply decrement the reference count by 1. Since myOtherObject still refers to that object, it is not yet available to be collected.

If you want help an object go away, set its reference to null.
String x = "sadfasdfasd";
// do stuff
x = null;
Setting reference to null will make it more likely that the object will be garbage collected, as long as there are no other references to the object.

You don't need to delete objects in java. When there is no reference to an object, it will be collected by the garbage collector automatically.

You can remove the reference using null.
Let's say You have class A:
A a = new A();
a=null;
last statement will remove the reference of the object a and that object will be "garbage collected" by JVM.
It is one of the easiest ways to do this.

Java has a Garbage Collector, it will delete the object for you if no reference is held to it anymore.

//Just use a List
//create the list
public final List<Object> myObjects;
//instantiate the list
myObjects = new ArrayList<Object>();
//add objects to the list
Object object = myObject;
myObjects.add(object);
//remove the object calling this method if you have more than 1 objects still works with 1
//object too.
private void removeObject(){
int len = myObjects.size();
for(int i = 0;i<len; i++){
Objects object = myObjects.get(i);
myObjects.remove(object);
}
}

Related

How to make object null by having only its reference in array?

I have an array of game objects in the GameWorld and they can get removed from that world. The problem is that some game objects have references to other game objects. E.g. Player class has a reference to a Bird. Bird gets randomly removed from GameWorld, but Player still has a reference to it. I currently do a null check to check whether the GameObject is still valid and in the world. However, removing an object from the array does not make that reference null. So how can I make it null?
Here is an example:
// GameWorld creates bird
ArrayList<Object> gameObjects = new ArrayList<>();
Object bird = new Object();
gameObjects.add(bird);
// Player references it
Object referencedBird = gameObjects.get(0);
// later in GameWorld, another scope, there is no access to the 'bird' object, trying to remove the bird from the world
Object objectToRemove = gameObjects.get(0);
gameObjects.remove(0);
objectToRemove = null;
// back in the Player class
Debug.log("is null " + (referencedBird == null)); // false! I need it to be true
You can't make an object null, you can only make a reference null. Updating one reference to an object doesn't change other references to the same object.
Think about it like us both having the same person's number in our phones: if I delete the number, it doesn't get deleted from your phone. And if we both delete it, that person's phone number doesn't cease to exist: just neither of us can call them.
The only things you can do are:
Set referencedBird = null explicitly;
Or refer to it via gameObjects.get(0) instead of via the referencedBird variable.
Okay since Andy pointed out that you can not destroy a object itself you can still have a work-around.
interface RemoveAble<T>{
boolean isRemoved();
T prepareRemoveAndGet();
}
class Bird implements RemoveAble<Bird>{
boolean shouldRemove = false;
#Override
public boolean isRemoved() {
return shouldRemove;
}
#Override
public Bird prepareRemoveAndGet() {
shouldRemove = true;
return this;
}
}
And use it like this:
// GameWorld creates bird
ArrayList<RemoveAble> gameObjects = new ArrayList<>();
Bird bird = new Bird();
gameObjects.add(bird);
// Player references it
Bird referencedBird = gameObjects.get(0);
// later in GameWorld, another scope, there is no access to the 'bird' object, trying to remove the bird from the world
Object objectToRemove = gameObjects.get(0).prepareRemoveAndGet;
// back in the Player class
Debug.log("is null " + (referencedBird.isRemoved == true)); // false! I need it to be true
And then null it by yourself
e.g.
if(referencedBird.isRemoved) referencedBird = null;
First you need to better understand how Java variables work:
I you set a variable to null that does not affect the object behind it at all. You would need to somehow invalidate the referenced object (using a boolean variable) or the better solution would be to always get the object directly from the ArrayList.
Unlike C and C++ in java you cant manipulate memory directly, the only option you have is to remove all the Strong (regular) reference to obj and leave to JVM to remove it from memory whenever it needs memory.
// GameWorld creates bird
ArrayList<Object> gameObjects = new ArrayList<>();
Object bird = new Object();
gameObjects.add(bird);
// a weak reference to array Item
WeakReference<Object> referencedBird = new WeakReference(gameObjects.get(0));
// manipulating and accessing array item via weak reference
referencedBird.get().toString();
// after this remove there is no strong reference to array element (0) and it is available for JVM to revoke
//memory allocated to it in up-coming garbage collection cycle
gameObjects.remove(0);
//garbage collection may remove the obj from memory so this method may return null
referencedBird.get();
Also you have the option to make your gameObjects list, memory efficient by making array of type WeakReference
ArrayList<WeakReference> weakReferenceToGameObjects = new ArrayList<>();
Object bird1 = new Object();
weakReferenceToGameObjects.add((WeakReference) bird1);
bird1 = null;
// now if you try to get the element you may get null!
weakReferenceToGameObjects.get(0).get();

Delete Reference of Inner Class [duplicate]

I want to delete an object I created, (a oval which follows you), but how would I do this?
delete follower1;
didn't work.
EDIT:
Okay, I'll give some more context. I'm making a small game with a oval you can control, and a oval which follows you. Now I've got files named: DrawPanel.class, this class draws everything on the screen, and handles collisions, sounds, etc. I got an enemy.class, which is the oval following the player. I got an entity.class, which is the player you can control. And if the player intersects with the follower, I want my player object to get deleted. The way I'm doing it:
public void checkCollisions(){
if(player.getBounds().intersects(follower1.getBounds())){
Follower1Alive = false;
player.health = player.health - 10;
}
}
You should remove the references to it by assigning null or leaving the block where it was declared. After that, it will be automatically deleted by the garbage collector (not immediately, but eventually).
Example 1:
Object a = new Object();
a = null; // after this, if there is no reference to the object,
// it will be deleted by the garbage collector
Example 2:
if (something) {
Object o = new Object();
} // as you leave the block, the reference is deleted.
// Later on, the garbage collector will delete the object itself.
Not something that you are currently looking for, but FYI: you can invoke the garbage collector with the call System.gc()
Your C++ is showing.
There is no delete in java, and all objects are created on the heap. The JVM has a garbage collector that relies on reference counts.
Once there are no more references to an object, it becomes available for collection by the garbage collector.
myObject = null may not do it; for example:
Foo myObject = new Foo(); // 1 reference
Foo myOtherObject = myObject; // 2 references
myObject = null; // 1 reference
All this does is set the reference myObject to null, it does not affect the object myObject once pointed to except to simply decrement the reference count by 1. Since myOtherObject still refers to that object, it is not yet available to be collected.
If you want help an object go away, set its reference to null.
String x = "sadfasdfasd";
// do stuff
x = null;
Setting reference to null will make it more likely that the object will be garbage collected, as long as there are no other references to the object.
You don't need to delete objects in java. When there is no reference to an object, it will be collected by the garbage collector automatically.
You can remove the reference using null.
Let's say You have class A:
A a = new A();
a=null;
last statement will remove the reference of the object a and that object will be "garbage collected" by JVM.
It is one of the easiest ways to do this.
Java has a Garbage Collector, it will delete the object for you if no reference is held to it anymore.
//Just use a List
//create the list
public final List<Object> myObjects;
//instantiate the list
myObjects = new ArrayList<Object>();
//add objects to the list
Object object = myObject;
myObjects.add(object);
//remove the object calling this method if you have more than 1 objects still works with 1
//object too.
private void removeObject(){
int len = myObjects.size();
for(int i = 0;i<len; i++){
Objects object = myObjects.get(i);
myObjects.remove(object);
}
}

when object will be eligible for garbage collecion

A method given to me and asked, when it will be eligible for Garbage Collection, i mean at which line. I believe both o and oa are eligible for garbage collection. Since, they are set to null. Please correct me, if i'm wrong. But, the question was, when it will be eligible for gc, i mean at which line. ?
public Object m() {
Object o = new Float(3.14F);
Object[] oa = new Object[1];
oa[0] = o; /* Line 5 */
o = null; /* Line 6 */
oa[0] = null; /* Line 7 */
return o; /* Line 8 */
}
Please anyone explain. ?
Let us walk through the code:
1) o = new Float();
2) oa = new Object[];
at this point we have 2 objects.
3) oa[0] = o;
at this point oa[0] holds the reference of o.
4) o = null;
o is still being referenced by oa[0]
5) oa[0] = null
o now has zero references.
6) return o;
o is null.
Line 7 is where the GC eligibility happens for o. oa is not eligible for GC until the function exits.
In general, an object is only eligible for GC when there are no references left to it. Be very careful when dealing with a String as there is a special place called the String pool. So the following code:
void foo()
{
String s = "foo";
s=null;
return s;
}
At no point is s guaranteed to be eligible in the function.
Question from comments
one question, you said..oa is not eligible for GC until the function
exits. but, before the return o, oa set to be null and it nowhere
referred too
Answer:
oa is not set to null. What gets set to null is the object at oa[0]
(the first index of oa). If the line was oa = null that would be true,
and irrespective of the only item in oa being null, does not in fact
make the wrapper (in this case an array) null. Similar to having a
List and nulling out all of its elements does not make the List null.
Java is allowed to do certain optimizations, so an optimizing JIT that reasons only about local-effects could simplify this code to
public Object m() {
//Object o = // o does not participate in any externally visible side-effect
new Float(3.14F); // Available for collection as soon as ctor finishes.
//Object[] oa = new Object[1]; // Array ctors are known not to have side-effects, and oa does not participate in a side-effect or result that is visible outside the method.
//oa[0] = o; /* Line 5 */ // Side-effect not visible.
// o = null; /* Line 6 */ // Side-effect not visible.
//oa[0] = null; /* Line 7 */
//return o; /* Line 8 */ // Eliminated by inlining.
return null; // Type-analysis proves that this method can only return null.
}
Don't assume that assignments of local variables to null actually happen in long-lived method calls.
Garbage collection is eligible when no reference to that object exists any longer, but it can be important to note that GC is not guaranteed to run at that time, so technically the memory can be allocated.
oa[0] refers to the object, so when you set it to null at line 7, no reference to that object exists any longer, so it is eligible for GC.
As pointed out on comments, oa, the array itself, is still around until the method is done executing, i.e. after line 8 executes. It is local to the lifetime of the method m(), so it will be eligible for GC when m() returns from execution.
Please correct me, if i'm wrong. But, the question was, when it will be eligible for gc, i mean at which line. ?
The question is nonsensical or based upon an over-simplified model of garbage collection. Garbage collectors act at run-time on the available representation which means tracing reachability from global roots including the registers, stack and global variables. There is no correspondance with high-level source code so it does not make sense to ask about line numbers. In reality, the compiler will mangle your code beyond all recognition before the GC runs.
AFAIK, Java uses the Mark-And-Sweep algorithm. The GC runs in a separate thread over the heap repeatedly.
If a certain reference variable(or object) goes out of scope, its marked for deletion and sweeped off when appropriate(or overwritten).
Also whenever the variable is set to null, that is when the reference count object becomes unreachable by static references and other threads, that is when its reference no longer exists, its marked for deletion again.
Line7 in your code is where it will be marked for deletion.

Garbage collection of referenced objects in Java

I have the following code:
class Test {
public static void main(String[] args) {
String a,b,c;
a = new String(args[0]);
b = a;
a = null;
b = null;
}
}
Can someone tell me when a will be eligible for garbage collection. I think it's after b is made null because don't a and b reference the same object ?
Pitching my answer too. As the other answers say, the String/ object is available for Garbage Collection once it is no longer accessible (you no longer have a handle to it).
So if you had a one-direction linked list... [1] -> [2] -> [3] and you had a handle to [1] (which has a handle to [2] and onwards). If you set your handle to [1] to null, you would put the entire list available to the Garbage collector. As this answer says, you are able to call System.gc() to request the Garbage Collector run, but it is not guaranteed that it will.
I believe the main focus to this answer is that objects are available to the garbage collector when they are inaccessible and that does not necessarily mean that there are no references to it. In my above example, even though [1] had a handle to [2], [2] was available for the garbage collector because there was no handle to [1].
The object you've created, new String(args[0]);, will be eligible for collection once there are no longer any references to it. So let's step through the code:
a = new String(args[0]);
a points to your String, it is not eligible for collection.
b = a;
a and b point to your String, not eligible.
a = null;
b points to your String, not eligible.
b = null;
No references to your String, Garbage Colelctor is happy!
What do you mean by a? a is a reference, and only objects are garbage collected.
The string referenced by a, and then b, is eligible for garbage collection when nothing references it anymore. In this case, this is after both references to the string (a and b) have been changed to reference something else; in this case, null.
You must reason in terms of allocated objects: the String you allocated is not referenced by anyone as soon as you nullify both a and b. From thereon the garbage collector is entitled to do its job.
class Test {
public static void main(String[] args) {
String a,b,c; // you dont have objects yet
a = new String(args[0]); // here u make a new object
b = a; // b references to the same object as a
a = null; // a points to null, reference is removed.
b = null; // b point to null, reference is removed
}
}
in your program the object that was created and assigned to a and b will be garbage collected after references are removed.
Garbage collector will clean up the object that has no roots and not being referenced by anything.

Which object will be garbage collected?

I wish to confirm which scenario will cause a Garbage Collection on the object myObj:
Scenario 1
ArrayList arList = new ArrayList();
while(someCondition)
{
myObj = new MyObect(); // a custom object
arList.add(myObj);
}
Scenario 2
ArrayList arList = new ArrayList();
while(someCondition)
{
myObj = new MyObect(); // a custom object
arList.add(myObj);
myObj=null;
}
Does explicitly setting an object as null improves garbage collection behavior or will be it same when I reset the object using the new constructor ?
You don't specify the scope of myObj and its important. If its a local variable it almost certainly doesn't matter. If its an instance variable then that could be a long-lived and unnecessary reference in which case setting to null will be useful.
Update: given the updated information that myObj is local to the method, it will be of zero value to set it to null at the end of each iteration of the loop. Consider this example:
public void process(String text) {
String[] lines = text.split("\n");
List<MyObject> list = new ArrayList<MyObject>();
Object myObj;
for (String line : lines) {
myObj = new MyObject(line);
list.add(myObj);
// 1. set myObj = null here
}
list = null; // 2
// 3. do some other stuff
}
public class MyObject {
private final String line;
public MyObject(String line) {
this.line = line;
}
}
Now in this example, let's say that at step 3, it took a long time. Say 10 minutes. During that 10 minutes myObj is pointing to the last line processed. Doesn't sound like a problem? Well it could be. The way substrings work in Java is that they reference the original string. So if you do:
String s = ... // 100 megabytes
String s2 = s.substring(100, 101);
you're actually keeping the entire 100MB in memory because s2 references s.
So in the function I have above, myObj references a line which references the entire file. Changing step 1 to myObj = null; would actually help that because this reference is preventing the object being garbage collected.
Note: step 2 is important here because if you didn't nullify the list all the references would exist anyway.
You just need to think about how references work. An object won't be garbage collected while a reference to it exists. This means clearing long-lived references and keeping variables scoped as tightly as possible. The correct solution for the above is:
for (String line : lines) {
Object myObj = new MyObject(line);
...
}
and then myObj is scoped inside the loop so as soon as the loop ends or another iteration begins it has gone out of scope, which is much better.
Setting it to null will have no effect, since the object is still reachable via arList.
That is, your MyObect instances will live at least as long as arList.
EDIT: Based on your comment, it does sound like myObj is longer-lived. In that case, set it to null after the end of your loop.
I think that this is the root of your misunderstanding.
hmm.. but I don't wish to keep 2 copies of myObj , one in arList and one in the original variable. How can I flush myObj once I add it to arLsit ?
You do NOT "keep two copies of myObj". In your examples, there is only ever one "copy" of each MyObject instance created by the loop. The sequence is:
You create a MyObject instance, assigning its reference to myObj.
You add the reference to the instance to the ArrayList that arList refers to.
You assign null to the reference in myObj.
Note that adding the reference to the list does NOT create a copy of the MyObject instance. It simply means that that you have the reference in two places instead of
one. And when you assign the null you once again have the reference in just one place.
The other thing to note is that assigning null to something will never CAUSE the garbage collector to run. All it does is to (explicitly) remove a potential copy of a reference from consideration the next time the garbage collector is run.
Finally, if we assume that the scoping is as follows, then the line C will have no discernible effect ... unless either line A or line B triggers a garbage collection.
{
MyObject myObj;
ArrayList arList = new ArrayList();
while (someCondition) { // A
myObj = new MyObect(); // B
arList.add(myObj);
myObj = null; // C
}
}
Because it is in a while, myObj is always overwritten (the reference). So in Scenario 1 only one object (the last added in arList) will not be null.
It would be better if you declare it in the while statement:
while(someCondition)
{
MyObect myObj = new MyObect(); // a custom object
arList.add(myObj);
}

Categories

Resources