3

Here is the situation:

I want to use a multithreaded approach to store some feature vectors corresponding to images to a database. The problem is that with my given implementation (I am using a fixed thread pool) I don't have any guarantee of the order the output. Since I am giving an increasing number as index to where to place the vector inside the db this affects the order and make it inaccessible.

If some more details make the problem clearer:

  • I have a lot of vectors stored as csv files 1 file per image/vector.
  • Each task is reading the csv file, calculates some other indices
  • Using an implemetation of Runnable to read, calculate the indices etc and it
  • Calls a synchronized method to make the actual indexing in the db.

Is there a way to enforce the order of the outputs to be the same as the order of the submitted tasks? In other words if the vector i is submitted first then the vector i should be indexed first.

1 Answer 1

3

Use an ExecutorService to create the tasks in order.

Use executor.invokeAll to invoke (start) the threads / tasks.

Use future.get() to the results of the tasks in the order it was submitted.

ExecutorService executor = Executors.newFixedThreadPool(numberOfThread);
        List<Task> threads = new ArrayList<>();
        // create the threads
        for (Integer key_ : dbIdList) {
            threads.add(new Task(key_));
        }
        try {
            //launch the threads
            List<Future<String>> futures = executor.invokeAll(threads);
            //read results
            for (Future<String> future_ : futures) {
                System.out.println(future_.get()); // this preserves the order of the tasks

            }

        } catch (Exception e) {

        } finally {
            //shut down
            executor.shutdown();
        }

Thread class which does the task:

class Task implements Callable<String> {

    Integer dbId = null;

    @Override
    public String call() throws Exception {
    //do whatever works needs to be done
        return output;
    }

    public Task(int dbId_) {
        this.dbId = dbId_;
    }

}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.