Thursday, September 26, 2013

THREADS


Threads
Executing several tasks simultaneously where each task is a separate independent part of the same program is called Thread.
Based Multitasking
àEach Independent part is called a Thread.
àThread Based Multitasking is best suitable at programmatic Level.
àWhether it is thread based/process based, the main objective of multitasking is reduce response time and improve performance of the system.
àWhen compared to other languages like c++, java provides inbuilt support for Multithreading through a Rich API(Thread class, Thread Group, Runnable Interface) etc. Hence developing Multithreading example is very easy in java.
àThen main important applicable area is Multithreading are:
1. To develop video games
2. To implement multimedia graphics
3. To develop animation movies etc.







  1. New state: After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive. 
  2. Runnable (Ready-to-run) state:  A thread start its life from Runnable state. A thread first 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. On this state a thread is waiting for a turn on the processor.  
  3. Running state: A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool.
  4. Dead stateA thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again.
  5. BlockedA thread can enter in this state because of waiting the resources that are hold by another thread.

Defining, Instantiating and starting a thread:
1.Extending Thread Class
2.Implementing Runnable Interface

Defining a thread by Extending Thread Class:
Class MyThread extends Thread{
Public void run()
{
//            Defining a Thread
//            Job  of the thread
}
}
Class ThreadDemo{
           psvm(Strring[] args){
               MyThread t         =             new MyThread();
àInstating a Thread
                                t.start();
àStarting a Thread
             }
}


Defining a thread by Implementing Runnable Interface:

Class MyRunnable implements Runnable{
Public void run()
{
//            Defining a Thread
//            Job  of the thread
}
}


Class RunnableDemo{
           
psvm(Strring[] args)  
              MyRunnable  r        =      new MyRunnable ();
               Thread          t         =      new Thread(r); -->Instating a Thread
                                t.start(); -->Starting a Thread
             }
}




yield() method

/**
  * A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore
  * this hint. Yield is a heuristic attempt to improve relative progression between threads that would otherwise over-utilize a CPU.
  * Its use should be combined with detailed profiling and benchmarking to ensure that it actually has the desired effect.
  */

public static native void yield();

yield() tells the JVM Thread Scheduler that it's OK to give other threads time slices. Usually the JVM uses this call to activate another thread of the same thread priority. In a good preemptive multithreading environment, yield() is a no-op. However, it is important in a cooperative multithreading environment, since without yield(), one thread can eat up all of the CPU.


  • Yield is a Static method and Native too.
  • Yield tells the currently executing thread to give a chance to the threads that have equal priority in the Thread Pool.
  • There is no guarantee that Yield will make the currently executing thread to runnable state immediately.
  • It can only make a thread from Running State to Runnable State, not in wait or blocked state.

Join() method

The join() method of a Thread instance can be used to “join” the start of a thread’s execution to the end of another thread’s execution so that a thread will not start running until another thread has ended. If join() is called on a Thread instance, the currently running thread will block until the Thread instance has finished executing.
//Waits for this thread to die.
public final void join() throws InterruptedException


Giving a timeout within join(), will make the join() effect to be nullified after the specific timeout. When the timeout is reached, the main thread and taskThread are equally probable candidates to execute. However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify.
Like sleep, join responds to an interrupt by exiting with an InterruptedException.
wait() ,notify() and notifyAll() method of object class must have to be called inside synchronized method or synchronized block in Java

Need/Advantage of ThreadPool?
Instead of creating new thread every time for executing tasks, we can create ThreadPool which reuses a fixed number of threads for executing tasks. 

As threads are reused, performance of our application improves drastically. 
Java provides multiple ways to implement multithreading, each with its use cases and advantages:
  • Extending Thread: Simple but inflexible as it does not allow extending other classes.
  • Implementing Runnable: More flexible, allowing the class to extend other classes.
  • Using ExecutorService: Manages a pool of threads and provides better control and management of tasks.
  • Using ForkJoinPool: Suitable for tasks that can be broken down recursively.
  • Using CompletableFuture: Simplifies writing non-blocking asynchronous code.


Future vs CompletableFuture

While Future is a simple and straightforward interface for representing the result of an asynchronous computation, CompletableFuture extends it and provides a more flexible and powerful way to compose and manage asynchronous tasks. Here are some key differences:

  1. Chaining and Composition:

    • Future: Does not support chaining or composing multiple asynchronous tasks.
    • CompletableFuture: Supports chaining (thenApply, thenAccept, thenRun, etc.) and composing (thenCombine, thenCompose, etc.) multiple asynchronous tasks.
  2. Completing Manually:

    • Future: Does not support manual completion of the future.
    • CompletableFuture: Allows manual completion using methods like complete, completeExceptionally, and obtrudeValue.
  3. Combining Multiple Futures:

    • Future: Requires additional logic to combine multiple futures.
    • CompletableFuture: Provides methods like allOf and anyOf to easily combine multiple futures.

  • CompletableFuture.supplyAsync starts an asynchronous task.
  • thenApply transforms the result "Hello, World!" into its length (13).
  • thenAccept consumes the length and prints it.
  • thenRun executes a Runnable that prints "Computation finished!" after the future completes.

  • No comments:

    Security Certificates

      1. Cryptography Basics Understand Key Concepts : Encryption, decryption, hashing, and digital signatures. Key terms: confidentiality, inte...