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

Thursday, July 19, 2018

Comparator interface and its example in java


In our previous post we have learn about what is comparable , In this article we will see basics about Comparator.


#What is Comparator ?
Comparator is a interface which is used to order the different user defined objects. When we have 2 object of different classes we want to order them we will use comparator.

Learn about What is Comparable?

#UserCase :
We have an array of person , we want to sort them on different basis , like on the basis of age of the person , or on the basis of name of the person. there are 2 questions comes in our mind , can we use comparable , - No ( as we can only compare on one of the 2 basis not both) , can we use comparator - Yes .




Approach 

  1. We will first create one person class .
  2. Now we will create 2 different Custom Comparator classes which will implements Comparator<person>
    1. One will be AgeComparator.
    2. Second will be NameComparator.
  3. Now we will create one Main class where we will create list of person. and then we will use Collections.sort and pass the list along with the comparator , we want to use for sorting.
Implementation

Person.java

class Person{
 
 int age;
 String name;
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 @Override
 public String toString() {
  return "Person [age=" + age + ", name=" + name + "]";
 }
 
 
 
}
AgeComparator.java

class AgeComparator implements Comparator<Person>{

 @Override
 public int compare(Person arg0, Person arg1) {
  // TODO Auto-generated method stub
  return arg0.getAge() - arg1.getAge();
 }
 
}
NameComparator.java

class NameComparator implements Comparator<Person>{

 @Override
 public int compare(Person o1, Person o2) {
  // TODO Auto-generated method stub
  return o1.getName().compareTo(o2.getName());
 }
 
}

Main Class

public class ComparatorDemo {
 public static void main(String[] args) {
  List<Person> list = new ArrayList<>();
  Person p1 = new Person();
  p1.setAge(35);
  p1.setName("vishal");
  
  Person p2 = new Person();
  p2.setAge(45);
  p2.setName("rohan");
  
  
  list.add(p2);
  list.add(p1);
  
  
//  Collections.sort(list,new AgeComparator());
  Collections.sort(list,new NameComparator());
  list.forEach(s-> System.out.println(s));
 }
 
}

Result 

Person [age=45, name=rohan]
Person [age=35, name=vishal]

Here we can see that the Objects are sorted on the basis of name , we can also do it by using age comparator as well.

If you have any issue , Please let us know , if you want any other topic to be covered in our next article please leave us a comment.

If you like this article please share it with your friends as well.

Thanks for reading
noeik

Saturday, July 14, 2018

Comparable and its example in java

comparable interface and its example

Most of us have heard about comparable and most of you also know what is comparable,
What is a comparable interface?
Comparable interface is used to sort the objects on the basis of any one variable, It is found in java.lang package and contain only one method compareTo(Object o).

In java When we have a scenario where we need to sort the array of objects on the basis of there member variable, or to eligible the objects to compare we use Comparable.

There are some good interview questions are there related to the comparable interface.

In this article, we will see one example of the implementation of the comparable interface and its explanation.



#Objective - We have a list of student and we need to sort the list on the bases of student ages in ascending order.

#Approach
  • We will implement the Comparable interface in the student class.
  • we will override the compareTo() method and write the logic for that 
  • As compareTo() method return 
    • 1 when own variable is greater than compared object variable.
    • 0 when both are equal
    • -1 when the own variable is less than compared object variable.
Now let see the implementation.
Below is the Student class

package com.programinjava.learning.comparable;


//implementing the comparable interface
public class Student implements Comparable<Student>{
 
 
 private int age;
 private String name;
 
 
 

 public int getAge() {
  return age;
 }




 public void setAge(int age) {
  this.age = age;
 }




 public String getName() {
  return name;
 }




 public void setName(String name) {
  this.name = name;
 }

 @Override
 public int compareTo(Student o) {
  return this.getAge() - o.getAge();
 }




 @Override
 public String toString() {
  return "Student [age=" + age + ", name=" + name + "]";
 }
 
 

}
Now we will see the Main Demo class

ComparableDemo.java
package com.programinjava.learning.comparable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ComparableDemo {
 
 public static void main(String[] args) {
  
  
  
//  creating list of student with different name and age
  List<Student> list = new ArrayList<>();
  Student s1 = new Student();
  s1.setAge(10);
  s1.setName("student 1");
  
//  second
  Student s2 = new Student();
  s2.setAge(20);
  s2.setName("student 2");
//  third
  
  Student s3 = new Student();
  s3.setAge(30);
  s3.setName("student 3");
  
//  fourth
  Student s4 = new Student();
  s4.setAge(40);
  s4.setName("student 4");
  
//  fifth
  Student s5 = new Student();
  s5.setAge(50);
  s5.setName("student 5");
  
  list.add(s2);
  list.add(s1);
  list.add(s4);
  list.add(s3);
  list.add(s5);
  
  System.out.println("Printing before sorting the list");
  list.forEach(s->System.out.println(s));
  
//  sorting the list 
  Collections.sort(list);
  System.out.println();
  
  System.out.println("Printing after sorting the list");
  list.forEach(s->System.out.println(s));
  
  
 }

}
Result Looks like below
Printing before sorting the list
Student [age=20, name=student 2]
Student [age=10, name=student 1]
Student [age=40, name=student 4]
Student [age=30, name=student 3]
Student [age=50, name=student 5]

Printing after sorting the list
Student [age=10, name=student 1]
Student [age=20, name=student 2]
Student [age=30, name=student 3]
Student [age=40, name=student 4]
Student [age=50, name=student 5]

I hope this will help you in understand how to implement comparable and when to implement it.

There are some other topics if you want to explore


Conditional Logic in java
Loops in java
Arrays in java
Wrapper classes in java
Methods in java
Object Oriented Practices
Inheritance in java

If you have any issue, please leave us a comment, if you like it, please share it with your friends

Thanks for reading 
noeik