简体   繁体   中英

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:

@AllArgsConstructor
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?

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 (eg database down, etc.)

Future is only an interface. It's up to individual implementations how they provide the methods cancel() , get() , isCancelled() and done() .

You could, for example, write a method which returns a Future which just does the job synchronously:

    public Future<Void> print(String x) {
        System.out.println(message);
        return new Future<Void>() {
            @Override
            public boolean cancel(boolean mayInterruptIfRunning) {
                return false;
            }

            @Override
            public boolean isCancelled() {
                return false;
            }

            @Override
            public boolean isDone() {
                return true;
            }

            @Override
            public Void get() throws InterruptedException, ExecutionException {
                return null;
            }

            @Override
            public Void get(long timeout, TimeUnit unit)
                    throws InterruptedException, ExecutionException, TimeoutException {
                return null;
            }
        };
    }

Equally you could write your own implementation that doesn't do the work until get() is called! (This isn't good code in a multi-threaded context, but it's illustrates the point):

 public Future<Void> foo(String x) {
        return new Future<Void>() {

            private boolean done = false;

            @Override
            public boolean cancel(boolean mayInterruptIfRunning) {
                return false;
            }

            @Override
            public boolean isCancelled() {
                return false;
            }

            @Override
            public boolean isDone() {
                return done;
            }

            @Override
            public Void get() throws InterruptedException, ExecutionException {
                System.out.println(message);
                done = true;
                return null;
            }

            @Override
            public Void get(long timeout, TimeUnit unit)
                    throws InterruptedException, ExecutionException, TimeoutException {
                return get();
            }
        };
    }

DBPersister is either a from a third-party library, or something of your own. We can't guess how it has implemented Future .

A mainstream of example of something that returns Future s is ExecutorService . A typical ExecutorService will keep running until something calls its shutdown() , whereupon it will stop accepting new tasks, process what's on its queue, then terminate. The JVM won't stop until the last thread has finished.

However, Runtime.exit() has the potential to abruptly kill everything. Avoid calling it; or if you can't avoid it, learn about shutdown hooks.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM