Search code examples
javamultithreadingblocking

Remove blocking from a method


This is homework.

I do not want the solution, just a small number of links or ideas.

Simply speaking what I want to do is,

Simple example :

public class Example
{
    public void method()
    {
           int x = doThat();
           //Call other methods which do not depend on x
           return;
    }
}

doThat() is a method that is known to be time consuming, which results in my program blocking until results are back. And I want to use different methods of this Object, but program is frozen until doThat() is finished. Those different methods do not necesserely have to be invoked from the method() used in this example, but maybe from outside the object.

I thought about using threads but if I have a huge number of objects (1000+) this probably wont be very efficient (correct me if I am wrong please). I guess if I use threads I have to use one thread per object ?

Is there any other way besides threads that can make the invoking object not block when calling doThat(); ? If threading is the only way, could you provide a link ?

Knowing questions like that get downvoted I will accept any downvotes. But please just a link would be more than great.

Thanks in advance. I hope question is inline with the rules.


Solution

  • I'd also use threads for this, but I simply wanted to add that it would probably be interesting to look at java.util.concurrent.Executors (to create thread pools as you have a number of objects) and the java.util.concurrent.Future and java.util.concurrent.Callable classes which will allow you to launch threads that can return a value.

    Take a look at the concurrency tutorial for more info.