Pages

Showing posts with label Multithreading. Show all posts
Showing posts with label Multithreading. Show all posts

Friday, 8 July 2016

Parallelism vs Concurrency

Parallelism
Parallelism means that an application splits its tasks up into smaller subtasks which can be processed in parallel, for instance on multiple CPUs at the exact same time.



Example:If a person is listening to music while writing an assignment then work done is in parallel way.

Concurrency
A condition that exists when at least two threads are making progress. A more generalized form of parallelism that can include time-slicing as a form of virtual parallelism.

If the computer only has one CPU the application may not make progress on more than one task at exactly the same time, but more than one task is being processed at a time inside the application. It does not completely finish one task before it begins the next.




Example:If a person is watching TV while writing an assignment then work done is in concurrent way.

Wednesday, 8 June 2016

Calling run method directly of thread (created by implementing Runnable interface) in Java

It will works as ordinary java method because the thread class run() method implementation.

voidjava.lang.Thread.run()

If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns. Subclasses of Thread should override this method.

@Override
public void run() {
    if (target != null) {
        target.run();
    }
}

Here target is our runnable class which will set while calling Thread class constructor while creating thread.

Example:

class MyThread implements Runnable {
     @Override
     public void run() {
           System.out.println("This is my thread !!");
     }
}

public class ThreadTest {
     public static voidmain(String[] args) {
           MyThread  myThread = new MyThread();
          
           Thread thread = new Thread(myThread);
          
           thread.run();
     }
}

Sunday, 22 May 2016

Java ExecutorService Example

In server programming, suppose one client request can be processed using one thread than there will few challenges:

1. It subsequently limit how many client can access server concurrently.
2. In order to support large number of clients, you may decide to use one thread per request paradigm, in which each request is processed by separate Thread, but this require Thread to be created, when request arrived.  Since creation of Thread is time consuming process, it delays request processing.
3. It also limits number of clients based upon how many thread per JVM is allowed, which is obviously a limited number.
Thread pool solves this problem for you, It creates Thread and manage them. Instead of creating Thread and discarding them once task is done, thread-pool reuses threads in form of worker threadSince Thread are usually created and pooled when application starts, your server can immediately start request processing, which can further improve server’s response time.

In short, we need thread pools to better manage threads and decoupling task submission from execution. Thread pool and Executor framework is an excellent thread pool provided by library.

The executor framework separate out task submission from task execution giving us some flexibility in controlling concurrency policy, scheduling etc.

ExecutorService is an interface that extends Executor class and represents an asynchronous execution. It provides us mechanisms to manage the end and detect progress of the asynchronous tasks.

newFixedThreadPool():ExecutorService that creates a thread pool of fixed number of threads.

Methods to start ExecutorService:
execute(Runnable r): Depending on the implementation of the Executor class and may perform the Runnable in a new thread, in a pooled thread, or in the calling thread.

submit(Runnable r): submit() method extends execute(), by returning a Future that represents the submitting task.

Method th close down the ExecutorService:
shutdown():Submitted tasks are executed before the shutting down but new tasks can not be accepted.

shutdownNow():Stops the executing tasks, pause the waiting ones and returns the list of the awaiting ones.

awaitTermination():it can be used in order to wait until all threads are terminated.

package executor;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class WorkerThread implements Runnable {

      private String cmnd;
      CountDownLatch cdl;

      publicWorkerThread(String s,CountDownLatch cdl){
            this.cmnd=s;
            this.cdl = cdl;
      }

      @Override
      public void run() {
            System.out.println(Thread.currentThread().getName()+" start Worker = "+cmnd);
            processCommand();
            System.out.println(Thread.currentThread().getName()+" end Worker = "+cmnd);
            cdl.countDown();
      }

      private void processCommand() {
            try {
                  Thread.sleep(5000);
            } catch(InterruptedException e) {
                  e.printStackTrace();
            }
      }

      @Override
      public String toString(){
            return this.cmnd;
      }
}

public class ExecuterPool {
      public static void main(String[] args) throws InterruptedException {
            ExecutorService executor = Executors.newFixedThreadPool(5);
            CountDownLatch cdl = new CountDownLatch(5);
            for (int i = 0; i < 5; i++) {
                  Runnable worker = new WorkerThread("" + i, cdl);
                  executor.execute(worker);
            }
            executor.shutdown();
            cdl.await();
            System.out.println("Finished all threads");
      }
}

Limitations from traditional Thread overcome by Executor framework (built-in Thread Pool framework).

Poor Resource Management: It keeps on creating new resource for every request. No limit to creating resource. Using Executor framework we can reuse the existing resources and put limit on creating resources.

Not Robust: If we keep on creating new thread we will get StackOverflowException exception consequently our JVM will crash.

Overhead Creation of time: For each request we need to create new resource. To creating new resource is time consuming. i.e. Thread Creating > task.
Using Executor framework we can get built in Thread Pool.

Advantages of Thread Pool:

Use of Thread Pool reduces response time by avoiding thread creation during request or task processing.
Use of Thread Pool allows you to change your execution policy as you need. You can go from single thread to multiple threads by just replacing ExecutorService implementation.

Thread Pool in Java application increases stability of system by creating a configured number of threads decided based on system load and available resource.


Thread Pool frees application developer from thread management stuff and allows focusing on business logic.

Saturday, 14 May 2016

Sleeping barber problem

In computer science, the sleeping barber problem is a classic inter-process communication and synchronization problem between multiple operating system processes. The problem is analogous to that of keeping a barber working when there are customers, resting when there are none, and doing so in an orderly manner.

The Sleeping Barber Problem is often attributed to Edsger Dijkstra (1965), one of the pioneers in computer science.

Problem Statement


Sleeping Barber problem

Flow chart for Sleeping barber problem

The analogy is based upon a hypothetical barber shop with one barber. The barber has one barber chair and a waiting room with a number of chairs in it. When the barber finishes cutting a customer's hair, he dismisses the customer and then goes to the waiting room to see if there are other customers waiting. If there are, he brings one of them back to the chair and cuts his hair. If there are no other customers waiting, he returns to his chair and sleeps in it.

Each customer, when he arrives, looks to see what the barber is doing. If the barber is sleeping, then the customer wakes him up and sits in the chair. If the barber is cutting hair, then the customer goes to the waiting room. If there is a free chair in the waiting room, the customer sits in it and waits his turn. If there is no free chair, then the customer leaves.

Based on a naïve analysis, the above description should ensure that the shop functions correctly, with the barber cutting the hair of anyone who arrives until there are no more customers, and then sleeping until the next customer arrives. In practice, there are a number of problems that can occur that are illustrative of general scheduling problems.

Boundary Cases

à A customer may arrive and observe that the barber is cutting hair, so he goes to the waiting room. While he is on his way, the barber finishes the haircut he is doing and goes to check the waiting room. Since there is no one there (the customer not having arrived yet), he goes back to his chair and sleeps. The barber is now waiting for a customer and the customer is waiting for the barber.

à Two customers may arrive at the same time when there happens to be a single seat in the waiting room. They observe that the barber is cutting hair, go to the waiting room, and both attempt to occupy the single chair.

Implementation

semaphore.sem_wait() locks the semaphore.sem_post() unlocks it.
Semaphore Customers = 0;
Semaphore Barber = 0;
Mutex accessSeats = 1;
int NumberOfFreeSeats = N;

Barber {
      while(1) {
            /* waits for a customer (sleeps). */
            sem_wait(Customers);

            /* mutex to protect the number of available seats.*/
            sem_wait(accessSeats);

            /* a chair gets free.*/
            NumberOfFreeSeats++;
           
            /* bring customer for haircut.*/
            sem_post(Barber);
           
            /* release the mutex on the chair.*/
            sem_post(accessSeats);
            /* barber is cutting hair.*/
      }
}

Customer {
      while(1) {
            /* protects seats so only 1 thread tries to sit in a chair if that's the case.*/
            sem_wait(accessSeats);
            if(NumberOfFreeSeats > 0) {
                 
                  /* sitting down.*/
                  NumberOfFreeSeats--;
                 
                  /* notify the barber. */
                  sem_post(Customers);
                 
                  /* release the lock */
                  sem_post(accessSeats);
                 
                  /* wait in the waiting room if barber is busy. */
                  sem_wait(Barber);
                  // customer is having hair cut
            } else {
                  /* release the lock */
                  sem_post(accessSeats);
                  // customer leaves
            }
      }
}


A multiple sleeping barbers problem has the additional complexity of coordinating several barbers among the waiting customers.

References:

Thursday, 12 May 2016

Advantages and Disadvantages of Lock in Java

Advantages of ReentrantLock in Java

1) Ability to timeout while waiting for lock using Lock.tryLock(long timeout, TimeUnit timeUnit).

2) Ability to lock interruptibly.
The lockInterruptibly method allows you to try to acquire a lock while remaining responsive to interruption. lockInterruptibly() may block if the lock is already held by another thread and will wait until the lock is acquired. This is the same as with regular lock(). But if another thread interrupts the waiting thread lockInterruptibly() will throw InterruptedException.

3) Power to create fair lock i.e. longest waiting thread gets the lock first.

4) API to get list of waiting thread for lock.

5) Flexibility to try for lock without blocking.

Disadvantages of ReentrantLock in Java

Drawback of using ReentrantLock is wrapping method body inside try-finally block, which makes code unreadable and hides business logic because finally is required to call unlock method.

In case of lock, programmer is responsible for acquiring and releasing lock, it may lead to subtle bugs when programmer forget to release the lock in finally block.


Difference between Lock Interface and synchronized keyword

1) In synchronized block, thread might end up waiting indefinitely for the lock. But in case of lock, we can use Lock.tryLock(long timeout, TimeUnit timeUnit) to make sure thread waits for specific time only for lock.

2)Synchronization blocks or methods can cover only one method. A Lock can have its calls to lock() and unlock() in separate methods.

3)synchronized keyword doesn’t provide fairness whereas we can set fairness to true while creating ReentrantLock object so that longest waiting thread gets the lock first.

4) We can create different conditions for Lock and different thread can await() for different conditions.

5)Synchronization code is much cleaner and easy to maintain whereas with Lock we are forced to have try-finally block to make sure Lock is released even if some exception is thrown between lock()and unlock() method calls.