Home > Articles > Programming > Java

Creating a Thread Pool with Java

  • Print
  • + Share This
  • 💬 Discuss
Threads are a very important aspect of Java, but creating large numbers of threads can negatively impact program performance. Discover the advantages of thread pools, which allow you to limit the total number of threads running assigned tasks to each of the threads.

This article shows you how to create a thread pool in Java. A complete thread pool is included with this article. This thread pool is extensible enough to be added to your own programs to add thread pool functionality. This article will focus on how the thread pool was created and how it is used.

A thread allows Java to perform more than one task at a time. In much the same way as multitasking allows your computer to run more than one program at a time, multithreading allows your program to run more than one task at a time. Depending on the type of program, multithreading can significantly increase the performance of a program.

When to Use Multithreading

There are two primary cases in which multithreading can increase performance. The first is when the program is run on a multiprocessor computer, which will do little for your program if it is not multithreaded. A multiprocessor computer works by using the multiple processors to handle threads simultaneously. If your program uses only the one thread that all programs begin with, multiple processors will do your program little good because the computer has no way to divide your program among the processors.

The second type of program that greatly benefits from multithreading is a program that spends a great deal of time waiting for outside events. One example of this is a Web crawler, which must visit a Web page and then visit all of the links on that page. When crawling a large site, your program must examine a considerable amount of pages. Requesting a Web page can take several seconds—even on a broadband connection. This is a considerable amount of time for a computer to wait for each Web page. If the crawler has a considerable number of pages to visit, these mere seconds can really add up.

It would be much better for the crawler to request a large number of Web pages and then wait for each of these pages at the same time. For example, the program may use 10 different threads to request 10 different Web pages. The program is now waiting for 10 pages, rather than just one. Because the time spent waiting for the page is idle, the program can be waiting for a large number of pages before performance degrades. Also, because the pages are being waited for in parallel, the entire process takes only a fraction of the time that it would when the pages were waited on individually.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus