Multithreading Parag Shah Adaptive Software Solutions http://www.adaptivelearningonline.net
Agenda Multithreading concepts Creating threads Controlling threads Thread states Summary
Multithreading concepts Multithreading concepts Creating threads Controlling threads Thread states Summary
Multithreading concepts Need for concurrency Multi processing Multi threading Multi threading makes user interfaces more responsive Multi threading makes better utilization of time when the program is blocking for IO
Creating Threads A thread represents code that will be run concurrently with other code in the same process Creating a thread Use the Thread class Use the Runnable interface Pros and Cons Extending thread is simpler Implementing Runnable allows subclassing other classes
Creating Threads – Extending Thread Extend java.lang.Thread Implement the run method See [SimpleThread.java]
Creating Threads – Implementing Runnable Extend java.lang.Thread Implement the run mthod See [SimpleRunnable.java] A Runnable cannot throw a checked exception
Thread Priorities Priorities are between 1 – 10 Best to use the constants defined in Thread MAX_PRIORITY MIN_PRIORITY NORM_PRIORITY Uses of thread priority
States Of A Thread A thread can be in any one of these 4 states New: The thread object has been created but it has not been initialized Runnable: The thread object is ready to run whenever the CPU gives it a time slot Blocked: The thread could be run, but is currently not in a runnable state Dead: The thread has terminated
Controlling Thread Behavior Yielding Sleeping Setting Priorities Joining
Controlling Thread Behavior Yielding A thread can be made to yield when it comes to a point when the CPU can be relinquished to another thread Yielding is done by calling the yield() method A call to yield() is a hint to the underlying operating system. It does not guarantee that the CPU will be immediately given to another thread See [SimpleYieldingThread.java]
Controlling Thread Behavior Sleeping A thread can be put to sleep for xxx ms Use the sleep(long x) call on the thread to put it to sleep for x ms The thread is guaranteed to sleep for x ms It may take more than that for the scheduler to give it control It may be interrupted by another thread See [SimpleThread.java]
Controlling Thread Behavior Priorities Every thread can have a priority Scheduler will choose thread with highest priority for running first Exact mechanism of choosing the thread is indeterminate JDK supports 10 priority levels For portability it is best to use one of the predefined (MAX_PRIORITY, NORM_PRIORITY, MIN_PRIORITY) priority levels
Controlling Thread Behavior Joining Another Thread Joining a thread is the process of suspending till the other thread completes execution Join can be called with or without a timeout Exercise SimpleJoiningThread.java
Some Deprecated Methods Deprecated methods suspend & resume stop & destroy These methods are deadlock prone An alternate mechanism for stopping threads
Sharing Resources In A Multithreaded Environment Multiple threads may try to access the same resource The point at which a thread will be suspended and another will resume is indeterminate A thread may not have finished totally processing a data structure before it is suspended. Another thread accessing the same data structure may find it in an improper state
Controlling Access To Shared Resources Put the shared resource in an object Make all methods in the object which access the shared resource, synchronized Every object has a lock (monitor) Before a thread enters a synchronized method it must obtain the lock The lock is released when the thread leaves the synchronized method Only one thread can have a lock to an object at a time Synchronize a critical section on an object
Atomic Operations Atomic operations are those operations that are guaranteed to be completed before a context switch Simple assignments and 'returning values' are some atomic operations An exception is when dealing with double and long values Be careful while omitting the synchronized keyword when multiple methods are accessing the shared resource
Thread Blocking A thread can be blocked due to one of the following reasons It is waiting for I/O It has called its sleep(long ms) It has called the wait method The thread has called join on another thread The thread has called a synchronized method/block on another object and the lock is unavailable
Using wait() and notify() with threads sleep(long ms) does not release the locks held by that thread Use wait() with notify() or notifyAll() instead See [WaitNotifyThread.java]
Deadlock What is deadlock The dining philosophers problem Conditions for a deadlock to occur At least one resource used by threads is not shareable At least one thread holds a resource and is waiting on another resource which is being held by another thread A resource cannot be taken away from a thread A circular wait happens
Threading In JDK 1.5 JDK 1.5 has increased support for threading Has a new concurrency packages java.util.concurrent java.util.concurrent.atomic java.util.concurrent.locks
Summary It is important to understand when to use threads Caution must be exercised while writing multi-threaded code Thorough testing is recommended It is important to understand which classes and methods should be made thread safe
Where to Get More Information Bruce Eckel's – Thinking In Java Taming Java Threads – Allen Holub

Multithreading In Java

  • 1.
    Multithreading Parag ShahAdaptive Software Solutions http://www.adaptivelearningonline.net
  • 2.
    Agenda Multithreading conceptsCreating threads Controlling threads Thread states Summary
  • 3.
    Multithreading concepts Multithreadingconcepts Creating threads Controlling threads Thread states Summary
  • 4.
    Multithreading concepts Needfor concurrency Multi processing Multi threading Multi threading makes user interfaces more responsive Multi threading makes better utilization of time when the program is blocking for IO
  • 5.
    Creating Threads Athread represents code that will be run concurrently with other code in the same process Creating a thread Use the Thread class Use the Runnable interface Pros and Cons Extending thread is simpler Implementing Runnable allows subclassing other classes
  • 6.
    Creating Threads –Extending Thread Extend java.lang.Thread Implement the run method See [SimpleThread.java]
  • 7.
    Creating Threads –Implementing Runnable Extend java.lang.Thread Implement the run mthod See [SimpleRunnable.java] A Runnable cannot throw a checked exception
  • 8.
    Thread Priorities Prioritiesare between 1 – 10 Best to use the constants defined in Thread MAX_PRIORITY MIN_PRIORITY NORM_PRIORITY Uses of thread priority
  • 9.
    States Of AThread A thread can be in any one of these 4 states New: The thread object has been created but it has not been initialized Runnable: The thread object is ready to run whenever the CPU gives it a time slot Blocked: The thread could be run, but is currently not in a runnable state Dead: The thread has terminated
  • 10.
    Controlling Thread BehaviorYielding Sleeping Setting Priorities Joining
  • 11.
    Controlling Thread BehaviorYielding A thread can be made to yield when it comes to a point when the CPU can be relinquished to another thread Yielding is done by calling the yield() method A call to yield() is a hint to the underlying operating system. It does not guarantee that the CPU will be immediately given to another thread See [SimpleYieldingThread.java]
  • 12.
    Controlling Thread BehaviorSleeping A thread can be put to sleep for xxx ms Use the sleep(long x) call on the thread to put it to sleep for x ms The thread is guaranteed to sleep for x ms It may take more than that for the scheduler to give it control It may be interrupted by another thread See [SimpleThread.java]
  • 13.
    Controlling Thread BehaviorPriorities Every thread can have a priority Scheduler will choose thread with highest priority for running first Exact mechanism of choosing the thread is indeterminate JDK supports 10 priority levels For portability it is best to use one of the predefined (MAX_PRIORITY, NORM_PRIORITY, MIN_PRIORITY) priority levels
  • 14.
    Controlling Thread BehaviorJoining Another Thread Joining a thread is the process of suspending till the other thread completes execution Join can be called with or without a timeout Exercise SimpleJoiningThread.java
  • 15.
    Some Deprecated MethodsDeprecated methods suspend & resume stop & destroy These methods are deadlock prone An alternate mechanism for stopping threads
  • 16.
    Sharing Resources InA Multithreaded Environment Multiple threads may try to access the same resource The point at which a thread will be suspended and another will resume is indeterminate A thread may not have finished totally processing a data structure before it is suspended. Another thread accessing the same data structure may find it in an improper state
  • 17.
    Controlling Access ToShared Resources Put the shared resource in an object Make all methods in the object which access the shared resource, synchronized Every object has a lock (monitor) Before a thread enters a synchronized method it must obtain the lock The lock is released when the thread leaves the synchronized method Only one thread can have a lock to an object at a time Synchronize a critical section on an object
  • 18.
    Atomic Operations Atomicoperations are those operations that are guaranteed to be completed before a context switch Simple assignments and 'returning values' are some atomic operations An exception is when dealing with double and long values Be careful while omitting the synchronized keyword when multiple methods are accessing the shared resource
  • 19.
    Thread Blocking Athread can be blocked due to one of the following reasons It is waiting for I/O It has called its sleep(long ms) It has called the wait method The thread has called join on another thread The thread has called a synchronized method/block on another object and the lock is unavailable
  • 20.
    Using wait() andnotify() with threads sleep(long ms) does not release the locks held by that thread Use wait() with notify() or notifyAll() instead See [WaitNotifyThread.java]
  • 21.
    Deadlock What isdeadlock The dining philosophers problem Conditions for a deadlock to occur At least one resource used by threads is not shareable At least one thread holds a resource and is waiting on another resource which is being held by another thread A resource cannot be taken away from a thread A circular wait happens
  • 22.
    Threading In JDK1.5 JDK 1.5 has increased support for threading Has a new concurrency packages java.util.concurrent java.util.concurrent.atomic java.util.concurrent.locks
  • 23.
    Summary It isimportant to understand when to use threads Caution must be exercised while writing multi-threaded code Thorough testing is recommended It is important to understand which classes and methods should be made thread safe
  • 24.
    Where to GetMore Information Bruce Eckel's – Thinking In Java Taming Java Threads – Allen Holub