Reputation: 109
I am creating object via method. Then I want to "destroy" it. I need to somehow remember a reference to specified object to call destroy()
on it? How do I do it?
public class Obj {
private int size;
private boolean exist;
private Obj(int size) {
this.size = size;
this.exist = true;
}
public static Obj getObj(int size) {
Obj s = new Obj(size);
return s;
}
public void destroy() {
exist = false;
}
}
Upvotes: 1
Views: 516
Reputation: 12751
The other answers seem to be trying to educate you about garbage collection.
But to answer your actual question... In your code, you will need to call the factory method and assign the result to a variable: Obj obj = Obj.getObj(1234)
. This is your reference to the object. When you want to call the destroy()
method you use that reference.
For example:
public class Main {
public static void main(String[] args) {
Obj obj = Obj.getObj(42);
obj.destroy();
}
}
Upvotes: 0
Reputation: 147164
So, your method creates an resource, some other entity operates on it and then you release the resource. Am I warm?
In that case, the clean approach is to pass the code that operates on the object through as a function object, so you can definitely clean up as it exits. The general idea is called Execute Around.
import java.util.function.Consumer;
public static void getObj(int size, Consumer<Obj> consumer) {
Obj s = new Obj(size);
try {
consumer.accept(s);
} finally {
s.destroy();
}
}
Use as:
Obj.getObj(1066, s -> {
... something with s ...;
});
Alternatively there is java.lang.AutoCloseable
and try-with-resource which places responsibility on the caller so is best avoided if possible.
In any case, attempting to pool mutables in a static is generally a very bad idea.
Upvotes: 1
Reputation: 757
If you want to remember a reference of a variable with in a class, you can declare it in class level and use it in initialise and destroy methods
class Obj {
private static Obj s;
public static int getObj(){
s=new Obj();
}
public void destroy (){
s=null;
}
}
Upvotes: 0
Reputation: 5742
The garbage collector should do it for you... however if you want to call destroy implicitly, you can define a class level list of all instances
public class Obj {
private int size;
private boolean exist;
private static List<Obj> list = new ArrayList<>();
private Obj(int size) {
this.size = size;
this.exist = true;
}
public static Obj getObj(int size) {
Obj s = new Obj(size);
list.add(s) // save ref
return s;
}
public void destroy() {
exist = false;
}
}
Upvotes: 0