Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }
}
like image 387
coder Avatar asked Dec 27 '12 16:12

coder


1 Answers

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'.

like image 61
Daniil Avatar answered Sep 22 '22 20:09

Daniil