I am trying to understand, at a fundamental level, what will happen to the local variable being passed to the thread in the following situation. I need a cleanup action to happen on someObject
which has a delete
method, which calls an external API to delete the instance of someObject by its member, id
.
public interface Deleteable {
public delete()
}
public SomeClass implements Deleteable {
int id;
public void delete() {
HttpApiCall.deleteById(this.id);
}
}
SomeClass someObject = null;
for(i = 0; i < 3; i++) {
// simple loop to illustrate problem
someObject = new SomeClass();
Runtime.getRuntime()
.addShutdownHook(new Thread(someObject::delete));
}
While the program is executing, will some of the instances of SomeClass be GC'ed before the thread will be able to call delete? Will each thread receive their own copy that was newed or will the operate on the last set value of someObject
?
I read up a little bit about the volatile
keyword but I am not sure it is going to help me here.
No. You are adding these someObject::delete
method references to a collection in Runtime
. Since the Runtime
is still reachable, these objects too are reachable and shouldn't get GCd.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.