Introduction to Java Threads

Hi Friends,

As per my Knowledge, Following is the Tutorial on Introduction  to threads, Implementation of threads in Java, thread pools and performance considerations while coding threads. 
Hope this blog helps you a lot in finding useful Info to Learn Threads in Java and It will be benefit you in day to day life. 
Please provide me any feedback by your comments or any valuable suggestions.

Lets start with contents

- Thread basics
- Thread Management
- Synchronization
- Thread Scheduling
- Thread pools
- Performance considerations
- Reference

Thread basics
 “a thread is a program's path of execution ”
Threads exist within a process and Process can have multiple concurrently executing threads
Threads share the process's resources, including memory and open files.
Every Java program has at least one thread – the main thread



Thread Life cycle :
Thread is always in one of following states.
Ready-to-run state - enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also
Running state - the scheduler select a thread from runnable pool
Dead state - considered dead when its run() method completes
Blocked state - can enter in this state because of waiting the resources that are hold by another thread


Thread Management
Creating threads :
i. Extending the Thread class (java.lang.Thread) 



ii. Implement the Runnable interface (java.lang.Runnable) 

Ending threads :
The thread comes to the end of its run() method
The thread throws an Exception or Error that is not caught
Another thread calls one of the deprecated stop() methods

Synchronization
Synchronization for Controlled access:

it ensures that only one thread Executes a protected  section of code at one time (mutual exclusion )
It ensures that data changed by one thread is visible to other threads (visibility of changes)
Synchronization uses the concepts of monitors, or locks, to coordinate access to critical section
When a thread enters a synchronized block of code, the thread blocks and waits until the lock is available.

Examples of using Thread Synchronization is in “The Producer/Consumer Model”.

Synchronization can be implemented in Java using :
(i) synchronized methods
    - Non-static synchronized  method acquire lock on that object.
    - Static synchronized methods acquire lock on the class.
    // synchronized method
    public void synchronized MyClearMethod() {
        CollectionObj.clear();
        CollectionObj.notify();
    }

(ii) synchronized blocks
    - These enable to execute synchronized code that acquires lock on any object (other than     this)
    - Object whose lock is to be acquired and statements to execute on obtaining the lock
    // synchronized block
    public void MyClearMethod() {
        synchronized(CollectionObj) { // object is not 'this'
         CollectionObj.clear(); // clears collection
               CollectionObj.notify();
    } }

Thread Scheduling
 JVM schedules using a preemptive , priority based scheduling algorithm
    - the Thread class contains three integer priority constants
      1. [ 1] MIN_PRIORITY
      2. [ 5] NORM_PRIORITY
      3. [10] MAX_PRIORITY
    - Manage threads priority using getPriority() and setPriority()
join() with threads
    use Thread.join() which the calling thread will block until the target thread completes
sleep()
    static method of the Thread class that causes the currently executing thread to delay for a specified period
    If a thread is interrupted by a call to Thread.interrupt(), the sleeping thread will throw an Interrupted Exception
yield()
    Provides a hint to the scheduler that the current thread need not run at the present time, so the scheduler may choose another thread to run .
Wait and Notification (monitor)
   wait(), notify(),  and notifyAll()  must be called from within a synchronized context.
   wait() - sleep until it is interrupted with Thread.interrupt(), the specified timeout elapses, or another thread wakes it up with notify() or notifyAll().
   notifyAll() – all threads waiting on that object will be awakened.
   notify() – this method tells only one of the waiting threads that something has occurred that might satisfy the condition. We cannot specify the thread to be notified.


Example :

  synchronized(bf) {
      while(bf.isFull()) {
          try {
         //LogLog.debug ("Waiting for free space in buffer, "+bf.length());
             bf.wait();
            } catch(InterruptedException e) {
            if (!interruptedWarningMessage) {
              interruptedWarningMessage = true;
              LogLog.warn ("AsyncAppender interrupted.", e);
            } else {
              LogLog.warn ("AsyncAppender interrupted again.");
            }
            }
        }
        //cat.debug ("About to put new event in buffer.");
        bf.put(event);
        if(bf.wasEmpty()) {
            //cat.debug ("Notifying dispatcher to process events.");
          bf.notify();
        }
   }

Thread pools
The thread pool is given some fixed number of threads to use
The thread pool will assign its tasks to each of these threads . As the threads finish with old tasks, new ones are assigned
No thread-pooling feature built into Java; thread pooling must be implemented by the programmer 




Implementation of Thread pool
  - Thread pool contains an array of WorkerThread objects
  - This class is generic implementation of thread pool which have following input 1) Size of the pool to be constructed 2) Name of the class which implements Runnable (which has a visible default constructor)
  - It constructs a thread pool with active threads that are waiting for activation. Once the threads have finished their task they will come back and wait for assigning a new task.
Benefits of Thread Pooling
  - It saves the machine work of creating a new thread.
  - Single thread can recycle again and again.
  - Response time can be quick.
Risks of using thread pools
  - There will be high rejection rate
  - Sometime there is problem of deadlock also

Performance considerations
Benefits from Multithreading :
   - Improve application responsiveness
   - Use multiprocessors more efficiently
   - Use fewer system resources
   - Perform asynchronous or background processing
Problems with Multithreading:
   There are two central issues in multi-threaded programming - data integrity and level of 

   concurrency (or "liveness")
  - Deadlock
     Deadlock describes a situation where two or more threads are blocked forever,  waiting for each  

    other    
    To avoid deadlock, you should ensure that when you acquire multiple locks, you  Always acquire the 

    locks in the same order in all threads.
  - Race conditions

Don't overdo it
   There is a limit on how many threads you can create without degrading performance
   Threads consume resources and over use of threads Can be hazardous to your program's 

   performance and its maintainability


Most classes are not synchronized
  - classes, like the Collection classes in java.util, do not use  synchronization internally.
  - This means that classes like Hash Map ,you must synchronize on the same lock each time.


When you don't need to synchronize
 - Reads and writes are atomic for all variables declared volatile
 - Immutable classes (like String, Integer etc.,) and final fields
 - When data is initialized by a static initializer

References
‘The Java Programming Language’ by James Gosling's
Java Concurrency in Practice  By Brian Goetz, Tim Peierls, Joshua Bloch
DougLea's Concurrent Programming in Java, Second Edition
http://java.sun.com/docs/books/tutorial/essential/concurrency/
 


About the Author :
I, Author is currently working as Senior Programmer at CISCO Systems , India.
I Pursued M.Tech degree in Computer Science from V.T.U, Bangalore and B.Tech in
Computer Science from Nagarjuna University.
My Hobbies are Coding , Watching TV, Listening to music.

Reach me at naresh.master3@gmail.com