Java Threads: Understanding and Mastering Concurrent Programming

Java Threads: Understanding and Mastering Concurrent Programming

Java Threads: Understanding and Mastering Concurrent Programming

Java Threads: Understanding and Mastering Concurrent Programming

eBook

$23.99  $31.99 Save 25% Current price is $23.99, Original price is $31.99. You Save 25%.

Available on Compatible NOOK devices, the free NOOK App and in My Digital Library.
WANT A NOOK?  Explore Now

Related collections and offers


Overview

Threads are essential to Java programming, but learning to use them effectively is a nontrivial task. This new edition of the classic Java Threads shows you how to take full advantage of Java's threading facilities and brings you up-to-date with the watershed changes in Java 2 Standard Edition version 5.0 (J2SE 5.0). It provides a thorough, step-by-step approach to threads programming.Java's threading system is simple relative to other threading systems. In earlier versions of Java, this simplicity came with tradeoffs: some of the advanced features in other threading systems were not available in Java. J2SE 5.0 changes all that: it provides a large number of new thread-related classes that make the task of writing multithreaded programs that much easier.You'll learn where to use threads to increase efficiency, how to use them effectively, and how to avoid common mistakes. This book discusses problems like deadlock, race conditions, and starvation in detail, helping you to write code without hidden bugs.Java Threads, Third Edition, has been thoroughly expanded and revised. It incorporates the concurrency utilities from java.util.concurrent throughout. New chapters cover thread performance, using threads with Swing, threads and Collection classes, thread pools, and threads and I/O (traditional, new, and interrupted). Developers who cannot yet deploy J2SE 5.0 can use thread utilities provided in the Appendix to achieve similar functionality with earlier versions of Java.Topics include:

  • Lock starvation and deadlock detection
  • Atomic classes and minimal synchronization (J2SE 5.0)
  • Interaction of Java threads with Swing, I/O, and Collection classes
  • Programmatically controlled locks and condition variables (J2SE 5.0)
  • Thread performance and security
  • Thread pools (J2SE 5.0)
  • Thread groups
  • Platform-specific thread scheduling
  • Task schedulers (J2SE 5.0)
  • Parallelizing loops for multiprocessor machines
In short, this new edition of Java Threads covers everything you need to know about threads, from the simplest animation program to the most complex applications. If you plan to do any serious work in Java, you will find this book invaluable.Scott Oaks is a senior software engineer for the Java Performance Engineering group at Sun Microsystems and the author of four books in the O'Reilly Java series.Formerly a senior systems engineer at Sun Microsystems, Henry Wong is an independent consultant working on various Java related projects.

Product Details

ISBN-13: 9781449366667
Publisher: O'Reilly Media, Incorporated
Publication date: 09/10/2004
Sold by: Barnes & Noble
Format: eBook
Pages: 362
Sales rank: 924,009
File size: 3 MB

About the Author

Scott Oaks is a Java Technologist at Sun Microsystems, where he has worked since 1987. While at Sun, he has specialized in many disparate technologies, from the SunOS kernel to network programming and RPCs. Since 1995, he's focused primarily on Java and bringing Java technology to end-users. Scott also authored O'Reilly's Java Security, Java Threads and Jini in a Nutshell titles.


Henry Wong is an independent consultant, involved in various Java related projects. Henry previously workedas a computer engineer at Sun Microsystems from 1989to 2003. Originally hired as a consultant to help customers with special device drivers, kernel modifications, and DOS interoperability products, Henry has also worked on Solaris ports, performance tuning projects, and multithreaded design and implementations for benchmarks and demos. Since early 1995, Henry has been involved in developing Java prototypes and supporting customers who are usingJava.

Prior to working at Sun, Henry earned a Bachelor of Science degree in chemical engineering from The Cooper Union in 1987. He joined a small software company in 1986 working on SCSI device drivers, image and audio data compression, and graphics tools used for a medical information system.

When not in front of a computer, Henry is an instrument rated private pilot, who also likes to dabble in archery, cooking, and traveling to different places with his wife, Nini.

Read an Excerpt


Chapter 1: Introduction to Threading

...Why Threads?

The notion of threading is so ingrained in Java that it's almost impossible to write even the simplest programs in Java without creating and using threads. And many of the classes in the Java API are already threaded, so that often you are using multiple threads without realizing it.

Historically, threading was first exploited to make certain programs easier to write: if a program can be split into separate tasks, it's often easier to program the algorithm as separate tasks or threads. Programs that fall into this category are typically specialized and deal with multiple independent tasks. The relative rareness of these types of programs makes threading in this category a specialized skill. Often, these programs were written as separate processes using operating-system-dependent communication tools such as signals and shared memory spaces to communicate between processes. This approach increased system complexity.

The popularity of threading increased when graphical inter-faces became the standard for desktop computers because the threading system allowed the user to perceive better program performance. The introduction of threads into these platforms didn't make the programs any faster, but it did create an illusion of faster performance for the user, who now had a dedicated thread to service input or display output.

Recently, there's been a flurry of activity regarding a new use of threaded programs: to exploit the growing number of computers that have multiple processors. Programs that require a lot of CPU processing are natural candidates for this category, since a calculation that requires one hour on a single-processor machine could (at least theoretically) run in half an hour on a two-processor machine, or 15 minutes on a four-processor machine. All that is required is that the program be written to use multiple threads to perform the calculation.

While computers with multiple processors have been around for a long time, we're now seeing these machines become cheap enough to be very widely available. The advent of less expensive machines with multiple processors, and of operating systems that provide programmers with thread libraries to exploit those processors, has made threaded programming a hot topic, as developers move to extract every benefit from these new machines. Until Java, much of the interest in threading centered around using threads to take advantage of multiple processors on a single machine.

However, threading in Java often has nothing at all to do with multiprocessor machines and their capabilities; in fact, the first Java virtual machines were unable to take advantage of multiple processors on a machine, and many implementations of the virtual machine still follow that model. However, there are also implementations of the virtual machine that do take advantage of the multiple processors that the computer may have. A correctly written program running in one of those virtual machines on a computer with two processors may indeed take roughly half the time to execute that it would take on a computer with a single processor. If you're looking to use Java to have your program scale to many processors, that is indeed possible when you use the correct virtual machine. However, even if your Java program is destined to be run on a machine with a single CPU, threading is still very important.

The major reason threading is so important in Java is that Java has no concept of asynchronous behavior. This means that many of the programming techniques you've become accustomed to using in typical programs are not applicable in Java; instead, you must learn a new repertoire of threading techniques to handle these cases of asynchronous behavior.

This is not to say there aren't other times when threads are a handy programming technique in Java; certainly it's easy to use Java for a program that implements an algorithm that naturally lends itself to threading. And many Java programs implement multiple independent behaviors. The next few sections cover some of the circumstances in which Java threads are a required component of the program, due to the need for asynchronous behavior or to the elegance that threading lends to the problem.

Nonblocking I/O

In Java, as in most programming languages, when you try to get input from the user, you execute a read () method specifying the user's terminal (System.in in Java). When the program executes the read () method, the program will typically wait until the user types at least one character before it continues and executes the next statement. This type of I/O is called blocking I/O: the program blocks until some data is available to satisfy the read () method.

This type of behavior is often undesirable. If you're reading data from a network socket, that data is often not available when you want to read it: the data may have been delayed in transit over the network, or you may be reading from a network server that sends data only periodically. If the program blocks when it tries to read from the socket, then it's unable to do anything else until the data is actually available. If the program has a user interface that contains a button and the user presses the button while the program is executing the read () method, nothing will happen: the program will be unable to process the mouse events and execute the event-processing method associated with the button. This can be very frustrating for the user, who thinks the program has hung.

Traditionally, there are three techniques to cope with this situation:

I/O multiplexing

Developers often take all input sources and use a system call like select () to notify them when data is available from a particular source. This allows input to be handled much like an event from the user (in fact, many graphical tool kits use this method transparently to the user, who simply registers a callback function that is called whenever data is available from a particular source).

Polling

Polling allows a developer to test if data is available from a particular source. If data is available, the data can be read and processed; if it is not, the program can perform another task. Polling can be done either explicitly--with a system call like poll ()--or, in some systems, by making the read () function return an indication that no data is immediately available.

Signals

A file descriptor representing an input source can often be set so that an asynchronous signal is delivered to the program when data is available on that input source. This signal interrupts the program, which processes the data and then returns to whatever task it had been doing.

In Java, none of these techniques is directly available. There is limited support for polling via the available () method of the FilterInputStream class, but this method does not have the rich semantics that polling typically has in most operating systems. To compensate for the lack of these features, a Java developer must set up a separate thread to read the data. This separate thread can block when data isn't available, and the other thread (s) in the Java program can process events from the user or perform other tasks.

While this issue of blocking I/O can conceivably occur with any data source, it occurs most frequently with network sockets. If you're used to programming sockets, you've probably used one of these techniques to read from a socket, but perhaps not to write to one. Many developers, used to programming on a local area network, are vaguely aware that writing to a socket may block, but it's a possibility that many of them ignore because it can only happen under certain circumstances, such as a backlog in getting data onto the network. This backlog rarely happens on a fast local area network, but if you're using Java to program sockets over the Internet, the chances of this backlog happening are greatly increased; hence the chance of blocking while attempting to write data onto the network is also increased. So in Java, you may need two threads to handle the socket: one to read from the socket and one to write to it...

Table of Contents

Preface
1. Introduction to Threading
Java Terms 1
Thread Overview 3
Why Threads? 6
Summary 11
2. The Java Threading API
Threading Using the Thread Class 12
Threading Using the Runnable Interface 19
The Life Cycle of a Thread 24
Thread Naming 28
Thread Access 30
More on Starting, Stopping, and Joining 34
Summary 37
3. Synchronization Techniques
A Banking Example 40
Reading Data Asynchronously 44
A Class to Perform Synchronization 49
The Synchronized Block 53
Nested Locks 55
Deadlock 58
Return to the Banking Example 61
Synchronizing Static Methods 63
Summary 65
4. Wait and Notify
Back to Work (at the Bank) 67
Wait and Notify 68
wait(), notify(), and notifyAll() 74
wait() and sleep() 77
Thread Interruption 79
Static Methods (Synchronization Details) 85
Summary 86
5. Useful Examples of Java Thread Programming
Data Structures and Containers 88
Simple Synchronization Examples 93
A Network Server Class 101
The AsyncInputStream Class 108
Using TCPServer with AsyncInputStreams 121
Summary 122
6. Java Thread Scheduling
An Overview of Thread Scheduling 124
When Scheduling Is Important 135
Scheduling with Thread Priorities 138
Popular Scheduling Implementations 142
Native Scheduling Support 153
Other Thread-Scheduling Methods 157
Summary 167
7. Java Thread Scheduling Examples
Thread Pools 170
Round-Robin Scheduling 176
Job Scheduling 191
Summary 197
8. Advanced Synchronization Topics
Synchronization Terms 198
Preventing Deadlock 200
Lock Starvation 208
Thread-Unsafe Classes 222
Summary 234
9. Parallelizing for Multiprocessor Machines
Parallelizing a Single-Threaded Program 236
Inner-Loop Threading 255
Loop Printing 259
Multiprocessor Scaling 263
Summary 273
10. Thread Groups
Thread Group Concepts 274
Creating Thread Groups 275
Thread Group Methods 278
Manipulating Thread Groups 283
Thread Groups, Threads, and Security 285
Summary 291
A. Miscellaneous Topics
B. Exceptions and Errors

Index


From the B&N Reads Blog

Customer Reviews