r/javahelp • u/_SuperStraight • Apr 27 '26
Does Supplier.get() gets garbage collected after its job is done
Suppose I have a class ServiceImpl and it may use an instance of some worker class, say InitWorker depending on whether some database is empty in a method called init:
class ServiceImpl{
private final Service<InitWorker> worker;
public ServiceImpl(Service<Initworker> worker){
this.worker = worker;
}
public void init(){
int recordsCount = getRecordsFromDatabase();
if(recordsCount ==0){
worker.get().initFromExternalFile("external_file.xlsx");
}
}
}For some reason, the init() method cannot have the InitWorker as a parameter (the method calling it cannot provide an instance).
My question is, does the instance of worker.get() stays in the memory, or only the supplier reference (which should be smaller in size) remains after init finishes?
8
Upvotes
View all comments
Show parent comment
1
u/_SuperStraight Apr 28 '26
Since
workeris a global variable inside ServiceImpl, then it won't be garbage collected as long as ServiceImpl itself is being referenced by some other class. But the InitWorker which worker calls via get(), will it also reside as well?As for clarity, Suppose a ServiceFactory is responsible for providing instance of ServiceImpl: