Thursday, November 16, 2006

Thread pooling in Java 5

Only recently I began learning (and working with) Java 5's new features. When they announced the most emblematic new features there was an immediate reaction to them. Some people loved the new features, others hated it. To be true, I liked some things (like enumerations and generics) but never cared much about auto-boxing or varargs. However, I'm not going to talk about these popular features that almost everyone has heard of. It seems there's plenty more to know about Java 5. Today I discovered a fantastic (first impressions) and powerful new feature: java.util.concurrent package. This package provides several utilities to handle threads and locks, simplifying the whole process. For now I only tried one thing: creating thread pools. This is something that comes in handy very often and it's now very simple to do.

First, you have the usual Runnable that implements whatever you want the thread to do. In this simple example it just prints "hello".


public class WorkerThread implements Runnable {
public void run() {
System.out.println("hello");
}
}

Now, let's imagine I want to create 300 WorkerThread s, but allowing only 5 threads simultaneously. So, a thread pool has to be created with size 5. Then I submit the 300 tasks to the pool, which only executes 5 at a time, queuing the rest. As one thread finishes, the next one in the queue starts.

ExecutorService pool = Executors.newFixedThreadPool(5);
for(int i=0; i<300; i++){
pool.submit(new WorkerThread());
}

As simple as that. But there's a lot more to learn. For example, there's a new interface Callable, that you can use instead of Runnable. Callable allows the executing method to return arbitrary Objects and throw exceptions, something you couldn't do with Runnable's run() method. Look here for more information about this and other cool enhancements that didn't get the overall attention they deserve.

2 comentários:

Anonymous said...

good post helped in searching what i was looking for...:)

Anonymous said...

Добро пожаловать на сайт [url=http://theloveland.ru/]знакомства мамба[/url] Сайт входит в единый сервис знакомств, очень знаменитый в России и странах СНГ. Заходите, регистрируйтесь - здесь вас ожидают приятные знакомства, романтические встречи и настоящая любовь!!!