PDA

View Full Version : JDK 5 generic type & concurrency programming



bluedolphincp
Jul 4th, 2007, 07:35 PM
I am leaning concurrency programming in jdk 5, and ran into trouble with Executor framework, actually, it's a generic type problem.

I want to use Executor.invokeAll to execute a collection of tasks, the signature of this method is:

<T> List<Future<T>> invokeAll(Collection<Callable<T>> tasks, long timeout, TimeUnit unit)

My task class is:

class LongTask implements Callable<Integer>{

...

}

My problems are:

1) I have to define the collection of the tasks as:


List<Callable<Integer>> tasks=new ArrayList<Callable<Integer>>();

I can't just say:


List<LongTask> tasks=new ArrayList<LongTask>();

If I do this, compiler will refuse to compile the following method:


exec.invokeAll(tasks,(long)6500, TimeUnit.MILLISECONDS);

I get it that List<LongTask> is not a subset of List<Callable<Integer>>, my question is why executor.invokeAll is not defined as the following:


<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)

If it is defined this way, then caller code will have a more natual way of using it.

2) My second question is how can i define a subclass of Callable whose call() method returns void? I tried "class LongTask implements Callable<Void>" and "class LongTask implements Callable<?>", but compiler is not happy with both of them.

Thanks.

bluedolphincp
Jul 5th, 2007, 07:42 PM
Can anyone please kindly help me out?

al0
Jul 6th, 2007, 08:35 AM
I dare say that your mail is a bit off-topic. Here is Spring-devoted forum, and your questions are about pure Java, and not about Spring.

Anyway, first question you have to address to Sun and developes of JDK.
For second question - Callable is defined as task that returns a result (see Javadoc for Callable), so callable without result is a nonsense. You should use Runnable instead. BTW, invokeAll is absent from the Executor, is is present in ExecutorService, but for Callble only, so you are lost with invokeAll(). But you may use submit().

You as well may use java.util.concurrency.Executors.callable(Runnable) to convert Runnable to Callable.

lloyd.mcclendon
Jul 8th, 2007, 01:37 PM
as for the first question, are you aware of the syntax for explicit type parameters?

exec.<LongTask> invokeAll(tasks,(long)6500, TimeUnit.MILLISECONDS);

i didn't bother to get my head around all of that, this may or may not help. I have found it to be quite useful, not a lot of people know it exists.

bluedolphincp
Jul 8th, 2007, 07:58 PM
exec.<LongTask> invokeAll(tasks,(long)6500, TimeUnit.MILLISECONDS);

I tried that, but it didn't work either.