Java Threads

A pretty cool tutorial at the ibm developer works Concurrency in JDK 5.0. You must register for the tutorial, but is well worth it.

The new java.util.concurrency package offers a lot of cool features which I haven’t completely incorporated in my daily programming practices yet but it is among the new 5.0 features that which will have the most impact on program design.

My latest threading enlightenment is this neat little idiom (of course this enlightenment didn’t come out of nowhere I saw it in several places like the concurrency tutorial mentionned above, the java specialists newsletters mentionned previously on the blog and more ….):

final Executor pool = Executors.newFixedThreadPool(
                THREAD_POOL_SIZE,
                CheckThreadFactory.getInstance());
        
while(!queue.isEmpty()) {                    
   final MyTask task = queue.poll();
   final Runnable runTask = new Runnable() {
      public void run() {
         //perform task blub .... 
         task.methodX();
     }
   };
   pool.execute(runTask);
}

The part I call “idiom” is where you use the anonymous class to perform the computation of your task threaded but the computation code stays where it logically belongs … it is a very obvious thing to do this after seeing it once. It is much easier in structure than my previous construct which included a class implementing Runnable providing the run method and another class to start the thread where the computation was often done in yet a third class … not pretty.

Of course the code snippet contains more than that idiom. I just want to make you drool for the new 5.0 features like ThreadPools and Queues 😉 As far as I understand the package there is something more in there which should provide the functionality of a combined ThreadPool and Queue somehow. But I haven’t “got” it yet.

2 Replies to “Java Threads”

  1. Thanks for the hint. I used a slight variant:


    final String p = "MyProblem";
    final Runnable solve = new Runnable() {
    public void run(){
    solveProblem(p, timeout);
    }
    };
    new Thread(solve).start();

    Works like a charm.

Comments are closed.