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 ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue 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 ();
    }
}

Monday, 22 May 2017

Kotlin Basics

Install in Studio

Go to File --> Settings -->Pluins-->install jet brains plugin-->select kotlin -->Download and install

Restart IDE

Sample Project
--------------------
Create new project
Open MainActivity and then type ctrl+Alt+shft+k
File gets converted to kotlin file

Access UI components in Kotlin file
---------------------------------------------------
Add this import in MainActivity.java "import kotlinx.android.synthetic.main.activity_main.textView;"

Access directly in oncreate as follows

textView.setText("This is kotlin example")


Done build and run:)

Wednesday, 17 May 2017

Android TableLayout Dynamic Creation and filling cells

package com.example.namratha.tableview;

import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.widget.HorizontalScrollView;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    int startTime , endTime;
    int columnName;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        String[] row = {"9", "10", "11", "12", "13", "14",
                "15" ,"16" , "17" , "18", "19" ,"20","21","22","23","24"};
        String[] column = {"COLUMN1", "COLUMN2", "COLUMN3", "COLUMN4",
                "COLUMN5", "COLUMN6" , "COLUMN7" , "COLUMN8" ,"COLUMN9" , "COLUMN10" , "COLUMN11"};
        int rl = row.length;
        int cl = column.length;
        ScrollView sv = new ScrollView(this);
        TableLayout tableLayout = createTableLayout(row, column, rl, cl);

        HorizontalScrollView hsv = new HorizontalScrollView(this);

        hsv.addView(tableLayout);
        sv.addView(hsv);
        setContentView(sv);


        //Meeting time for colun 3 is from 9 to 11        /*startTime = 9;        endTime = 11;        int rowId = findRowID(startTime ,endTime);*/        //meeing time is at 12 for column 3;        int rowIndex = findRowID(15);
        makeCellEmpty(tableLayout , rowIndex , 3);
        //meeting time is 9 to 11        startTime = 9;
        endTime =11;
         columnName =3;
        calculateTimeDiff(tableLayout, columnName );

        startTime = 12;
        endTime =18;
        columnName = 5;
        calculateTimeDiff(tableLayout,columnName);

    }

    private void calculateTimeDiff(TableLayout tableLayout, int name) {
        for(int i = startTime;i<=endTime;i++)
        {
            int rowIndexSample = findRowID(i);
            makeCellEmpty(tableLayout, rowIndexSample,name);

        }
    }


    private int findRowID(int startTime)
    {
        int rowId = 0;
        if(startTime == 9)
            rowId = 1;
        else if(startTime == 10)
            rowId =2;
        else if(startTime == 11)
            rowId =3;
        else if(startTime == 12)
            rowId =4;
        else if(startTime == 13)
            rowId =5;
        else if(startTime == 14)
            rowId =6;
        else if(startTime == 15)
            rowId =7;
        else if(startTime == 16)
            rowId =8;
        else if(startTime == 17)
            rowId =9;
        else if(startTime == 18)
            rowId =10;
        else if(startTime == 19)
            rowId =11;
        else if(startTime == 20)
            rowId =12;
        else if(startTime == 21)
            rowId =13;
        else if(startTime == 22)
            rowId =14;
        else if(startTime == 23)
            rowId =15;
        else if(startTime == 24)
            rowId =16;

        return rowId;

    }


    public void makeCellEmpty(TableLayout tableLayout, int rowIndex, int columnIndex) {
        // get row from table with rowIndex        TableRow tableRow = (TableRow) tableLayout.getChildAt(rowIndex);
/*        tableRow.setLayoutParams(new TableLayout.LayoutParams(                TableLayout.LayoutParams.FILL_PARENT,                TableLayout.LayoutParams.FILL_PARENT, 1.0f));*/        // get cell from row with columnIndex        TextView textView = (TextView) tableRow.getChildAt(columnIndex);

        // make it black        textView.setBackgroundColor(Color.BLACK);

    }

    public void setHeaderTitle(TableLayout tableLayout, int rowIndex, int columnIndex) {

        // get row from table with rowIndex        TableRow tableRow = (TableRow) tableLayout.getChildAt(rowIndex);

        // get cell from row with columnIndex
        TextView textView = (TextView) tableRow.getChildAt(columnIndex);

        textView.setText("Hello");
    }


    private TableLayout createTableLayout(String[] rv, String[] cv, int rowCount, int columnCount) {
        // 1) Create a tableLayout and its params        TableLayout.LayoutParams tableLayoutParams = new TableLayout.LayoutParams();
        TableLayout tableLayout = new TableLayout(this);
        tableLayout.setBackgroundColor(Color.BLACK);


        // 2) create tableRow params        TableRow.LayoutParams tableRowParams = new TableRow.LayoutParams();
        tableRowParams.setMargins(1, 1, 1, 1);
        tableRowParams.weight = 1;


        int leftMargin=10;
        int topMargin=50;
        int rightMargin=10;
        int bottomMargin=50;
      //  tableRowParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);


        for (int i = 0; i < rowCount; i++) {
            // 3) create tableRow            TableRow tableRow = new TableRow(this);
            tableRow.setBackgroundColor(Color.GRAY);
            //tableRow.setBackground(getResources().getDrawable(R.drawable.border));           /* tableRow.setLayoutParams(new TableLayout.LayoutParams(                    TableLayout.LayoutParams.FILL_PARENT,                    TableLayout.LayoutParams.FILL_PARENT, 1.0f));*/
            for (int j = 0; j < columnCount; j++) {
                // 4) create textView                TextView textView = new TextView(this);
                //  textView.setText(String.valueOf(j));                textView.setBackgroundColor(Color.WHITE);
                textView.setGravity(Gravity.CENTER);
                textView.setWidth(200);
                textView.setHeight(300);

                String s1 = Integer.toString(i);
                String s2 = Integer.toString(j);
                String s3 = s1 + s2;
                int id = Integer.parseInt(s3);
                Log.d("TAG", "-___>" + id);
                if (i == 0 && j == 0) {
                    textView.setText("0==0");
                } else if (i == 0) {
                    Log.d("TAAG", "set Column Headers");
                    textView.setText(cv[j - 1]);
                } else if (j == 0) {
                    Log.d("TAAG", "Set Row Headers");
                    textView.setText(rv[i - 1]);
                } else {
//                    textView.setText("" + id);                    // check id=23                    if (id == 23) {
  //                      textView.setText("ID=23");
                    }
                }

                // 5) add textView to tableRow                tableRow.addView(textView, tableRowParams);
            }

            // 6) add tableRow to tableLayout            tableLayout.addView(tableRow, tableLayoutParams);
        }

        return tableLayout;
    }
}


Thursday, 27 April 2017

Interview Questions

1.Activity to thread communicaton
2.static and dynamic broad cast receivers
3.collection and collections diff
4.Arraylist and /array internally working memory...etc
5.java how to create synchronised object
6.Asynctask internal communication
7.Asyntask simultaneously run how?
8.Sharing file b/w application developed by same developer
9.Broadcast receivers and intent filters
10.Custombroad cast
If we do not know intent filters then how can we listen for broad cast?
11.Content Provider Athorisation Token
12.Custom HashMap
13.Activit ifeCucle
14.Data Abstraction
15.Service start two times
16.ArrayList Creation ways
17.Collision
18.Producer Consumer Problem
19.Thread LifeCycle
20.Thread Architecture Java
21.DVM
22.Application Architecture
23.Intent Service
24.Intent Filter


1: Explain Android Architecture?
2: Activity life cycle?
3. Fragment life cycle?
4. Difference between Service,Asynctask,Thread?
5. Difference between Hashmap and Hashtable?
6. What is task affinity?
7. Permission required to access user Location in android?
8. Have you worked in Map integration?Explain in brief.
9.Have you worked in Camera integration?Explain in brief.
10. What are Crash and user analytics tools?
11. How to do good memory management in Android?
12. What is Broadcast receiver?
13.What is Notification?
14 Twitter,Facebook integration.
15. Intent and intent filter.
16. How to create custom permission in Android?
17. Difference between <permission> and <uses permission> tag in Manifest file?
18. What is the use of minSdkVersion,maxSdkVersion,targetSdkVersion in <uses-sdk> in Manifest file?
19 What are Android application components?
20. Why fragment is required?
21 Example of Inheritance in Android application?
22 What is content provider?How to create your own content provider?
23. Difference between content provider and Sqlite database?
24 Have you worked in OpenGL,3d animation in Android?
25. Version control systems.
26.Multiple screen support in Android?
27.Multiple language support in Android?
28. About latest Android OS and what are the new features added on it?
29 Have you developed in any open source library?

Thursday, 20 April 2017

Onclick listener on the view items in RecyclerViewAdapter

int pos = getAdapterPosition();

Call this inside viewholder defined in adapter

One of example
http://wiki.workassis.com/android-recyclerview-example/

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...