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

Thursday, June 25, 2020

[Multi threading Interview Question ]Rate Limiter Implementation in java

There was one interesting problem I have encounter while preparing for a multithreading coding interview.


Question: We have an application for which we need to implement RateLimiter, 
Rate Limiter is an interface which will play a role to limit the number of Request client send to Server in a given time.

In the Current Question, it was asked to implement a rate limit who will do 2 things.

1) It will only allow one client to send 100 requests in 1 hrs. ( one client will be identified by the client Id).
2) It will allow a total of 10000 requests to be passed to the server in 1 hrs.

Rate Limiter Interface 
interface RateLimiter{

boolean accept(String clientId);
}

Java Implementation of Rate Limiter 

When we need to Implement such things where there is any restriction of accessing the resource for limited count We always start thinking using Semaphores  
Why Semaphores? 
Because it maintains the multi-access locking on its own with defined number of threads to access the critical section.

MyRateLimiter.java

class MyRateLimiter  {
 
 
    private Semaphore semaphore;
    private int maxPermits;
    private TimeUnit timePeriod;
    private ScheduledExecutorService scheduler;
    
    
 
    public static MyRateLimiter create(int permits, TimeUnit timePeriod) {
    MyRateLimiter limiter = new MyRateLimiter(permits, timePeriod);
        limiter.schedulePermit();
        return limiter;
    }
 
    private MyRateLimiter(int permits, TimeUnit timePeriod) {
        this.semaphore = new Semaphore(permits);
        this.maxPermits = permits;
        this.timePeriod = timePeriod;
    }
 
    public boolean tryAcquire() {
        return semaphore.tryAcquire();
    }
 
    public void stop() {
        scheduler.shutdownNow();
    }
 
    public void schedulePermit() {
        scheduler = Executors.newScheduledThreadPool(1);
        scheduler.scheduleAtFixedRate(() -> {
            semaphore.release(maxPermits - semaphore.availablePermits());
        }, 0, 1, timePeriod);
 
    }

 }

 RateLimiterImpl.java

	class RateLimiterImpl implements RateLimiter{

private static long MINUTE_TIME_LIMIT=1000*60L; // update as per question
private static long REQUEST_ALLOWED_PER_MINUTE=10000; // Update as per question
Queue<Long> q = new LinkedList<>();
private static int minuteLimit=100;

private Map<String, Optional<MyRateLimiter>> limiters = new ConcurrentHashMap<>();
     
@Override
public boolean accept(String clientId) {
if(!hit(System.currentTimeMillis())) {
return false;
}
Optional<MyRateLimiter> rateLimiter = getRateLimiter(clientId);
if(rateLimiter.isPresent()) {
boolean canAcquire= rateLimiter.get().tryAcquire();
if(canAcquire)
return q.add(System.currentTimeMillis());
}
return false;
}
private boolean hit(long timestamp) {
while(!q.isEmpty() && timestamp-q.peek() >= MINUTE_TIME_LIMIT) q.poll();
if(q.size() < REQUEST_ALLOWED_PER_MINUTE)
{
q.offer(timestamp); 
return true;
}
return false;
}
private Optional<MyRateLimiter> getRateLimiter(String clientId) {
        return limiters.computeIfAbsent(clientId, id -> {
            return Optional.of(createRateLimiter(id));
            
        });
    }
private MyRateLimiter createRateLimiter(String clientId) {
        return MyRateLimiter.create(minuteLimit, TimeUnit.MINUTES);
    }

}

Main Class Calling

public class RateLimiterDemo {


public static void main(String[] args) {

RateLimiter limiter = new RateLimiterImpl();
        System.out.println("test1 " + limiter.accept("test1"));
        System.out.println("test1 " +limiter.accept("test1"));
        System.out.println("test1 " +limiter.accept("test1"));
        System.out.println("test1 " +limiter.accept("test1"));
        System.out.println("test2 " +limiter.accept("test2"));
        System.out.println("test2 " +limiter.accept("test2"));
        System.out.println("test2 " +limiter.accept("test2"));
        System.out.println("test2 " +limiter.accept("test2"));
        System.out.println("test1 " +limiter.accept("test1"));


}

}

You can also check the Code from HERE 

Hope this will help you in understanding the Code

Wednesday, November 28, 2018

Thread Pooling In Java Using Executors Class

Most of the Important and most of the developer found one topic in java they perform a task and then they get destroyed. Purpose of multithreading is to perform multiple tasks simultaneously for effective utilization of our resources (time and CPU).


Imagine that there are 10 tasks to perform, so using traditional multithreading mechanism we will need 10 threads. Do you see a drawback in this approach? I see it; creation of a new thread per task will cause resource overhead.

Friday, July 20, 2018

producer consumer problem implementation using wait notify methods.

producer-consumer problem using wait notify

Most of you have heard about the Producer-Consumer problem where one is producing something and another is consuming it.


So basically what actually the producer-consumer problem says 

Producer-Consumer Problem says that if we have a shared resource among 2 threads, and producer's job is to generate the data and put it in the buffer and consumer's job is to take the data from the buffer but then where is the problem? So problem is there should not be a scenario where the producer has produced the data more than the buffer size, which results in overflow problem also consumer should not consume all the data in the buffer and again try, which result in underflow problem. 
So basically its a multi-thread synchronization problem.

Read about: Concurrency CountDownLatch in java

Now, what is the solution?
We can use wait-notify mechanism to solve this problem of synchronization.



Approach 
  1. We will have 2 thread one is to produce random data and second will get the random data from the shared LinkedList (or and queue).
  2. we will write on a class called processor where there will be 2 methods one is produce() and second will be consume () 
  3. In produce() method we will write random generator and also be checking whether the size of linked list is less than 10 or not if greater we will call wait method over the object called lock which we are using for the locking mechanism.
  4. when produce() put the data in linkedlist it will call lock.notify() which will notify the second thread that there are some data stored in the linked list.
  5. now in consume() we will have a check for the linked list size should not be 0 if so we will call lock.wait() else we will take the data from the list and notify the producer().
Now let see the implementation of the above approach.

learn more about wait notify ()

#Implemenation

Processor.java (this class will have the produce() and consume() method in it )

class Processor {
 
 LinkedList<Integer> list = new LinkedList<>();
 Object lock = new Object();
 int value =0;
 
 public void produce() throws InterruptedException{
  
  while(true)
  {
   synchronized (lock) {
    
    while(list.size() == 10)
     lock.wait();
    
    list.add(value++);
    lock.notify();
    
   }
  }
  
 }
 
 public void consume() throws InterruptedException {
  
  Random random = new Random();
  while(true){
  synchronized (lock) {
  
   while(list.size() == 0)
    lock.wait();
   int i =list.removeFirst();
   lock.notify();
   System.out.println("Got the value "+i + "now the list size is "+list.size());
   
   
   
  }
  Thread.sleep(random.nextInt(1000));
  
  }
  
  
 }
}

Now we will see the 2 thread class and how we are calling them.

ProducerConsumerWithWaitNotify.Java

public class ProducerConsumerWithWaitNotify {
 
 public static void main(String[] args) {
  Processor pro = new Processor();
  Thread t1 = new Thread(new Runnable() {
   
   @Override
   public void run() {

    try {
     pro.produce();
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  });
  Thread t2 = new Thread(new Runnable() {
   
   @Override
   public void run() {

    try {
     pro.consume();
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  });
  
  
  t1.start();
  t2.start();
 }
 

}

After executing the code what will be the result, It will be like below

Got the value 0now the list size is 9
Got the value 1now the list size is 9
Got the value 2now the list size is 9
Got the value 3now the list size is 9
Got the value 4now the list size is 9
Got the value 5now the list size is 9
Got the value 6now the list size is 9
Got the value 7now the list size is 9
Got the value 8now the list size is 9
Got the value 9now the list size is 9
Got the value 10now the list size is 9
Got the value 11now the list size is 9
Got the value 12now the list size is 9
Got the value 13now the list size is 9
Got the value 14now the list size is 9

I hope this will help you in understanding the producer-consumer problem implementation using wait notify method in java

If you have any issue or concern, please leave us a comment, will be happy to help

Thanks for reading
noeik

Wednesday, June 13, 2018

Tuesday, February 13, 2018

Java thread wait, notify and notifyAll Methods Examples

Inter communication between thread is one of the most important topic now a days asked in interview questions.i.e wait() , notify() , notifyAll()

If you dont know the basics of Multithreading see my previous posts
Multithreading in java 
Basics of Volatile Keywords


What is Wait , Notify and NotifyAll Method do ?




Wait()
This method is the part of Object Class which is used to release the lock over the shared resource. Wait has 2 variant , one is where the thread will wait for the resource for infinite time for notify or notifyAll to be call. Other is it wait for specific time which user assigned before wake up.

Notify()
Notify method is also the part of Object class , It basic responsibility is to notify any one the thread who are waiting for the resource to get lock based on the priority or system implementation
OR
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.

NotifyAll()
Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods.

These methods can be used for Producer – Consumer Problem on low level synchronization.

Interview Question : print continuous number using 2 thread 

Now we will see how to use the Wait , Notify and NotifyAll In java




Explanation :
  • We have 2 class one is Processor2 and Second is WaitNotifyDemo (main class)
  • In Processor2 class we have 2 methods one is producer() and other is consumer() , In Producer we have first sysout command and then wait() method which will release the lock at wait() line , whereas in consumer() method we are sleeping the thread for 1 sec so that producer will take the lock .
  • Now in consumer method we have created a scanner object where we are looking for the keystroke after the key stoke we are notify() to other threads to get the lock.
  • After this point the thread one which is waiting for the lock in producer() method will get the lock and then print the last sysout.

NOTE 
This program is just to show you how wait and notify works whereas we always use wait in while loop.
We will see the industry level code for wait notify in next post of Producer ConsumerProblem.

I hope this will help you to understand the wait and notify working. If you have any issue please leave us a comment we will be happy to help.

Thanks for reading
Noeik



Printing Numbers in Sequence from alternating Threads in java

This is one of the most asked multi threading interview question we you need to write the program in which there will be 2 thread one will print even number and second will print odd number but we need to write the program in which the output will be the sequential.



Problem Statement
Write a multi threaded program to print continues number from 1 to 100 or 1 to 10(assume we will use only 2 threads).


If You don’t know the basics of Multithreading you can see my previous posts


Solution 

(Logical)

  • To Solve the problem we need to think in a way that there will be 2 threads , one will print even number and second will print odd number.
  • As The thread sequence is not defined we need to think about the sequencing of the thread , as Thread1 thread2 thread1 thread2 thread1 
    • Above will be the sequence in which we need to print the thread.
  • Now to achieve this sequence we need to use Wait & Notify Mechanism. If you don’t know about the Wait and Notify in java see my previou post – Wait and Notify in Threading
  • So we will Create one Class in which we will be having one Boolean value which maintain the current sequence is either odd or even.
  • This class called as counter will be used for lock over and the condition will be checked as if count.isEven = false thread2 (which is odd print thread) will take the lock
  • Count.isEven =true thread1 (which is even print thread) will take the lock.
  • After print the value the current thread will notify() other thread who is waiting for lock but before release the thread will change the count.isEven value to be negation of current.
In this way we can achieve the solution.
Programmatic Solution.


Explanation:
  • Here we have created 2 classes one is ContiniousPrintDemo second is Counter.
  • The ContiniousPrintDemo (will say Main class in future) is the Main Class where we have created 2 threads one will print even number and second will print odd number.
  • Counter class is used for Locking and checking the current value of the Count.
    • If the current value of count is even thread 1 will take lock , if count value will be odd thread 2 will take the lock.
This way we will be able to solve this problem 

If you have any problem or issue fell free to leave us a comment , will be happy to help you 

Thanks for reading
Noeik

Monday, February 12, 2018

Java Volatile Keyword and its use

This is the Second Tutorial of Multithreading Tutorials If you want to learn the basics of Multithreading you can read the previous post


So In Multithreading we use the Volatile keyword ,
What is Volatile Keyword and where we use it?
Volatile Keyword, the volatile modifier guarantees that any thread that reads a field will see the most recently written value.

We use volatile keyword when we don’t want the program to cache the variable in cpu rather thread will always read the value from the main memory.

Now let see the Program of Volatile keyword used in java.





Explanation :

In the above problem:
  • We have created a new thread which is checking the Boolean variable running , if variable value is true we are printing the Running on screen if it is false we are not printing.
  • If we have 2 thread and the variable is not volatile and one thread will check the variable value and see that the value is true and after one thread complete the task and change the value to false whereas the second thread is creating the variable value he is seeing it as true as the value is cached in the cpu and thread is only creating the cached value(This is happens sometime , not always) and it is seeing it as true but the current updated value is false . here we use the volatile keyword.
  • As using volatile keyword both the thread will always check the variable value from the main memory

NOTE: This problem only occurred  sometimes not always , but we need to cover all the scenario while coding.


When we are not using Volatile Keyword .





here the value will be cached in CPU Cache of Thread where the differences comes





When we use Volatile Keyword.

In this case the thread will directly read the value from the main memory only .


Is Volatile is Enough ??

As If there are 2 threads , both are reading and writing on shared resources then using the volatile keywords for that is not enough as we need to use synchronized in that case to guarantee that reading and writing both will be atomic. Or no 2 thread will have the access to write something on shared resource.
The volatile keyword is guaranteed to work on 32 bit and 64 variables.
We have a alternative of synchronization , we can use AtomicInteger  or AtomicBoolean which is a thread safe .

I hope this tutorial will help you in understand the volatile keyword and its use. In next tutorial we will post about the synchronization in java.

Thanks for Reading
Noeik


[Basics] Multithreading in java

Multithreading is a concept in java where we basically create more than one thread in program so that we can achieve the improved performance of the program.

How to Use Volatile keyword In Java


What is Process ?
Process is an instance of computer program that is being executing.
What is thread ?
Thread is the single unit of work or we can say a lightest process of computer program .

Thread is the simplest piece of process.

Multithreading in java 
            In Java by default the main thread is always run , if we cant to achieve the concurrency in programming we use the concept of multithreading.
Example – If we have a queue and we want to add the values in Queue and remove the value in a way that there should never be a List full situation occur of underflow situation occurred.To solve this problem we can use multithreading in java , where one thread is responsible for produce the number and push it in list and other thread is removing the number in list.

Thread Lifecycle-


Ways to create Thread in java
There are 2 ways to create threads in java
  • ·         By Extending Thread Class
  •        By Implementing Runnable Interface.

Program to create the Thread By Extending Thread Class



Explanation :

In Above Program
  • There are 2 classes one is main class and other is thread class.
  • MyThread class is a thread class where we are extending the Thread Class and over rite the  run() method of the class 
    • run() is the method we we need to write the logic we want to run while the thread will run. This is the most important method and all the code logic for thread need to write here only.
    • When we call the start() method it implicitly call the run() of the Thread class
  • In Run Method I have written the for we I am printing the current value along with the thread name.
  • The Main Class ThreadDemo , I have created 2 object of MyThread Class and We are calling start() method(which will start the thread).

NOTE: If I will directly call the run() method of the class , It will start my Main Thread only not the MyThread Class Thread.

By Implementing Runnable Interface.
In this way , we need to implement the runnable interface in our class and override the run() interface
The Only difference here is that we need to pass the runnable interface in construction while creating thread .
Thread t = new Thread(new MyRunnable());

Program of Runnable Interface 



Explanation:
In Above Program:
We are doing everything same as for thread class Only Thing we have changed is We need to Pass the Runnable Class in my Thread Class.

    Thread t = new Thread(new MyThread1());

Above is the Only Change. 

In Next Tutorial we will see how to Use Syncronization in Thread and when we need to use extend way and when runnable we will see in next tutorials.

In you have any Issue leave us a message . Will be happy to help

Thanks for reading

Noeik