coder
coder

Reputation: 1941

Multithreading best practices in java

I'm new to Java programming. I have a use case where I have to execute 2 db queries parallely. The structure of my class is something like this:

class A {
    public Object func_1() {
        //executes db query1
    }

    public Object func_2() {
        //executes db query1
    }
}

Now I have a add another function func_3 in the same class which calls these 2 functions but also makes sure that they execute parallely. For this, I'm making use callables and futures. Is it the right way to use it this way? I'm storing the this variable in a temporary variable and then using this to call func_1 and func_2 from func_3(which I'm not sure is correct approach). Or is there any other way to handle cases like these?

class A {
    public Object func_1() {
        //executes db query1
    }

    public Object func_2() {
        //executes db query1
    }

    public void func_3() {
        final A that = this;
        Callable call1 = new Callable() {
            @Override
            public Object call() {
               return that.func_1();
            }
        }

        Callable call2 = new Callable() {
            @Override
            public Object call() {
               return that.func_2();
            }
        }
        ArrayList<Callable<Object>> list = new ArrayList<Callable<Object>>();
        list.add(call1);
        list.add(call2);
        ExecutorService executor = Executors.newFixedThreadPool(2);
        ArrayList<Future<Object>> futureList = new ArrayList<Future<Object>>();
        futureList = (ArrayList<Future<Object>>) executor.invokeAll(list);
        //process result accordingly
    }
}

Upvotes: 6

Views: 1315

Answers (2)

Alexei Kaigorodov
Alexei Kaigorodov

Reputation: 13525

The whole idea of Executor(Service) is to use small number of threads for many small tasks. Here you use 2-threaded executor for 2 tasks. I would either create globally defined executor, or just spawn 2 threads for 2 tasks.

Upvotes: 0

Daniil
Daniil

Reputation: 5780

First of all, you do NOT need to store this in another local variable: outer functions will be available just as func_1() or func_2() and when you want to get this of outer class you just use A.this.

Secondly, yes, it is common way to do it. Also, if you are going to call func_3 often - avoid creating of fixed thread pool, you should just pass it as params, since thread creation is rather 'costly'.

Upvotes: 5

Related Questions