SringSring

Thursday, 30 October 2014

Top 10 Reasons Your Application Is Running Poorly

“Hey…the Internet is down” or “the application is really slow” are common problems I’ve heard over the years. As the Ned Stark meme goes, how does one simply fix “it’s slow”?

Full disclosure, this list is not scientific, it’s just based upon experience dealing with customers trying to solve application issues.

Configuration – The wrong Thread Pool or Connection Pool Settings.
Not providing enough threads to match large load can cause serious blocking issues and create  bottlenecks.
Memory Management – Improper Memory Configuration for the Code Size and Transaction Volume.
Improper memory settings can cause excessive garbage collection and REMEMBER, in Java,
a “Full Garbage Collection” means ALL THREADS STOP.
Web Services  – SOAP based web services have more overall overhead when compared to REST based web services.
Did you know that a simple SOAP web service call that returns a temperature or a zip code requires 1 or 2KB of packaging data? Like shipping a watch in a big box full of foam peanuts. Unnecessary overhead.
Object Relational Mapping – We are really talking about Java and Hibernate Abuse.
Application Code – Poorly written code. Make ALL of your developers read Code Complete by Steve McConnell
  and Implement Unit Testing. Both can great improve the quality of their code.
Input/Output Bottlenecks – Storage and network bottlenecks –
Ensure your disks are configured for sufficient I/O.
You need to make sure you have sufficient I/O configurations, especially in virtual machine and complex environments.
Logging Accidentally left on DEBUG mode – After your major load test, did you leave your logging solution in DEBUG mode? This can create a huge bottleneck that correlates directly with load. However, this problem is pretty sneaky and you won’t discover this issues unless you run a major load test.
Request Overload – We have too many inbound requests coming in and not enough resources to handle the load —
Simply a bandwidth issue.
Database – It’s probably not the database. Oracle DBA’s typically run a fast databases.
SQL Server implementations are typically less tuned for performance.
Database, cont. – It’s probably the database, bad index or just a bad query.
 Could also be a developer writing a query inside a query. (See Above)

Wednesday, 29 October 2014

Junit Test cases examples

package Com.Srini.Junit;

import static org.junit.Assert.*;

import org.junit.Test;

public class MyUnitTest {
@Test
   public void testConcatenate() {
       MyUnit myUnit = new MyUnit();

       String result = myUnit.concatenate("one", "two");

       assertEquals("onetwo", result);

   }
@Test
   public void testGetTheStringArray() {
       MyUnit myUnit = new MyUnit();

       String[] expectedArray = {"one", "two", "three"};

       String[] resultArray =  myUnit.getTheStringArray();

       assertArrayEquals(expectedArray, resultArray);
   }
@Test
   public void testGetTheBoolean() {
       MyUnit myUnit = new MyUnit();

       assertTrue (myUnit.getTheBoolean());

       assertFalse(myUnit.getTheBoolean());
   }

}
-------------------------------------------
package Com.Srini.Junit;

public class MyUnit {
public String concatenate(String one, String two){
        return one + two;
    }
public String[] getTheStringArray(){
String strArry[]={"one", "two", "three"};
return strArry;
}

public boolean getTheBoolean() {
// TODO Auto-generated method stub
return true;
}
}
----------------------------------
package Com.Srini.Junit;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.junit.Test;

public class MyMatcherTest {
@Test
    public void testWithMatchers() {
        assertThat("this string", is("this string"));
        assertThat(123, is(123));
    }
}

Display OrderByValue in map

package Com.Srini.program;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

public class OrderByValue {
public static void main(String a[]){
       Map<String, Integer> map = new HashMap<String, Integer>();
       map.put("java", 20);
       map.put("C++", 45);
       map.put("Java2Novice", 2);
       map.put("Unix", 67);
       map.put("MAC", 26);
       map.put("Why this kolavari", 93);
       Set<Entry<String, Integer>> set = map.entrySet();
       List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
       Collections.sort( list, new Comparator<Map.Entry<String, Integer>>()
       {
           public int compare( Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 )
           {
               return (o2.getValue()).compareTo( o1.getValue() );
           }
       } );
       for(Map.Entry<String, Integer> entry:list){
           System.out.println(entry.getKey()+" ==== "+entry.getValue());
       }
/*Map<String, Integer> map = new HashMap<String, Integer>();
       map.put("java", 20);
       map.put("C++", 45);
       map.put("Java2Novice", 2);
       map.put("Unix", 67);
       map.put("MAC", 26);
       map.put("Why this kolavari", 93);
       Set<Entry<String, Integer>> set = map.entrySet();
     
       Iterator itr = set.iterator();
       while(itr.hasNext())
       {
           System.out.println(itr.next());
       }*/
     
   }
}

StringTokenizer in java

package Com.Srini.program;

import java.util.StringTokenizer;

public class MyStringTokens {
//public class MyStringTokens {
   public static void main(String a[]){
       String msg = "http://10.123.43.67:80/";
       StringTokenizer st = new StringTokenizer(msg,"://.");
       while(st.hasMoreTokens()){
           System.out.println(st.nextToken());
       }
   }
}

Hash Code Implementation in java

package Com.Srini.program;

import java.util.HashMap;

public class MyHashcodeImpl {
public static void main(String a[]){
       
       HashMap<Price, String> hm = new HashMap<Price, String>();
       hm.put(new Price("Banana", 20), "Banana");
       hm.put(new Price("Apple", 40), "Apple");
       hm.put(new Price("Orange", 30), "Orange");
       //creating new object to use as key to get value
       Price key = new Price("Banana", 20);
       System.out.println("Hashcode of the key: "+key.hashCode());
       System.out.println("Value from map: "+hm.get(key));
   }
}

class Price{
   
   private String item;
   private int price;
   
   public Price(String itm, int pr){
       this.item = itm;
       this.price = pr;
   }
   
   public int hashCode(){
       System.out.println("In hashcode");
       int hashcode = 0;
       hashcode = price*20;
       hashcode += item.hashCode();
       return hashcode;
   }
   
   public boolean equals(Object obj){
       System.out.println("In equals");
       if (obj instanceof Price) {
           Price pp = (Price) obj;
           return (pp.item.equals(this.item) && pp.price == this.price);
       } else {
           return false;
       }
   }
   
   public String getItem() {
       return item;
   }
   public void setItem(String item) {
       this.item = item;
   }
   public int getPrice() {
       return price;
   }
   public void setPrice(int price) {
       this.price = price;
   }
   
   public String toString(){
       return "item: "+item+"  price: "+price;
   }
}

Fibonacci series program in java

package Com.Srini.program;

public class MyFibonacci {
 /*public static void main(String a[]){
       
         int febCount = 15;
         int[] feb = new int[febCount];
         feb[0] = 0;
         feb[1] = 1;
         for(int i=2; i < febCount; i++){
             feb[i] = feb[i-1] + feb[i-2];
         }

         for(int i=0; i< febCount; i++){
                 System.out.print(feb[i] + " ");
         }
       
    }*//*public final static void main(String[] args){
     double d = 10.0 / -0;
     if(d == Double.POSITIVE_INFINITY)
     System.out.println("Positive infinity");
     else
       System.out.println("Negative infinity");
    }*/

 public static void main(String[] args){
   int[] a = {1};
   MyFibonacci t = new MyFibonacci();
   t.increment(a);
   System.out.println(a[a.length - 1]);
}
 void increment(int[] i){
    i[i.length - 1]++;
 
 }

}

Deadlock in threads

package Com.Srini.program;

public class MyDeadlock {

String str1 = "Java";
    String str2 = "UNIX";
   
    Thread trd1 = new Thread("My Thread 1"){
        public void run(){
            while(true){
                synchronized(str1){
                    synchronized(str2){
                        System.out.println(str1 + str2);
                    }
                }
            }
        }
    };
   
    Thread trd2 = new Thread("My Thread 2"){
        public void run(){
            while(true){
                synchronized(str2){
                    synchronized(str1){
                        System.out.println(str2 + str1);
                    }
                }
            }
        }
    };
   
    public static void main(String a[]){
        MyDeadlock mdl = new MyDeadlock();
        mdl.trd1.start();
        mdl.trd2.start();
    }
}

Missing or Duplicate number in specified number.

package Com.Srini.program;

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

public class DuplicateNumber {
public int findDuplicateNumber(List<Integer> numbers){
       
        int highestNumber = numbers.size() - 1;
        System.out.println(" highestNumber : "+highestNumber);
        int total = getSum(numbers);
        System.out.println(" total : "+total);
        int duplicate = total - (highestNumber*(highestNumber+1)/2);
        return duplicate;
    }
   
    public int getSum(List<Integer> numbers){
       
        int sum = 0;
        for(int num:numbers){
            sum += num;
        }
        return sum;
    }
   
    public static void main(String a[]){
        List<Integer> numbers = new ArrayList<Integer>();
        for(int i=1;i<6;i++){
            numbers.add(i);
        }
        //add duplicate number into the list
        numbers.add(5);
       // numbers.add(23);
        DuplicateNumber dn = new DuplicateNumber();
        System.out.println("Duplicate Number: "+dn.findDuplicateNumber(numbers));
    }
}

Find duplicate characters in String in java

package Com.Srini.program;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class DuplicateCharsInString {
public void findDuplicateChars(String str){
       
       Map<Character, Integer> dupMap = new HashMap<Character, Integer>();
       char[] chrs = str.toCharArray();
       for(Character ch:chrs){
           if(dupMap.containsKey(ch)){
               dupMap.put(ch, dupMap.get(ch)+1);
           } else {
               dupMap.put(ch, 1);
           }
       }
       Set<Character> keys = dupMap.keySet();
       for(Character ch:keys){
           if(dupMap.get(ch) > 1){
               System.out.println(ch+"--->"+dupMap.get(ch));
           }
       }
   }
   
public  static void     main(String a[]){
       DuplicateCharsInString dcs = new DuplicateCharsInString();
       dcs.findDuplicateChars("SRINIVAS");
   }

}

Count the duplicated elements in the list in java

package Com.Srini.program;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class CountDuplicatedList {
public static void main(String[] args) {

List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("b");
list.add("c");
list.add("a");
list.add("a");
list.add("a");

System.out.println("\nExample 1 - Count 'a' with frequency");
System.out.println("a : " + Collections.frequency(list, "a"));

System.out.println("\nExample 2 - Count all with frequency");
Set<String> uniqueSet = new HashSet<String>(list);
for (String temp : uniqueSet) {
System.out.println(temp + ": " + Collections.frequency(list, temp));
}

System.out.println("\nExample 3 - Count all with Map");
Map<String, Integer> map = new HashMap<String, Integer>();

for (String temp : list) {
Integer count = map.get(temp);
map.put(temp, (count == null) ? 1 : count + 1);
}
printMap(map);

System.out.println("\nSorted Map");
Map<String, Integer> treeMap = new TreeMap<String, Integer>(map);
printMap(treeMap);

 }

 public static void printMap(Map<String, Integer> map){

for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : "
+ entry.getValue());
}

 }
}

Tuesday, 28 October 2014

String Revers by using recursive method in java

package Com.Srini.program;

public class StringRecursiveReversal {
/*String reverse = "";
 
    public String reverseString(String str){
       
        if(str.length() == 1){
            return str;
        } else {
            reverse += str.charAt(str.length()-1)
                    +reverseString(str.substring(0,str.length()-1));
            return reverse;
        }
    }
   
    public static void main(String a[]){
        StringRecursiveReversal srr = new StringRecursiveReversal();
        System.out.println("Result: "+srr.reverseString("Java2novice"));
    }*/
public static void main(String args[])
  {
     String original, reverse = "";
    // Scanner in = new Scanner(System.in);

     System.out.println("Enter a string to reverse");
     original = "SRINI";

     int length = original.length();

     for ( int i = length - 1 ; i >= 0 ; i-- )
        reverse = reverse + original.charAt(i);

     System.out.println("Reverse of entered string is: "+reverse);
  }
}

Reading data from XML using SAXS parsers in java

package Com.Srini.SAXS;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

//import Com.Srini.DOM.ReadXml;

public class ReadXml extends DefaultHandler {
public static void main(String[] args){
ReadXml read=new ReadXml();
read.getXml();
}
public void getXml(){
 try {
  // obtain and configure a SAX based parser
  SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();

  // obtain object for SAX parser
  SAXParser saxParser = saxParserFactory.newSAXParser();

  // default handler for SAX handler class
  // all three methods are written in handler's body
  DefaultHandler defaultHandler = new DefaultHandler(){
   
   String firstNameTag="close";
   String lastNameTag="close";
   String emailTag="close";
   String phoneTag="close";
   
   // this method is called every time the parser gets an open tag '<'
   // identifies which tag is being open at time by assigning an open flag
   public void startElement(String uri, String localName, String qName,
     Attributes attributes) throws SAXException {
   
    if (qName.equalsIgnoreCase("FIRSTNAME")) {
     firstNameTag = "open";
    }
    if (qName.equalsIgnoreCase("LASTNAME")) {
     lastNameTag = "open";
    }
    if (qName.equalsIgnoreCase("EMAIL")) {
     emailTag = "open";
    }
    if (qName.equalsIgnoreCase("PHONE")) {
     phoneTag = "open";
    }
   }

   // prints data stored in between '<' and '>' tags
   public void characters(char ch[], int start, int length)
     throws SAXException {
     
    if (firstNameTag.equals("open")) {
     System.out.println("First Name : " + new String(ch, start, length));
    }
    if (lastNameTag.equals("open")) {
     System.out.println("Last Name : " + new String(ch, start, length));
    }
    if (emailTag.equals("open")) {
     System.out.println("Email : " + new String(ch, start, length));
    }
    if (phoneTag.equals("open")) {
     System.out.println("Phone : " + new String(ch, start, length));
    }
   }

   // calls by the parser whenever '>' end tag is found in xml  
   // makes tags flag to 'close'
   public void endElement(String uri, String localName, String qName)
     throws SAXException {
     
    if (qName.equalsIgnoreCase("firstName")) {
     firstNameTag = "close";
    }
    if (qName.equalsIgnoreCase("lastName")) {
     lastNameTag = "close";
    }
    if (qName.equalsIgnoreCase("email")) {
     emailTag = "close";
    }
    if (qName.equalsIgnoreCase("phone")) {
     phoneTag = "close";
    }
   }
  };
   
  // parse the XML specified in the given path and uses supplied
  // handler to parse the document
  // this calls startElement(), endElement() and character() methods
  // accordingly
  saxParser.parse("E://xml/student.xml", defaultHandler);
 } catch (Exception e) {
  e.printStackTrace();
 }
}
}

Read data from XMl using JAXB in java

package Com.Srini.JaxB;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class JAXBExampleXmlToObject {
public static void main(String[] args) {

try {

File file = new File("E:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);

Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
System.out.println(customer.name);

 } catch (JAXBException e) {
e.printStackTrace();
 }

}
}

Create XML file using JAXB in java

package Com.Srini.JaxB;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
public static void main(String[] args) {

 Customer customer = new Customer();
 customer.setId(100);
 customer.setName("mkyong");
 customer.setAge(29);

 try {

File file = new File("E:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

jaxbMarshaller.marshal(customer, file);
jaxbMarshaller.marshal(customer, System.out);

     } catch (JAXBException e) {
e.printStackTrace();
     }

}
}

Program for read the data from xml using DOM in java

package Com.Srini.DOM;

import java.io.File;

import javax.xml.parsers.DocumentBuilderFactory;



import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ReadXml {
public static void main(String[] args){
ReadXml read=new ReadXml();
read.readXML();
}
public void readXML() {

 try {

  File xmlFile = new File("E://xml/student.xml");
  DocumentBuilderFactory documentFactory = DocumentBuilderFactory
    .newInstance();
  DocumentBuilder documentBuilder = documentFactory
    .newDocumentBuilder();
  Document doc = documentBuilder.parse(xmlFile);

  doc.getDocumentElement().normalize();
  NodeList nodeList = doc.getElementsByTagName("student");

  System.out.println("Root element :"
    + doc.getDocumentElement().getNodeName());

  for (int temp = 0; temp < nodeList.getLength(); temp++) {
   Node node = nodeList.item(temp);

   System.out.println("\nElement type :" + node.getNodeName());

   if (node.getNodeType() == Node.ELEMENT_NODE) {

    Element student = (Element) node;

    System.out.println("Student id : "
      + student.getAttribute("id"));
    System.out.println("First Name : "
      + student.getElementsByTagName("firstname").item(0)
        .getTextContent());
    System.out.println("Last Name : "
      + student.getElementsByTagName("lastname").item(0)
        .getTextContent());
    System.out.println("Email Id : "
      + student.getElementsByTagName("email").item(0)
        .getTextContent());
    System.out.println("Phone No : "
      + student.getElementsByTagName("phone").item(0)
        .getTextContent());

   }
  }
 } catch (Exception e) {
  e.printStackTrace();
 }
}


}

Sample program for create xml data using DOM in java

package Com.Srini.DOM;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
 
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class CreateXml {
public static void main(String[] args){
CreateXml read=new CreateXml();
read.createXML();
}
public void createXML() {
 try {

  DocumentBuilderFactory documentFactory = DocumentBuilderFactory
    .newInstance();
  DocumentBuilder documentBuilder = documentFactory
    .newDocumentBuilder();

  // define root elements
  Document document = documentBuilder.newDocument();
  Element rootElement = document.createElement("school");
  document.appendChild(rootElement);

  // define school elements
  Element school = document.createElement("Student");
  rootElement.appendChild(school);

  // add attributes to school
  Attr attribute = document.createAttribute("id");
  attribute.setValue("1");
  school.setAttributeNode(attribute);

  // firstname elements
  Element firstname = document.createElement("firstname");
  firstname.appendChild(document.createTextNode("ankush"));
  school.appendChild(firstname);

  // lastname elements
  Element lastname = document.createElement("lastname");
  lastname.appendChild(document.createTextNode("thakur"));
  school.appendChild(lastname);

  // email elements
  Element email = document.createElement("email");
  email.appendChild(document.createTextNode("beingjavaguy@gmail.com"));
  school.appendChild(email);

  // phone elements
  Element phone = document.createElement("phone");
  phone.appendChild(document.createTextNode("8767675434"));
  school.appendChild(phone);

  // creating and writing to xml file
  TransformerFactory transformerFactory = TransformerFactory
    .newInstance();
  Transformer transformer = transformerFactory.newTransformer();
  DOMSource domSource = new DOMSource(document);
  StreamResult streamResult = new StreamResult(new File(
  "E://xml/student1.xml"));

  transformer.transform(domSource, streamResult);

  System.out.println("File saved to specified path!");

 } catch (ParserConfigurationException pce) {
  pce.printStackTrace();
 } catch (TransformerException tfe) {
  tfe.printStackTrace();
 }
}

}

Abstract Design Pattern in java

package Com.Srini.DesignPatterns.AbstractFactory;

public class AbstractFactoryTest {

   public static void main(String a[]){
       Button btn = GUIFactory.createButton();
       btn.paint();
   }
}

----------------------------------------------------------
package Com.Srini.DesignPatterns.AbstractFactory;

public interface Button {
public void paint();
}

--------------------------------------------------
package Com.Srini.DesignPatterns.AbstractFactory;

public interface ButtonFactory {
public Button createButton();
}
-----------------------------------------------------
package Com.Srini.DesignPatterns.AbstractFactory;

public class GUIFactory {
private GUIFactory(){
       //make private constructor..
   }
    
   public static Button createButton(){
        
       String os = null;
       /**
        * this method should work based on the operating system
        * it is running on. First we need to decide which operating 
        * system is it.
        * 
        * for the example purpose, i will hardcode OS as windows.
        */
        
       os = "mac"; //this is hardcoded value. it should be assigned
                       // with dynamic logic.
       if("windows".equalsIgnoreCase(os)){
           return new WindowsFactory().createButton();
       } else if("mac".equalsIgnoreCase(os)){
           return new MacOsFactory().createButton();
       }
        
       return null;
   }
}
---------------------------------------------------------
package Com.Srini.DesignPatterns.AbstractFactory;

public class MacButton implements Button {
@Override
    public void paint() {
        /** add code to paint MAC OS button **/
        System.out.println("painting MAC OS button...");
    }
}
------------------------------------------------------------
package Com.Srini.DesignPatterns.AbstractFactory;

public class MacOsFactory implements ButtonFactory {

@Override
   public Button createButton() {
       /**
        * this method creates a button for MAC OS 
        * button
        */
       System.out.println("creating mac os button...");
       return new MacButton();
   }

}
----------------------------------------------------
package Com.Srini.DesignPatterns.AbstractFactory;



public class WindowsButton implements Button {

@Override
    public void paint() {
        /** add code to paint windows button **/
        System.out.println("painting windows button...");
    }

}
--------------------------------------------------
package Com.Srini.DesignPatterns.AbstractFactory;

public class WindowsFactory implements ButtonFactory {

@Override
   public Button createButton() {
        
       /**
        * this method creates a button for windows 
        * button
        */
       System.out.println("creating windows button...");
       return new WindowsButton();
   }

}
-----------------------------------------------------

Factory Design pattern

package Com.Srini.DesignPatterns.Factory;

public class CurrencyFactory {
public static Currency getCurrencyByCountry(String cnty) throws Exception{
       
       if("IN".equalsIgnoreCase(cnty)){
           return new India();
       } else if("USA".equalsIgnoreCase(cnty)){
           return new USA();
       }
       throw new Exception("Invalid country...");
   }
   
   
   public static void main(String a[]){
       Currency india;
       try {
           india = CurrencyFactory.getCurrencyByCountry("USA");
           System.out.println("Indian currency: "+india.getCurrency());
           System.out.println("Indian currency symbol: "+india.getSymbol());
       } catch (Exception e) {
           e.printStackTrace();
       }
   }
}
-------------------------------------------
package Com.Srini.DesignPatterns.Factory;

public interface Currency {
public String getCurrency();
     
   public String getSymbol();
}
------------------------------------------
package Com.Srini.DesignPatterns.Factory;

public class India implements Currency{
@Override
   public String getCurrency() {
        
       return "Rupee";
   }
 
   @Override
   public String getSymbol() {
        
       return "Rs";
   }
 
   public static void main(String a[]){
        
       India in = new India();
       System.out.println(in.getSymbol());
   }
}
-------------------------------------
package Com.Srini.DesignPatterns.Factory;

public class USA implements Currency{
@Override
    public String getCurrency() {
         
        return "Dollar";
    }
 
    @Override
    public String getSymbol() {
         
        return "$";
    }
}

Difference between Array vs ArrayList in Java

1) Array is a fixed length data structure. ArrayList is a variable length Collection class.
2) You can not use Generics along with Array, as Array instance knows about what kind of type it can hold and throws ArrayStoreException, if you try to store type which is not convertible into type of Array. ArrayList allows you to use Generics to ensure type-safety.
3) All kinds of Array provides length variable which denotes length of Array while ArrayList provides size() method to calculate size of ArrayList.
4) You can not store primitives in ArrayList, it can only contain Objects. While Array can contain both primitives and Objects in Java.
5) Create instance of ArrayList without specifying size, Java will create Array List with default size but its mandatory to provide size of Array while creating either directly or indirectly by initializing Array while creating it.

What is Thread Dump?


Thread Life Cycle in java.



thread life cycle in java flowchart Thread life cycle in java and thread scheduling


Thread life cycle in java and thread scheduling

In previous post I have covered almost all the terms related to Java threads. Here we will learn Thread life cycle in java, we’ll also see thread scheduling.

Recommended Reads:

Thread Life cycle in Java

  • The start method creates the system resources, necessary to run the thread, schedules the thread to run, and calls the thread’s run method.
  • A thread becomes “Not Runnable” when one of these events occurs:
    • If sleep method is invoked.
    • The thread calls the wait method.
    • The thread is blocking on I/O.
  • A thread dies naturally when the run method exits.
Below diagram clearly depicts the various phases of thread life cycle in java.

 Thread Scheduling

  • Execution of multiple threads on a single CPU, in some order, is called scheduling.
  • In general, the runnable thread with the highest priority is active (running)
  • Java is priority-preemptive
    • If a high-priority thread wakes up, and a low-priority thread is running
    • Then the high-priority thread gets to run immediately
  • Allows on-demand processing
  • Efficient use of CPU

2.1 Types of scheduling

  • Waiting and Notifying
    • Waiting [wait()] and notifying [notify(), notifyAll()] provides means of communication between threads that synchronize on the same object.
  • wait(): when wait() method is invoked on an object, the thread executing that code gives up its lock on the object immediately and moves the thread to the wait state.
  • notify(): This wakes up threads that called wait() on the same object and moves the thread to ready state.
  • notifyAll(): This wakes up all the threads that called wait() on the same object.
  • Running and Yielding
    • Yield() is used to give the other threads of the same priority a chance to execute i.e. causes current running thread to move to runnable state.
  • Sleeping and Waking up
    • nSleep() is used to pause a thread for a specified period of time i.e. moves the current running thread to Sleep state for a specified amount of time, before moving it to runnable state. Thread.sleep(no. of milliseconds);

2.2 Thread Priority

  • When a Java thread is created, it inherits its priority from the thread that created it.
  • You can modify a thread’s priority at any time after its creation using the setPrioritymethod.
  • Thread priorities are integers ranging between MIN_PRIORITY (1) and MAX_PRIORITY (10) . The higher the integer, the higher the priority.Normally the thread priority will be 5.

2.3 isAlive() and join() methods

  • isAlive() method is used to determine if a thread is still alive. It is the best way to determine if a thread has been started but has not yet completed its run() method. final boolean isAlive();
  • The nonstatic join() method of class Thread lets one thread “join onto the end” of another thread. This method waits until the thread on which it is called terminates. final void join();

3. Blocking Threads

  • When reading from a stream, if input is not available, the thread will block
  • Thread is suspended (“blocked”) until I/O is available
  • Allows other threads to automatically activate
  • When I/O available, thread wakes back up again
    • Becomes “runnable” i.e. gets into ready state

4. Grouping of threads

  • Thread groups provide a mechanism for collecting multiple threads into a single object and manipulating those threads all at once, rather than individually.
  • To put a new thread in a thread group the group must
  • be explicitly specified when the thread is created
    • - public Thread(ThreadGroup group, Runnable runnable)
    • - public Thread(ThreadGroup group, String name)
    • - public Thread(ThreadGroup group, Runnable runnable, String name)
  • A thread can not be moved to a new group after the thread has been created.
  • When a Java application first starts up, the Java runtime system creates a ThreadGroup named main.
  • Java thread groups are implemented by the java.lang.ThreadGroup class.

Process vs Thread?

Process:
An executing instance of a program is called a process.
Some operating systems use the term ‘task‘ to refer to a program that is being executed.
A process is always stored in the main memory also termed as the primary memory or random access memory.
Therefore, a process is termed as an active entity. It disappears if the machine is rebooted.
Several process may be associated with a same program.
On a multiprocessor system, multiple processes can be executed in parallel.
On a uni-processor system, though true parallelism is not achieved, a process scheduling algorithm is applied and the processor is scheduled to execute each process one at a time yielding an illusion of concurrency.
Example: Executing multiple instances of the ‘Calculator’ program. Each of the instances are termed as a process.
Thread:
A thread is a subset of the process.
It is termed as a ‘lightweight process’, since it is similar to a real process but executes within the context of a process and shares the same resources allotted to the process by the kernel (See kquest.co.cc/2010/03/operating-system for more info on the term ‘kernel’).
Usually, a process has only one thread of control – one set of machine instructions executing at a time.
A process may also be made up of multiple threads of execution that execute instructions concurrently.
Multiple threads of control can exploit the true parallelism possible on multiprocessor systems.
On a uni-processor system, a thread scheduling algorithm is applied and the processor is scheduled to run each thread one at a time.
All the threads running within a process share the same address space, file descriptors, stack and other process related attributes.
Since the threads of a process share the same memory, synchronizing the access to the shared data withing the process gains unprecedented importance.

String equality in java

package com.srini;

public class StringEquality {

/**
* @param args
*/
public static void main(String[] args) {
String obj1 = new String("xyz");
String A= "TEST";
String B= new String("TEST");

String obj2 = new String("xyz");

if(obj1 == obj2)
  System.out.println("obj1==obj2 is TRUE");
else
 System.out.println("obj1==obj2 is FALSE");
if(obj1.equals(obj2))
  System.out.println("obj1.equals(obj2) is TRUE");
else
 System.out.println("obj1.equals(obj2) is FALSE");

if(A == B)
  System.out.println("A==B is TRUE");
else
 System.out.println("A==B is FALSE");
if(A.equals(B))
  System.out.println("A.equals(B) is TRUE");
else
 System.out.println("A.equals(B) is FALSE");
StringEquality s = new StringEquality();
int x=10;
s.calc(x);
System.out.println("X :"+x);
}

public void calc(int x){
x=20;
}


}