You are previewing Java Thread Programming.
O'Reilly logo
Java Thread Programming

Book Description

Java Thread Programming shows you how to take full advantage of Java's thread facilities: when to use threads to increase your program's efficiency, how to use them effectively, and how to avoid common mistakes. There is thorough coverage of the Thread API, ThreadGroup classes, the Runnable interface, and the synchronized operator. Extensive, complete, code examples show programmers the details of creating and managing threads in real-world applications.

Table of Contents

  1. Copyright
    1. Dedication
  2. About the Author
  3. Acknowledgments
    1. Tell Us What You Think!
  4. Introduction
    1. Structure of This Book
    2. Chapter 1—"Introduction to Threads"
    3. Chapter 2—"A Simple Two-Thread Example"
    4. Chapter 3—"Creating and Starting a Thread"
    5. Chapter 4—"Implementing Runnable Versus Extending Thread"
    6. Chapter 5—"Gracefully Stopping Threads"
    7. Chapter 6—"Thread Prioritization"
    8. Chapter 7—"Concurrent Access to Objects and Variables"
    9. Chapter 8—"Inter-thread Communication"
    10. Chapter 9—"Threads and Swing"
    11. Chapter 10—"Thread Groups"
    12. Chapter 11—"Self-Running Objects"
    13. Chapter 12—"Exception Callback"
    14. Chapter 13—"Thread Pooling"
    15. Chapter 14—"Waiting For the Full Timeout"
    16. Chapter 15—"Breaking Out of a Blocked I/O State"
    17. Chapter 16—"The SureStop Utility"
    18. Chapter 17—"The BooleanLock Utility"
    19. Chapter 18—"First-In-First-Out (FIFO) Queue"
    20. Appendixes: The Thread API and The ThreadGroup API
    21. Conventions Used in This Book
  5. I. Threads
    1. 1. Introduction to Threads
      1. What Is a Thread?
      2. Why Use Multiple Threads?
        1. Better Interaction with the User
        2. Simulation of Simultaneous Activities
        3. Exploitation of Multiple Processors
        4. Do Other Things While Waiting for Slow I/O Operations
        5. Simplify Object Modeling
      3. When Multiple Threads Might Not Be Good
      4. Java's Built-in Thread Support
      5. Easy to Start, Tough to Master
    2. 2. A Simple Two-Thread Example
      1. Extending the java.lang.Thread Class
      2. Overriding the run() Method
      3. Spawning a New Thread
      4. Putting It All Together
      5. Summary
    3. 3. Creating and Starting a Thread
      1. Using Thread.currentThread()
      2. Naming a Thread: getName() and setName()
        1. Using getName()
        2. Using setName()
      3. Thread Constructors
      4. Enlivening a Thread: start() and isAlive()
      5. Using Thread.sleep()
      6. Summary
    4. 4. Implementing Runnable Versus Extending Thread
      1. Visual Timer Graphical Component
      2. Extending Thread and JComponent?
      3. Interface java.lang.Runnable
      4. Passing a Runnable Object to a Thread's Constructor
      5. Modifying SecondCounter to Use Runnable
      6. Checking the Accuracy of SecondCounter
      7. Improving the Accuracy of SecondCounter
      8. Summary
    5. 5. Gracefully Stopping Threads
      1. Interrupting a Thread: interrupt()
        1. Interrupting a Sleeping Thread
        2. Pending Interrupts
        3. Using isInterrupted()
        4. Using Thread.interrupted()
        5. Using InterruptedException
      2. Suspending and Resuming Thread Execution
        1. Using the Deprecated Methods suspend() and resume()
        2. Suspending at a Bad Time
        3. Suspending and Resuming Without Deprecated Methods
      3. Stopping a Thread
        1. Using the Deprecated Method stop()
        2. An Alternative to stop()
      4. The Best Replacement for stop(), suspend(), and resume()
      5. Daemon Threads
      6. Summary
    6. 6. Thread Prioritization
      1. System Thread Priorities
      2. Thread Priority Constants
        1. Thread.MAX_PRIORITY
        2. Thread.MIN_PRIORITY
        3. Thread.NORM_PRIORITY
      3. Determining the Current Priority: getPriority()
      4. Changing the Priority of a Thread: setPriority()
        1. When setPriority() Might Not Work
      5. Thread States
      6. Priorities and Scheduling
      7. Voluntarily Relinquishing the Processor: Thread.yield()
      8. Thread-Scheduling Scenarios
        1. Scenario I: One High-Priority Thread Hogs Processor
        2. Scenario II: All High-Priority Threads Hog Processor
        3. Scenario III: All Threads Get Some Time on the Processor
      9. Summary
    7. 7. Concurrent Access to Objects and Variables
      1. volatile Member Variable Modifier
      2. synchronized Method Modifier
        1. Two Threads Simultaneously in the Same Method of One Object
        2. One Thread at a Time
        3. Two Threads, Two Objects
        4. Avoiding Accidental Corruption of an Object
        5. Deferring Access to an Object While It Is Inconsistent
      3. synchronized Statement Block
        1. Reducing the Time That the Lock Is Held
        2. Locking an Object Other Than this
        3. Safely Copying the Contents of a Vector into an Array
      4. static synchronized Methods
      5. Using the Class-Level Lock in a synchronized Statement
      6. Synchronization and the Collections API
        1. Wrapping Collections to Make Them synchronized
        2. Safely Copying the Contents of a List into an Array
        3. Safely Iterating Through the Elements of a Collection
      7. Deadlocks
        1. Deadlock Avoidance
      8. Speeding Concurrent Access
      9. Summary
    8. 8. Inter-thread Communication
      1. The Need for Inter-thread Signaling
      2. The Wait/Notify Mechanism
        1. Minimal Wait/Notify
        2. Typical Wait/Notify
        3. Wait/Notify with synchronized Methods
      3. Object API Used for Wait/Notify
        1. notify()
        2. notifyAll()
        3. wait()
        4. wait(long)
        5. wait(long, int)
      4. When to Use notifyAll() Instead of notify()
      5. Missed Notification
        1. MissedNotify
        2. MissedNotifyFix
      6. Early Notification
        1. EarlyNotify
        2. EarlyNotifyFix
      7. CubbyHole Example
      8. Using join() to Wait for a Thread to Die
        1. join()
        2. join(long)
        3. join(long, int)
        4. JoinDemo
      9. Streaming Data Between Threads Using Pipes
        1. PipedBytes
        2. PipedCharacters
      10. Using ThreadLocal and InheritableThreadLocal
        1. ThreadLocal API
        2. ThreadID
        3. InheritableThreadLocal API
        4. InheritableThreadID
      11. Summary
    9. 9. Threads and Swing
      1. Why Isn't the Swing Toolkit Multithread-Safe?
      2. Using SwingUtilities.invokeAndWait()
      3. Using SwingUtilities.invokeLater()
      4. Using SwingUtilities.isEventDispatchThread()
      5. When invokeAndWait() and invokeLater() Are Not Needed
      6. The Need for Worker Threads in a GUI Setting
      7. Using a Worker Thread to Relieve the Event Thread
      8. Scrolling Text in a Custom Component
      9. Animating a Set of Images
      10. Displaying Elapsed Time on a JLabel
      11. Floating Components Around Inside a Container
      12. Summary
    10. 10. Thread Groups
      1. What Are Thread Groups?
      2. Using getParent()
      3. Finding the Subgroups of a Thread Group
      4. Using the getThreadGroup() Method of Thread
      5. Finding All the Threads in a Thread Group
      6. Understanding Thread Group Security
      7. Using setMaxPriority() and getMaxPriority()
      8. Using interrupt()
      9. Deprecated Methods: stop(), suspend(), and resume()
      10. Class ThreadViewer
      11. Summary
  6. II. Techniques
    1. 11. Self-Running Objects
      1. Simple Self-Running Class
      2. Using an Inner Class to Hide run()
      3. Additional Functionality to Consider
        1. Example: Animated Images on a JComponent
      4. Summary
    2. 12. Exception Callback
      1. ExceptionListener Interface
      2. Additional Methods to Support ExceptionListener
      3. Summary
    3. 13. Thread Pooling
      1. Benefits of Thread Pooling
      2. Considerations and Costs of Thread Pooling
      3. A Generic Thread Pool: ThreadPool
      4. A Specialized Worker Thread Pool: HttpServer
        1. Class HttpServer
        2. Class HttpWorker
        3. Sample Files to Be Served
        4. Running HttpServer with 3 Workers
        5. Running HttpServer with 10 Workers
      5. Summary
    4. 14. Waiting for the Full Timeout
      1. Accidentally Returning Early
      2. Determining If wait() Should Be Invoked Again
      3. A General-Purpose Wait-Until Pattern
      4. Summary
    5. 15. Breaking Out of a Blocked I/O State
      1. The read() Method Ignores Interrupts and Stop Requests
      2. Closing a Stream to Break Out of the Blocked State
        1. Class CalcServer and Breaking Out of a Blocked accept()
        2. Class CalcWorker and Breaking Out of a Blocked read()
        3. Class CalcClient
        4. Output When Run
      3. Throwing InterruptedIOException When Interrupted
        1. Class ThreadedInputStream
        2. Class BufferedThreadedInputStream
      4. Using BufferedThreadedInputStream for Interruptible I/O
      5. Summary
    6. 16. The SureStop Utility
      1. Guidelines for Using SureStop
      2. The SureStop Class
      3. Peering Inside Using SureStopVerbose
      4. Watching It Work with SureStopDemo
      5. Summary
    7. 17. The BooleanLock Utility
      1. Background
      2. BooleanLock Class
      3. Inter-Thread Signaling Using BooleanLock
      4. Avoiding Blocking on synchronized
        1. SyncBlock
        2. InterruptibleSyncBlock
      5. Noticing Brief Changes in Value Using TransitionDetector
      6. Summary
    8. 18. First-In-First-Out (FIFO) Queue
      1. How a FIFO Queue Works
      2. Implementing a FIFO with an Array
      3. Simple Implementation in Java: SimpleObjectFIFO
      4. An Expanded FIFO Queue for Object References: ObjectFIFO
      5. A FIFO Queue for Bytes: ByteFIFO
      6. Summary
  7. III. Appendixes
    1. A. The Thread API
      1. Member Variables
        1. Thread.MAX_PRIORITY
        2. Thread.MIN_PRIORITY
        3. Thread.NORM_PRIORITY
      2. Constructors
        1. Thread(ThreadGroup, Runnable, String)
        2. Thread(ThreadGroup, Runnable)
        3. Thread(ThreadGroup, String)
        4. Thread(Runnable, String)
        5. Thread(Runnable)
        6. Thread(String)
        7. Thread()
      3. static methods
        1. Thread.activeCount()
        2. Thread.currentThread()
        3. Thread.dumpStack()
        4. Thread.enumerate()
        5. Thread.interrupted()
        6. Thread.sleep(long)
        7. Thread.sleep(long, int)
        8. Thread.yield()
      4. Instance Methods
        1. checkAccess()
        2. destroy()
        3. getContextClassLoader()
        4. getName()
        5. getPriority()
        6. getThreadGroup()
        7. interrupt()
        8. isAlive()
        9. isDaemon()
        10. isInterrupted()
        11. join()
        12. join(long)
        13. join(long, int)
        14. run()
        15. setContextClassLoader(ClassLoader)
        16. setDaemon(boolean)
        17. setName(String)
        18. setPriority(int)
        19. start()
        20. toString()
      5. Deprecated Methods
        1. countStackFrames()
        2. resume()
        3. stop()
        4. stop(Throwable)
        5. suspend()
    2. B. The ThreadGroup API
      1. Constructors
        1. ThreadGroup(ThreadGroup, String)
        2. ThreadGroup(String)
      2. Instance Methods
        1. activeCount()
        2. activeGroupCount()
        3. checkAccess()
        4. destroy()
        5. enumerate(Thread[], boolean)
        6. enumerate(Thread[])
        7. enumerate(ThreadGroup[], boolean)
        8. enumerate(ThreadGroup[])
        9. getMaxPriority()
        10. getName()
        11. getParent()
        12. interrupt()
        13. isDaemon()
        14. isDestroyed()
        15. list()
        16. parentOf(ThreadGroup)
        17. setDaemon(boolean)
        18. setMaxPriority(int)
        19. toString()
        20. uncaughtException(Thread, Throwable)
      3. Deprecated Methods
        1. allowThreadSuspension(boolean)
        2. resume()
        3. stop()
        4. suspend()