Tuesday, 4 July 2017

Solution to producer and Consumer Problem

Using Wait and Notify


public class ProducerConsumer {
LinkedList<Integer> list = new LinkedList<>();
private static final int limit = 10;
private Object lock = new Object();

public void produce() throws InterruptedException {
int value = 0;
while (true) {
synchronized (lock) {
while (list.size() == limit) {
System.out.println("List is full, so Produce thread is waiting..");
lock.wait();
}
list.add(value++);
System.out.println("Producer thread is notify..");
lock.notifyAll();
}
}
}

public void consume() throws InterruptedException {
while (true) {
synchronized (lock) {
while (list.size() == 0) {
System.out.println("List is empty, so Consumer thread is waiting..");
lock.wait();
}
int val = list.remove(0);
System.out.println("Consumer thread notify..");
lock.notifyAll();
}

}
}

public static void main(String a[]) {
final ProducerConsumer producerConsumer = new ProducerConsumer();

Thread producerThread = new Thread(new Runnable() {

@Override
public void run() {
try {
producerConsumer.produce();
} catch (Exception e) {
e.printStackTrace();
}

}
});

Thread consumerThread = new Thread(new Runnable() {

@Override
public void run() {
try {
producerConsumer.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}

}
});

producerThread.start();
consumerThread.start();
}
}

Using BlockingQueue


 
public class ProducerConsumerWithBlockingQueue {
private final int LIMIT = 10;
private BlockingQueue<Integer> blockingQueue = new LinkedBlockingDeque<Integer>();
public void producer() throws InterruptedException{
int val = 0;
while (true) {
blockingQueue.put(val++);
}
}
public void consumer() throws InterruptedException {
while(true) { 
int val = blockingQueue.take();
}
}

}

What is Producer and consumer Problem in Java

In computing, the producer–consumer problem[1][2] (also known as the bounded-buffer problem) is a classic example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, who share a common, fixed-size buffer used as a queue. The producer's job is to generate data, put it into the buffer, and start again. At the same time, the consumer is consuming the data (i.e., removing it from the buffer), one piece at a time. The problem is to make sure that the producer won't try to add data into the buffer if it's full and that the consumer won't try to remove data from an empty buffer.
The solution for the producer is to either go to sleep or discard data if the buffer is full. The next time the consumer removes an item from the buffer, it notifies the producer, who starts to fill the buffer again. In the same way, the consumer can go to sleep if it finds the buffer to be empty. The next time the producer puts data into the buffer, it wakes up the sleeping consumer. The solution can be reached by means of inter-process communication, typically using semaphores. An inadequate solution could result in a deadlock where both processes are waiting to be awakened. The problem can also be generalized to have multiple producers and consumers.


Java blocking Queue


Today we will look into Java BlockingQueue. java.util.concurrent.BlockingQueue is a java Queue that support operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.

Java BlockingQueue doesn’t accept null values and throw NullPointerException if you try to store null value in the queue.
Java BlockingQueue implementations are thread-safe. All queuing methods are atomic in nature and use internal locks or other forms of concurrency control.

Java BlockingQueue interface is part of java collections framework and it’s primarily used for implementing producer consumer problem. We don’t need to worry about waiting for the space to be available for producer or object to be available for consumer in BlockingQueue because it’s handled by implementation classes of BlockingQueue.
Java provides several BlockingQueue implementations such as ArrayBlockingQueueLinkedBlockingQueuePriorityBlockingQueueSynchronousQueue etc.
While implementing producer consumer problem in BlockingQueue, we will use ArrayBlockingQueue implementation. Following are some important methods you should know.
  • put(E e): This method is used to insert elements to the queue. If the queue is full, it waits for the space to be available.
  • E take(): This method retrieves and remove the element from the head of the queue. If queue is empty it waits for the element to be available.

Interview Programs

Simple Android thread and handler example

onCreate()
{
//layout and progress bar we have
//thread creation
thread = new Thread(new Mythread())
thread.start();
handler = new Handler()
{
handleMessage(Message msg)
{

//set value to progress bar

}
};



}

class Mythread implements Runnable
{


run()
{
//create Message object

for(int i =0;i<10;i++)
{
Message msg = Message.obtain();
msg.arg1 = i;
handler.sendMesahe(mg);

}

}


}

Download an image and send it to UI android httpurlconnection

private void downloadImage(String urlStr) {
      progressDialog = ProgressDialog.show(this, "", "Downloading Image from " + urlStr);
      final String url = urlStr;

      new Thread() {
         public void run() {
            InputStream in = null;

            Message msg = Message.obtain();
            msg.what = 1;

            try {
               in = openHttpConnection(url);
               bitmap = BitmapFactory.decodeStream(in);
               Bundle b = new Bundle();
               b.putParcelable("bitmap", bitmap);
               msg.setData(b);
               in.close();
            }catch (IOException e1) {
               e1.printStackTrace();
            }
            messageHandler.sendMessage(msg);
         }
      }.start();
   }

  private Handler messageHandler = new Handler() {
      public void handleMessage(Message msg) {
         super.handleMessage(msg);
         ImageView img = (ImageView) findViewById(R.id.imageView);
         img.setImageBitmap((Bitmap) (msg.getData().getParcelable("bitmap")));
         progressDialog.dismiss();
      }

   };

Fibonacci series


class FibExample{  
public static void main(String args[])  
{    
 int n1=0,n2=1,n3,i,count=10;    
 System.out.print(n1+" "+n2);//printing 0 and 1    
    
 for(i=2;i<count;i++)//loop starts from 2 because 0 and 1 are already printed    
 {    
  n3=n1+n2;    
  System.out.print(" "+n3);    
  n1=n2;    
  n2=n3;    
 }    
  
}}  

Find duplicates in array


public class DuplicateArray {


public static void main(String[] args) {
int sample [] = {1,2,3,4,5,2,3,4,2,2,2};
HashMap<Integer ,Integer> testMap = new HashMap<Integer,Integer>();
for(int  num : sample)
{
int i = 1;
if(!testMap.containsKey(num))
{
testMap.put(num, i);
}else
{
testMap.put(num, testMap.get(num)+1);
}
//System.out.println("print"+num);
}
for (HashMap.Entry<Integer, Integer> entry : testMap.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}

}
}

Reverse a String


public class ReverseString {

public static void main(String[] args) {

String test ="ABCD";
StringBuffer sb = new StringBuffer();
for(int i = test.length()-1 ;i>=0;i--)
{
sb.append(test.charAt(i));
}

System.out.println("print rev"+sb.toString());
}
}

Java Simple CallBack Example


public interface EventInterface {



public void notifyEventExample();

}

public class CallBack {

public EventInterface eI;
public CallBack(EventInterface eventInt)
{
this.eI = eventInt;
sendEvent();
}
public void sendEvent()
{
eI.notifyEventExample();
}
}



public class CallBackreceiver implements EventInterface {
public CallBackreceiver() { CallBack testCallBack = new CallBack(this); }
/* * public void testMethod() { testCallBack.sendEvent(); } */ public static void main(String args[]) {
CallBackreceiver receicer = new CallBackreceiver(); // receicer.testMethod();
}
public void notifyEventExample() { System.out.println("I'm Called"); }
}

Download an image from web service and load into an image view

@Override
    protected Bitmap doInBackground(String... params) {
     Bitmap bitmap = null;
     try {
         URL url = new URL(params[0]);
                bitmap = BitmapFactory.decodeStream((InputStream)url.getContent());
 } catch (IOException e) {
  Log.e(TAG, e.getMessage());
 }
        return bitmap;
    }
@Override
    protected void onPostExecute(Bitmap bitmap) {
  imageView.setImageBitmap(bitmap);
    }

Reverse a string with out using String Buffer and String builder

public static String reverse(String source){
        if(source == null || source.isEmpty()){
            return source;
        }       
        String reverse = "";
        for(int i = source.length() -1; i>=0; i--){
            reverse = reverse + source.charAt(i);
        }
      
        return reverse;
    }



Alternate thread printing odd and even




public class PrintOddEvenInSequence {


private boolean isOddPrinting = false;

private boolean isEvenPrinting = false;

private int oddNum = 0;
private int evenNum = 0;
public static void main (String args[]) {
final PrintOddEvenInSequence oddEvenInSequence = new PrintOddEvenInSequence();
Thread printOddNumThread = new Thread(new Runnable() {
public void run() {
oddEvenInSequence.printOddNumber();
}
});
printOddNumThread.start();
Thread printEvenNumThread = new Thread(new Runnable() {
public void run() {
oddEvenInSequence.printEvenNumber();
}
});
printEvenNumThread.start();
}
private void printOddNumber() {
synchronized (this) {
while (true) {
while (isEvenPrinting) {
try {
System.out.println("Waiting to print odd number");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
isOddPrinting = true;
System.out.println(++oddNum);
isOddPrinting = false;
notify();
}
}
}
private void printEvenNumber() {
synchronized (this) {
while (true) {
while (isOddPrinting) {
try {
System.out.println("Waiting to print even number");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
isEvenPrinting = true;
System.out.println(++evenNum);
isEvenPrinting = false;
notify();
}
}
}

}



Find number of repeating characters in a string



public class Testmain {

public static void main(String args[])throws Exception{
int  count = 0;
String s = "ABCDABD";
for(int i = 0;i<s.length();i++)
{
for(int j = i+1;j<s.length();j++)
{
if(s.charAt(i)==s.charAt(j))
{
count++;
System.out.println("repeated character is "+s.charAt(i));
}
}
}

System.out.println("count "+count);
}


}

Remove Specific character from string


 public static String removeCharInString (String string, char charToBeRemoved) {

        if (string == null)
             return "";

       
         StringBuilder strBuild = new StringBuilder ();

        for (int i = 0; i < string.length (); i++) {
            char chr = string.charAt (i);
            if (chr == charToBeRemoved)
                continue;
            strBuild.append (chr);
        }
        return strBuild.toString ();
    }
}

Pass a HashMap from Angular Client to Spring boot API

This example is for the case where fileData is very huge and in json format   let map = new Map<string, string>()      map.set(this.ge...