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
2
u/vowelqueue Apr 28 '26
In that case, there would be no reference to the InitWorker once init() completes so it could be garbage collected.