简体   繁体   中英

Making simultaneous function calls in Java

In my application I am loading a cache in following manner.

  1. Load user cache loadUserCache();
  2. Load account cache loadAccountCache();
  3. Load customer cache loadCustomerCache();

Each above call involves a database calls. Like wise there are 6-7 calls.

When my application is getting loaded , I have to wait untill the cache gets loaded.

Those are all sequential call one after another.

If I can find a way to make these calls parallelly, then the waiting time during application loading will come down drastically.

Can someone please help me making such parallel call or any other alternative approach?

Thanks in advance.

You are looking for multithreading. Have a look at the official tutorial for concurrency .

Create a Thread , and override runnable.

When you invoke start() on the thread, each thread will be invoked parallel of each other.

An alternative is using the high-level concurrency API , especially Executors .

You will have to make sure you don't have data races and/or dead-locks in the parallel program however! [which might not be trivial if there is some dependency between tasks].

You could use the executor framework:

public static void main(String args[]) throws InterruptedException {
    ExecutorService executor = Executors.newFixedThreadPool(3);
    Runnable user = new Runnable() {
        @Override
        public void run() {
            loadUserChache();
        }
    };
    Runnable account = new Runnable() {
        @Override
        public void run() {
            loadAccountCache();
        }
    };
    Runnable customer = new Runnable() {
        @Override
        public void run() {
            loadCustomerCache();
        }
    };

    executor.submit(user);
    executor.submit(account);
    executor.submit(customer);

    executor.shutdown();
    executor.awaitTermination(10, TimeUnit.SECONDS); //handle timeout here
}

Launch a new Thread for each block of code you want to run in parallel.

    new Thread(new Runnable(){
       loadUserCache();
    }).start();

    new Thread(new Runnable(){
       loadAccountCache();
    }).start();

    new Thread(new Runnable(){
       loadCustomerCache();
    }).start();

Or

    new Thread(new Runnable(){
       loadUserCache();
       loadAccountCache();
       loadCustomerCache();
    }).start();

Yes, this general topic can quickly open up all sorts of issues. Multi-Threaded code can be quite complicated, but in your case, the above may be just fine.

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