Java multithreading guidelines

I am new to Java programming. I have a use case when I need to execute 2 db requests in parallel. The structure of my class looks something like this:

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

Now I have another func_3 function in the same class that calls these 2 functions, but also ensures that they are executed in parallel. For this, I use callables and futures. Is it right to use? I save this variable in a temporary variable and then use it to call func_1 and func_2 from func_3 (which I'm not sure if this is the right approach). Or is there any other way to deal with such cases?

 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 } } 
+6
source share
2 answers

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

Secondly, yes, this is the usual way to do this. Also, if you often call func_3 - avoid creating a fixed pool of threads, you should just pass it as params, since creating threads is rather expensive.

+5
source

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

0
source

All Articles