简体   繁体   中英

how to execute stored procedure asynchronously using JAVA

I want to call one Stored Procedure from java function asynchronously that means my function should not wait whether that Stored Procedure executed or not. It should simply call that Stored Procedure and it should not wait for execution. I have tried with thread, Is there any other way to execute stored procedure asynchronously?

public void callLogonDetailSP(UserDetails userInfoSharedObject) {
        new Thread(() -> {
            int i = logonUserDetailsRepository.callLogonDetailSP(userInfoSharedObject.userName, userInfoSharedObject.password, userInfoSharedObject.userCityName);

        }).start();

    }

A more advanced alternative to Thread objects are Executor services. More info here:

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html

These can be created with the static methods of the Executors class. Some of the like newSingleThreadExecutor() manages 1 thread, but if more is needed you can use newFixedThreadPool(int n) which will create an executor service managing n threads.

These classes also use a Future object which represents the result of your task (the result is not yet calculated but you get a reference to it anyways, hence the name).

ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<Integer> c = new Callable<>() {
    @Override public Integer call() {
         return 0; //do some task here that returns an integer
    }
}; 
Future<Integer> future = executor.submit(c);

Notice that both Callable and Future are generic so you can use any class as the result of your background task.

FOR ANDROID: If you develop for android you can use the AsyncTask as well. Very useful, since normally the android UI elements can only be modified from the UI thread, but this class provides methods that run AFTER your task was completed and on the UI thread.

https://developer.android.com/reference/android/os/AsyncTask

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