harshit modani harshit modani - 3 years ago 122
Java Question

In Java, what happens when we return from a function with Future threads in progress?

I wanted to know what happens when we don't wait for Future Tasks to get completed and return before it?
Does the future tasks still completes, or all the threads are killed once I return from function.
For ex:

public class IdGenerator() {
private DBPersister dbPersister;
public String generateId(){
String id = UUID.randomString();
Future<Void> persistIdInDB = dBPersister.persist(id);
return id;

I want to return id to downstream as soon as it gets generated and don't want to wait for storing it in Data base. Does returning from a function kills all future task created in the function? Or I can be assured that the function dbPersister.persist once called will be executed fully? If not, is there any way I can achieve the same in Java?

Answer Source

What you can be sure about when returning from your method is that:

  • dBPersister.persist(id); will be invoked
  • The current thread will not block, as you're not invoking get on your Future<Void>

What will concretely happen in terms of persistence can only be discovered by looking at the implementation of dBPersister.persist(id);, as well as whether persistence was successful due to environmental variables (e.g. database down, etc.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download