[Java] Threading and Concurrency

In one of my Java web service, I have a slow method in a class which read caffe model,do deep neural network application and then save the result.

However, the service is a real-time service that I don’t want the slow method to delay the others from executing. I have used some asynchronous method and concurrency tasks in C#. That’s why I search for concurrency method in Java. My objective is creating a new thread which runs the slow method as a task and save the result back to the original class.

example code:

 new Thread(new Runnable() {
    public void run() {
        //Do whatever
    }
}).start();

my code: (written with in a method)

new Thread(new Runnable() {
    public void run() {
        try {
            recommender = new Recommend(path);
            recommender.recommend(img_recommend, recommend_x, recommend_y, recommend_w, recommend_h);
            recommend_initialized = true;
            recommend_initializing = false;
            System.out.println("Initialize recommendation result successfully!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}).start();

This method creates a new thread and a new runnable which contains the function you want to run asynchronously. This is exactly what I want.

The asynchronous code read a pre-trained caffe model and use it to recommend a result for an image which takes almost 10 second to execute on an Intel i7 desktop. By doing threading, these operation will no longer delay the others and the service runs smoothly.

Observe that the asynchronous code in this new thread could also call the class member variables and save results to class member variables, which is very good and convenient.

 

Some reference link:

Java 8 Concurrency Tutorial: Threads and Executors

How to asynchronously call a method in Java

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: