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

Wednesday, June 13, 2018

Tuesday, May 29, 2018

Tuesday, May 22, 2018

Why Python & its popular libraries

This is second article in the series of python programming language by Zachary Farley , you can check the first article from here.




History of python?
In 1999 Van Rossum submitted a funding proposal to DARPA titled “Computer Programming for Everybody” where he defined the clear goals for Python: 
1) An easy intuitive language
2) Code understandable as plain English
3) Suitability for everyday tasks, allowing short development times

Monday, May 21, 2018

Implementing Redis with Spring boot


Redis is one of the most used inmemory cache server used in most of the distributed system for saving the key value data structures in memory for defined time interval along with some other features like pub sub and more.


So In this article you will learn how to use redis server and store the data in it while working on spring boot.

Thursday, May 17, 2018

File Uploading in Spring MVC using thymeleaf and spring boot


File uploading is one of the very basic requirement now a day where user required to upload a file on server.
There are so many ways to upload a file but in this tutorial we will talk about the file upload in spring mvc using thymeleaf.


So lets start.

Pseudo code: (Only CSV and Zip are allowed to upload)
In this tutorial we will first create on web page 
this page will have a form whose action will call a spring controller
under this spring controller we will have the file upload logic.
we also define the server directory where we want to upload the file.
After file successfully uploaded , we will show the message on webpage.

Implementation code: ( You can download the source code from Github )

First we will see the project Structure 


Lets first see the pom.xml to see all the dependency

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>

 <groupId>com.programinjava.learn</groupId>
 <artifactId>FileUploadExample</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>FileUploadExample</name>
 <description>Demo project for Spring Boot</description>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.0.2.RELEASE</version>
  <relativePath/> <!-- lookup parent from repository -->
 </parent>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  <java.version>1.8</java.version>
 </properties>

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
  <dependency>
   <groupId>org.webjars</groupId>
   <artifactId>jquery</artifactId>
   <version>3.3.1</version>
  </dependency>
  <dependency>
   <groupId>org.webjars</groupId>
   <artifactId>bootstrap</artifactId>
   <version>3.3.7</version>
  </dependency>
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>


</project>


Here we have used below dependencies

  1. Thymeleaf
  2. Bootstrap
  3. Spring web
After this we will see the Controller class

package com.programinjava.learn.controller;

import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.programinjava.learn.service.StorageService;

@Controller
public class UploadController {
 
 @Autowired
 StorageService storageService;
 
// CHANGE IT ACCORDING TO YOUR LOCATION
 private final String UPLOAD_FILE_LOCATION="C:\\programinjava_workspace";
 
 @PostMapping("/upload")
 public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {

  if (file.isEmpty()) {
   redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
   return "redirect:uploadStatus";
  }
  String UploadedFolderLocation = UPLOAD_FILE_LOCATION+"/";
  String fileName = null;
//   this is done to work on IE as well
  String pattern = Pattern.quote(System.getProperty("file.separator"));
  String[] str = file.getOriginalFilename().split(pattern);
  if (str.length > 0)
   fileName = str[str.length - 1];
  else
   fileName = str[0];
  if(!storageService.store(file, fileName,UPLOAD_FILE_LOCATION))
  {
   redirectAttributes.addFlashAttribute("message", "Error occurred while uploading the file");
   redirectAttributes.addFlashAttribute("status", "false");
   return "redirect:/uploadStatus";
  }
  redirectAttributes.addFlashAttribute("message", "You successfully uploaded '" + fileName + "'");
  redirectAttributes.addFlashAttribute("status", "true");
  return "redirect:/uploadStatus";
 }
 
 @GetMapping("/uploadStatus")
 public String uploadStatus(ModelMap m) {
  return "Homepage";
 }
 
 @GetMapping("/upload")  
 public String displayHomePageForAlarm() {
  return "Homepage";
 }

}
// CHANGE IT ACCORDING TO YOUR LOCATION
 private final String UPLOAD_FILE_LOCATION="C:\\programinjava_workspace";
NOTE : Change the location according to your local settings.
Now we will see the Service class : In this class we have created method called store will will actually store the data from client side to server side
StoreService.java

package com.programinjava.learn.service;

import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.multipart.MultipartFile;


@Service
public class StorageService {


 private  Path rootLocation = Paths.get("data/input_data");

 public boolean store(MultipartFile file,String fileName ,String fileLocation){
  try {
    rootLocation = Paths.get(fileLocation);

   if(Files.copy(file.getInputStream(), this.rootLocation.resolve(fileName),StandardCopyOption.REPLACE_EXISTING)>0)
    return true;
  } catch (Exception e) {
   throw new RuntimeException("FAIL!" +e.getMessage());
  }
  return false;
 }

 public Resource loadFile(String filename) {
  try {
   Path file = rootLocation.resolve(filename);
   Resource resource = new UrlResource(file.toUri());
   if(resource.exists() || resource.isReadable()) {
    return resource;
   }else{
    throw new RuntimeException("FAIL!");
   }
  } catch (MalformedURLException e) {
   throw new RuntimeException("FAIL!");
  }
 }

 public void deleteAll(String path) {
  if(path!=null && !path.isEmpty())
  {
   FileSystemUtils.deleteRecursively(Paths.get(path).toFile());
   
  }
  else
   FileSystemUtils.deleteRecursively(rootLocation.toFile());
 }


}
Now let see the HTML template file

<!DOCTYPE html>
<html xmlns:th="http://thymeleaf.org">
<head>
<title>File Upload Example</title>
<link href="webjars/bootstrap/3.3.7/css/bootstrap.min.css"
 rel="stylesheet" />
<script type="text/javascript" src="webjars/jquery/3.3.1/jquery.min.js"></script>
<script src="webjars/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>
<script th:inline="javascript">
 /*<![CDATA[*/
 var _validFileExtensions = [ ".csv", ".zip" ];
 function Validate(oForm) {
  var arrInputs = oForm.getElementsByTagName("input");
  for (var i = 0; i < arrInputs.length; i++) {
   var oInput = arrInputs[i];
   if (oInput.type == "file") {
    var sFileName = oInput.value;
    if (sFileName.length == 0) {

     alert("Please select a file to upload");
     return false;
    }
    if (sFileName.length > 0) {
     var blnValid = false;
     for (var j = 0; j < _validFileExtensions.length; j++) {
      var sCurExtension = _validFileExtensions[j];
      if (sFileName.substr(
        sFileName.length - sCurExtension.length,
        sCurExtension.length).toLowerCase() == sCurExtension
        .toLowerCase()) {
       blnValid = true;
       break;
      }
     }

     if (!blnValid) {
      alert("Invalid File Extension");
      return false;
     }
    }
   }
  }

  return true;
 }
  
 /*]]>*/
</script>

<body>

 <div class="container-fluid padding-0">
  <div class="row padding-0">
   
   <div class="col-md-4">
    <h2>File Upload Example</h2>
   </div>
   <div class="col-md-4" align="right"></div>
  </div>
 </div>
 <nav role="navigation" id="trainingset-container-id"
  class="navbar navbar-default">
  <div class="row" style="margin-top: 10px;">
   <div class="col-md-2">
    <B>Upload File</B>
   </div>
   <div class="col-md-6">
    <form method="POST" action="/upload"
     onsubmit="return Validate(this);" enctype="multipart/form-data">
     <div class="col-sm-6">

      <input type="file" name="file"  />
     </div>
     <div class="col-sm-6">
      <input type="submit" class="btn btn-success btn-sm" value="Upload data" />
     </div>
    </form>
   </div>
   
  </div>
 </nav>
  <div id="messageboxid">
   <div id="uploadstatus" th:if="${message}">
    <B>Status Of Uploaded File</B>
    <h6 th:text="${message}" />
   </div>
  </div>
  
</body>
</html>
Thats it ,

How to run the webpage

you need to hit the below URL
http://localhost:8080/upload

you will be able to see the homepage and then you just need to upload the file and you will get the successful message once uploaded.

Hope this will help you !!

Read Also
  1. Spring Boot and Hibernate Tutorials - Application using Spring Boot
  2. What is Spring boot ?
  3. How to read value from property file in spring boot ?
  4. First Rest API Application - Top Spring Framework Interview Questions
Thanks for reading