I am pretty new to using multithreading, but I want to invoke a method asynchronously (in a separate Thread
) rather than invoking it synchronously. The basic idea is that I'm creating a socket server with an object in memory, so for each client I will have to run something like object.getStuff()
asynchronously.
The two constructs I found were:
- having the class implement Runnable and threading
this
and - declaring a
runnable
class within a method.
Additionally this
method needs a return value- will it be necessary to use Executor
and Callable
to achieve this? Could someone point me in the right direction for implementing this?
I have tried implement option 2, but this doesn't appear to be processing concurrently:
public class Test {
private ExecutorService exec = Executors.newFixedThreadPool(10);
public Thing getStuff(){
class Getter implements Callable<Thing>{
public Thing call(){
//do collection stuff
return Thing;
}
}
Callable<Thing> callable = new Getter();
Future<Thing> future = exec.submit(callable);
return future.get();
}
}
I am instantiating a single test object for the server and calling getStuff() for each client connection.