Volatile in Java

Volatile is a important topic in Java where we will use in Multi-Threading. Volatile keyword will be used in variables and the value will be changed simultaneously by other threads. This makes compiler to read the value from main memory instead of reading from registers. If we say simply value will not be cached in register. And also this makes each thread to get current value of the variable and each thread will not change values unexpectedly.

The main use of Volatile is stops caching the values of variables in registers. When every time value got changes, immediately flushes the value to RAM where other threads can access the updated value directly.

Here we may think of synchronized which will holds a lock for an Object. Where as here its not suitable since we are just reading and updating value when we use Volatile keyword. Volatile can be applied on Object or Primitive types.

Before Java version 1.5 Volatile is not guarantee the atomicity of a 64-bit long load. For example while thread updating some 64 bit long and other reads can get half of old values and half of new values which will reside in improper value. Later from Java 1.5 onwards atomicity of volatile longs is guaranteed on 64-bit hardware also.

Lets see small example of using Volatile keyword which will works along with Multi Threading.



public class MyVolatile {
 
 static volatile long value = 1234567890L;
 
 public static void main(String[] args) {
  new Thread(new IncrementVolatileValue()).start();
  new Thread(new CheckVolatileValue()).start();
 }
 
 static class CheckVolatileValue implements Runnable{
  @Override
  public void run() {   
   for(int i=0;i<10;i++){
    System.out.println("Value Same : "+value);
   }
  }
 }
 
 static class IncrementVolatileValue implements Runnable{
  @Override
  public void run() {
   for(int i=0;i<10;i++){
    System.out.println("Value Incremented : "+value++);
   }
  }
 } 
}



In above example we are incrementing volatile variable in single Thread and by other Thread we are reading the value and printing in loop for checking the change of value. Both the threads are having its own stack and its own copy of variables in its own memory. Volatile keyword is used to say to the JVM "Warning, this variable can be changed by other Thread" so don't cache it, rather read every time from RAM.

So one who programmer need to decide whether he needs to use Volatile or not according to his business logic's.








Vector and ArrayList

 
In this tutorial we will see about Vector and ArrayList in java. Both Vector and ArrayList shares common data structure "Array" internally.

Synchronized and non-synchronized
By default Vector is Synchronized and ArrayList is not Synchronized. By this for Thread safe we can use Vector and for non-thread safe we can use ArrayList. Even ArrayList can be converted to synchronized by Collections class using "Collections.synchronizedList(list)"


Vector in Collection API
Vector defined in first JDK version and later from Java 2 platform Vector got added with Java Collection API. Vector has been retrofitted to implement List Interface.
Once Vector added in Collection API, older methods in Vector class got updated to implement List Interface. Below are the methods got updated from Older version to new methods.


Old Vector MethodsNew Vector Methods
void addElement(Object)boolean add(Object)
boolean removeElement(Object)boolean remove(Object)
void removeElementAt(int)void remove(int)
void insertElementAt(Object, int)void add(index, Object)
Object elementAt(int)Object get(int)
Enumeration elements()Iterator iterator()
ListIterator listIterator()
void copyInto(Object[])Object[] toArray()
void removeAllElements()void clear()
void setElementAt(int)Object set(int, Object)


Where to use Vector and ArrayList
By performance wise ArrayList will be better in case of non synchronized operations and when we need for thread-safe operation then we need to opt for Vector.

Size
Both Vector and ArrayList will re-size dynamically. Vector will double the size of its array automatically when its full, where as ArrayList will increase by half of its array size.









How to read local and remote file in Java?

 
In our earlier tutorial we have seen list of various file operations. In this tutorial we will see how to read a file from local path and from remote server. Reading files from local and from other server through HTTP will vary. Lets see both examples separately.

Reading from local path:


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {
 public static void main(String[] args) {
  
  String fName = "/var/javadiscover/test.txt";
  BufferedReader br = null;
  try {
   FileReader myFile = new FileReader(fName);
   br = new BufferedReader(myFile);
   String line = null;
   while ((line = br.readLine()) != null) {
    System.out.println(line);
   }
  } catch (IOException e) {
   e.printStackTrace();
  
  } finally {
   if (br != null){
    try {
     br.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
}



Reading from remote server through HTTP:


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class ReadFile {
 public static void main(String[] args) {
  InputStreamReader isr  = null;
  BufferedReader buffRead = null;
  
  try{
   String fName = "http://mydomain/test.txt";
   URL url  = new URL(fName);
   URLConnection conn  = url.openConnection();
   isr   = new InputStreamReader(conn.getInputStream());
   buffRead  = new BufferedReader(isr);
   String str = "";
   while ((str = buffRead.readLine()) != null) {
    System.out.println(str);    
   }     
  
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  
  } finally{
   try{
    if(buffRead != null) buffRead.close();
    if(isr != null) isr.close();
   }catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}





Sending email using Java Mail API

In this tutorial we will see how to send email using Java Mail API. We are using Gmail SMTP host for sending email in the below sample code.
Mainly we need 2 jar files to implement Java Mail API. Those jar's are

  • activation-1.0.2.jar
  • mail-1.4.1.jar

Below code have tested along with above jar files. 



import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmailViaGmail {
 public static void main(String[] args) {
  
  // To address
  String to = "to@gmail.com";
  // If any CC email ids
  String cc = "cc@abcmail.com";
  // If any BCC email ids
  String bcc = "bcc@abcmail.com";
  // Email Subject
  String subject = "Java Discover";
  // Email content
  String emailText = "Hi All, Welcome to Java Discover";

  // Sending Email using Gmail SMTP
  sendEmail(to, cc, bcc, subject, emailText);
 }

 public static void sendEmail(String to, String cc, String bcc, String subject, String emailText) {
  
  // From address (Need Gmail ID)
  String from = "from@gmail.com";
  // Password of from address
  String password = "frompassword";
  // Gmail host address
  String host = "smtp.gmail.com";
  
  Properties props = System.getProperties();
  props.put("mail.smtp.host", host);
  props.put("mail.smtp.socketFactory.port", "465");
  props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.port", "465");
  props.put("mail.smtp.user", from);
  props.put("password", password);

  Session session = Session.getDefaultInstance(props, null);

  MimeMessage msg = new MimeMessage(session);
  try {
   msg.setFrom(new InternetAddress(from));
   
   // Adding To address
   msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
   // Adding CC email id
   msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
   // Adding BCC email id
   msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

   msg.setSubject(subject);
   msg.setText(emailText);
   
   Transport transport = session.getTransport("smtp");
   transport.connect(host, from, password);
   transport.sendMessage(msg, msg.getAllRecipients());
   transport.close();
   
   System.out.println("Email sent successfully.....");
   
  } catch (AddressException e) {
   e.printStackTrace();
  } catch (MessagingException e) {
   e.printStackTrace();
  }
 }
}



IMP:
Suppose if you are getting exception while running above like,

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

then valid SSL certificate is missing in the machine which your running. Follow the steps given in link and try again. 







Variable arity method in Java

In this tutorial we will see about Variable Arity method in Java. Variable Arity method question is bit old interview question which used widely before JDK 5. But good to know about this feature in Java and also in Java 7 we have got an update with @SafeVarargs


Its nothing but passing an arbitrary set of arguments to a method. Method can have N no. of arguments but the condition that we can't pass arguments after Arity member. Arity member variable should be always last in the method and it can be primitive or non-primitive data type. Below are the few valid and invalid Variable Arity method definition in Java.


Valid:

public void myMethod(int... arg){....}

public void myMethod(String... arg){....}

public void myMethod(Object... arg){....}

public void myMethod(int a, int b, int... arg){....}


Invalid:

public void myMethod(int... arg, int a){....}


Lets see small sample code how to pass values to Variable Arity method and how to print those values. 


public class ArityMethod {

 public static void myMethod1(int... arg){
  System.out.print("\nmyMethod1 : ");
  for (int i : arg) {
   System.out.print(i+", ");
  }
 }
 
 public static void myMethod2(String... arg){
  System.out.print("\nmyMethod2 : ");
  for (String str : arg) {
   System.out.print(str +" ");
  }
 }
 
 public static void myMethod3(int a, float b, Object... arg){
  
  System.out.print("\nmyMethod3 a value : "+a);
  System.out.print("\nmyMethod3 b value : "+b);
  
  System.out.print("\nmyMethod3 : ");
  for (Object str : arg) {
   System.out.print(str.toString() +" ");
  }
 } 
 
 public static void main(String[] args) {
  myMethod1(1,2,3,4,5);
  myMethod2("hello", "welcome", "to", "Java Discover");
  myMethod3(100,3.0f, "hello", "welcome", "to", "Java Discover");
 }
}


OUTPUT:


myMethod1 : 1, 2, 3, 4, 5, 

myMethod2 : hello welcome to Java Discover 

myMethod3 a value : 100
myMethod3 b value : 3.0
myMethod3 : hello welcome to Java Discover 








How to create user defined immutable class in Java?

In this tutorial we will discuss about how to create immutable class in Java. When we say about immutable we will be remembered about important interview question like What is the difference between String and StringBuilder? We are familiar with String is a immutable and StringBuilder is mutable where values once assigned to String variable cannot the changed. 

Yes correct same way this is also interview question as how to create user defined immutable class in Java? Its simple just by Final modifier we can create our own immutable class. For this we need to make class, methods and member variable in the class as Final. By changing the modifier as final one cannot extend the class or override the methods and even cannot change the value once assigned to member variables. By this we can implement our own immutable class.

In below example code will show how to immutable class in Java.



public final class MyImmutableClass {
 
 private final String empName;
 
 public MyImmutableClass(String empName) {
  this.empName = empName;
 }
 
 public String getEmpName(){
  return this.empName;
 }
}



public class TestMyImmutable {
 public static void main(String[] args) {
  MyImmutableClass obj = new MyImmutableClass("Raj");
  
  /* 
   * Values once assigned cannot to changed by using set methods.
   * Just we can get the value assigned to the variable.
  */
  String empName = obj.getEmpName();
  System.out.println("Emp Name : "+empName);  
 }
}







TreeMap using custom object sorting

 
We know that by default TreeMap will sort the values using key. Suppose if we need to sort the TreeMap using object stored in key part then we need to implement the Comparator interface and we need to @Override compare() method which will sort 2 Objects of key path and will give us the sorted output. 

Below single example will show you how to use custom Object sorting in TreeMap. TreeMap will take "Worker class instance" as key and "String name" as value. Where we need to sort the values using key based on the member variables in the Worker class. 

Class "MyNameComp" which implements the Comparator interface on "Worker" class and used to sort TreeMap based on name or salary. Below example will gives you sort on salary. Suppose if we need output based on name sorted then we need to un-comment "return obj1.getName().compareTo(obj2.getName());"



public class TreeMapUsingObjectSorting {
 
 public static void main(String a[]){
  TreeMap<Worker,String> map = new TreeMap<Worker, String>(new MyNameComp());
  map.put(new Worker("david",5000), "david");
  map.put(new Worker("joy",2000), "joy");
  map.put(new Worker("abel",7000), "abel");
  map.put(new Worker("ruby",9000), "ruby");
  
  for (Map.Entry<Worker, String> entry : map.entrySet()) {
   System.out.println("KEY : "+ entry.getKey() +" \t VALUE : "+entry.getValue());
  }
 }
}




public class Worker{
    
    private String name;
    private int salary;
    
    public Worker(String name, int salary){
        this.name = name;
        this.salary = salary;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }
    /* Called by entry.getKey() 
       Overriding toString() method from super class Object
       Since key is Object we are return our own key value
    */
    public String toString(){
     //return super.toString();
     return "("+this.name+":"+this.salary+")";
    }
}




public class MyNameComp implements Comparator<Worker>{

 @Override
 public int compare(Worker obj1, Worker obj2) {
        
  // Sort TreeMap based on name
  //return obj1.getName().compareTo(obj2.getName());
  
  // Sort TreeMap based on salary
  if(obj1.getSalary() > obj2.getSalary()) return 1;
  else if(obj1.getSalary() < obj2.getSalary()) return -1;
  else return 0;
    } 
}

OUTPUT:


KEY : (joy:2000)   VALUE : joy
KEY : (david:5000)   VALUE : david
KEY : (abel:7000)   VALUE : abel
KEY : (ruby:9000)   VALUE : ruby









How to create Factory Design Pattern in Java

Already we have seen Fully Singleton Design Pattern in our earlier tutorial, now we will see about Factory Design Pattern. 

Factory design pattern is one is the most important and widely used pattern every where in Java. The factory method pattern defines an interface for creating an object, but let sub-classes decide which class to instantiate based on the user requirement. JDK and most of all frameworks like Spring, Struts etc uses factory design pattern internally. Also factory design pattern can be classified into various types like Static Factory, Service Locator Factory and Abstract Factory. 

Lets see one simple example as getting various Computer instances based on the used requirement. As we already explained above we need to have a interface for creating and Object but sub-classes will decide which class need to be instantiated  As same way we are going to have interface called "Computer" and sub-classes like "Desktop", "WorkStation", "Server", "Laptop" and "SuperComputer" will implement "Computer" interface and will their own method definitions. 



public interface Computer {
 public String myComputerType();
}


public class Desktop implements Computer {
 public String myComputerType() {
  return "You have requested for Desktop";
 }
}


public class WorkStation implements Computer {
 public String myComputerType() {
  return "You have requested for WorkStation";
 }
}


public class Server implements Computer {
 public String myComputerType() {
  return "You have requested for Server";
 }
}


public class Laptop implements Computer {
 public String myComputerType() {
  return "You have requested for Laptop";
 }
}


public class SuperComputer implements Computer {
 public String myComputerType() {
  return "You have requested for SuperComputer";
 }
}



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

  // Based on user requirement we will get the Object
  
  Computer obj = FactoryPattern.getComputerType("desktop");
  if(obj != null) 
   System.out.println(obj.myComputerType());
  
  obj = FactoryPattern.getComputerType("laptop");
  if(obj != null) 
   System.out.println(obj.myComputerType());
  
  obj = FactoryPattern.getComputerType("server");
  if(obj != null) 
   System.out.println(obj.myComputerType());
 }
 
 public static Computer getComputerType(String val){
  if(val.equalsIgnoreCase("desktop")) return new PC();
  else if(val.equalsIgnoreCase("workstation")) return new WorkStation();
  else if(val.equalsIgnoreCase("server")) return new Server();
  else if(val.equalsIgnoreCase("laptop")) return new Laptop();
  else if(val.equalsIgnoreCase("super")) return new SuperComputer();
  return null;
 }
}



OUTPUT:


You have requested for Desktop
You have requested for Laptop
You have requested for Server