Thursday, 5 November 2015

Collection class: Thread-Safe Collections


Thread-Safe Collections :-  Similar to read-only collections, thread-safe collections are factory decorators that wrap instances of the six core interfaces into thread-safe versions.

  • Collection synchronizedCollection(Collection collection)
  • List synchronizedList(List list)
  • Map synchronizedMap(Map map)
  • Set synchronizedSet(Set set)
  • SortedMap synchronizedSortedMap(SortedMap map)
  • SortedSet synchronizedSortedSet(SortedSet set)


Synchronize the collection immediately after creating it. You also must not retain a reference to the original collection, or else you can access the collection unsynchronized. The simplest way to make sure you don't retain a reference is never to create one:

Set set = Collections.synchronizedSet(new HashSet());

Making a collection unmodifiable also makes a collection thread-safe, as the collection can't be modified. This avoids the synchronization overhead.

public static void main(String[] args) {  
           Set set = Collections.synchronizedSet(new HashSet());  
           synchronized (set) {  
                Iterator itr = set.iterator();  
                while (itr.hasNext()) {  
                     System.out.println(itr.next());  
                }  
           }  
      }  

The iterator itself is not synchronized and iterating through a collection requires multiple calls back into the collection. If you don’t synchronize the getting and use of your iterator, your iteration through the collection will not be atomic and the underlying collection may change.

Enjoy Reading.


Collections class: Read-Only Collections


Read-Only Collections: When working with collection, there are times when you need or at least prefer an unmodifiable access to your collection instance. This may be because you are finished adding and removing elements from the collection but you still want to use it or you need to pass your collection to some method which you don’t necessarily know or you know the method but you don’t want them to change anything. To provide this capability, the Collections class provides six factory methods, one for each of Collection, List, Map, Set, SortedMap, and SortedSet.
         
  •       Collection unmodifiableCollection(Collection collection)
  •       List unmodifiableList(List list)
  •           Map unmodifiableMap(Map map)
  •       Set unmodifiableSet(Set set) 
  •             SortedMap unmodifiableSortedMap(SortedMap map)
  •       SortedSet unmodifiableSortedSet(SortedSet set)



Once you've filled the collection, replace the original reference with the read-only reference.If you don't replace the original reference, then the collection is not read-only, as you can still use the original reference to modify the collection. The following program demonstrates the proper way to make a collection read-only. In addition, it shows what happens when you try to modify a read-only collection.

 import java.util.Collections;  
 import java.util.HashSet;  
 import java.util.Set;  
 public class ReadOnlyCollectionExample {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           Set set = new HashSet();  
           set.add("Cat");  
           set.add("Dog");  
           set.add("Frog");  
           set.add("Elephant");  
           set = Collections.unmodifiableSet(set);  
           set.add("Lion");  
      }  
 }  

Output:-

Exception in thread "main" java.lang.UnsupportedOperationException  
      at java.util.Collections$UnmodifiableCollection.add(Unknown Source)  
      at ReadOnlyCollectionExample.main(ReadOnlyCollectionExample.java:22) 


When the program is run and the last add() operation is attempted on the read-only set, an UnsupportedOperationException is thrown.


Enjoy Reading



Difference between the '&' operator and '&&' operator ?


‘&&’ : - is a Logical AND operator produce a boolean value of true or false based on the logical relationship of its arguments.

For example: - Condition1 && Condition2

If Condition1 is false, then (Condition1 && Condition2) will always be false, that is the reason why this logical operator is also known as Short Circuit Operator because it does not evaluate another condition. If Condition1 is false , then there is no need to evaluate Condtiton2.

If Condition1 is true, then Condition2 is evaluated, if it is true then overall result will be true else it will be false.

public static void main(String[] args) {  
           int a = 12;  
           int b = 6;  
           if (a > 8 && b > 4) {  
                System.out.println("True");  
           } else {  
                System.out.println("False");  
           }  
      }  

Output:-
True because both the condition are true.

‘&’ : - is a Bitwise AND Operator. It produces a one (1) in the output if both the input bits are one. Otherwise it produces zero (0).

For example:-

int a=12; // binary representation of 12 is 1100
int b=6; // binary representation of 6 is 0110
int c=(a & b); // binary representation of (12 & 6) is 0100

The value of c is 4.


Enjoy Reading.


Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees



The rotation can be performed in layers, where you perform a cyclic swap on the edges on each layer. In the first for loop, we rotate the first layer (outermost edges). We rotate the edges by doing a four-way swap first on the corners, then on the element clockwise from the edges, then on the element three steps away.

Once the exterior elements are rotated, we then rotate the interior region’s edges.

Sample Program:-


 /**  
  * @author Dixit  
  *   
  */  
 public class RotateMatrix {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           int m[][] = { { 1, 2 ,3}, { 4, 5 ,6} ,{7,8,9}};  
           int n = 3;  
           for (int i = 0; i < n; i++)  
           {  
                for (int j = 0; j < n; j++) {  
                     System.out.print(m[i][j] + " ");  
                }  
                System.out.println("\n");  
           }  
           rotate(m, n);  
      }  
      public static void rotate(int[][] matrix, int n) {  
           for (int layer = 0; layer < n / 2; ++layer) {  
                int first = layer;  
                int last = n - 1 - layer;  
                for (int i = first; i < last; ++i) {  
                     int offset = i - first;  
                     int top = matrix[first][i]; // save top  
                     // left -> top  
                     matrix[first][i] = matrix[last - offset][first];  
                     // bottom -> left  
                     matrix[last - offset][first] = matrix[last][last - offset];  
                     // right -> bottom  
                     matrix[last][last - offset] = matrix[i][last];  
                     // top -> right  
                     matrix[i][last] = top; // right <- saved top  
                }  
           }  
           System.out.println("Resulting Matrix after 90 degree rotation \n");  
           for (int i = 0; i < n; i++)  
           {  
                for (int j = 0; j < n; j++) {  
                     System.out.print(matrix[i][j] + " ");  
                }  
                System.out.println("\n");  
           }  
      }  
 }  

Output:-


 1 2 3   
 4 5 6   
 7 8 9   
 Resulting Matrix after 90 degree rotation :  
 7 4 1   
 8 5 2   
 9 6 3   


Enjoy Programming.

Wednesday, 4 November 2015

What are Volatile Variables?


A Volatile variable is modified asynchronously by concurrently running threads in a Java application. It is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have its data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Of course, it is likely that volatile variables have a higher access and update overhead than "plain" variables, since the reason threads can have their own copy of data is for better efficiency.


When a field is declared volatile, the compiler and runtime  are  put on  notice  that  this  variable  is shared  and  that  operations  on  it  should  not  be  reordered  with  other memory operations.Volatile variables  are  not  cached  in  registers  or  in  caches  where  they  are  hidden  from  other processors, so a read of a volatile variable always returns the most recent write by any thread.


The most common use for volatile variables is as a completion, interruption, or status flag. Volatile variables can be used for other kinds of state information, but more care is required when attempting this. For example, the semantics of volatile are not strong enough to make the increment operation (count++) atomic, unless you can guarantee that the variable is written only from a single thread.

Note: Volatile variables can only guarantee visibility not atomicity.



Enjoy Reading.                                       

What is Transient Variable?


Transient variable :- In Java, a transient variable is one which would not be saved during serialization. This is mostly the case when a variable is sensitive enough that it should not be saved during serialization, such as a password. Even when such variable is private in the object, once it is serialized it is possible to read it inside a file or over a network. The keyword 'transient' is solution for such variables that are not required to be serialized.

Another way to prevent sensitive part of your object from being serialized is to implement your class as Externalizable. Then nothing is automatically serialized and you can explicitly serialize only the necessary parts inside writeExternal ( ) method.

If you are working with Serializable object , all serialization happens automatically. To control this, you can turn off serialization field-by-field basis using the transient keyword.


For example:- Consider a Login object that keeps information about a particular session .Suppose that, once you verify login , you want to store the data , but without the password .The easiest way to do this is by implementing Serializable and marking the password field as transient.

 import java.io.FileInputStream;  
 import java.io.FileNotFoundException;  
 import java.io.FileOutputStream;  
 import java.io.IOException;  
 import java.io.ObjectInputStream;  
 import java.io.ObjectOutputStream;  
 import java.io.Serializable;  
 import java.util.Date;  
 /**  
  * @author Dixit  
  *  
  */  
 public class Login implements Serializable{  
      private static final long serialVersionUID = 1L;  
      private Date date=new Date();  
      private String userName;  
      private transient String password;  
      Login(String userName,String password)  
      {  
           this.userName=userName;  
           this.password=password;  
      }  
      public String toString()  
      {  
           String pwd=(password==null) ? "(n/a)" : password;  
           return "login info : \n  "+"UserName: "+userName+  
                     "\n Date :"+date+  
                     "\n Password : "+pwd;  
      }  
      /**  
       * @param args  
       * @throws IOException   
       * @throws FileNotFoundException   
       * @throws ClassNotFoundException   
       */  
      public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {  
           Login login=new Login("Ashish", "magic");  
           System.out.println("login: "+login);  
           ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("Login.out"));  
           out.writeObject(login);  
           out.close();  
           try {  
                Thread.sleep(5000);  
           } catch (InterruptedException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
           ObjectInputStream in=new ObjectInputStream(new FileInputStream("Login.out"));  
           System.out.println("Recovering object at : "+new Date());  
           login=(Login) in.readObject();  
           System.out.println("login : "+ login );  
      }  
 }  


You can see that date and username are ordinary and are automatically serialized.However, the password is transient, and so is not stored to disk. also the serialization mechanism makes no attempt to recover it.


Ouput:

 login: login info :   
   UserName: Ashish  
  Date :Wed Nov 04 19:40:10 IST 2015  
  Password : magic  
 Recovering object at : Wed Nov 04 19:40:16 IST 2015  
 login : login info :   
   UserName: Ashish  
  Date :Wed Nov 04 19:40:10 IST 2015  
  Password : (n/a)  

When the object is recovered, the password field is null. Note that the toString ( ) method checks for a null value of password


Enjoy Reading

What is Java Virtual Machine(JVM)?


A Java Virtual Machine is a runtime environment required for execution of a Java application. Every Java application runs inside a runtime instance of some concrete implementation of abstract specifications of JVM. It is JVM which is 'platform independent'.

A runtime instance of the Java virtual machine has a clear mission in life: to run one Java application. When a Java application starts, a runtime instance is born. When the application completes, the instance dies. If you start three Java applications at the same time, on the same computer, using the same concrete implementation, you'll get three Java virtual machine instances. Each Java application runs inside its own Java virtual machine.


A Java virtual machine instance starts running its application by invoking the main() method of some initial class. The main() method must be public, static, return void, and accept one parameter: a String array. Any class with such a main() method can be used as the starting point for a Java application.

 public class SampleProgram {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           System.out.println("Hello World");  
      }       
 }  

The main() method of an application's initial class serves as the starting point for that application's initial thread. Inside the Java virtual machine, threads come in two flavours: daemon and non- daemon. A daemon thread is ordinarily a thread used by the virtual machine itself, such as a thread that performs garbage collection. The application, however, can mark any threads it creates as daemon threads. The initial thread of an application, the one that begins at main() is a non- daemon thread.

A Java application continues to execute (the virtual machine instance continues to live) as long as any non-daemon threads are still running. When all non-daemon threads of a Java application terminate, the virtual machine instance will exit. If permitted by the security manager, the application can also cause its own demise by invoking the exit() method of class Runtime or System.

In the SampleProgram application previous, the main() method doesn't invoke any other threads. After it prints out the command line arguments, main() returns. This terminates the application's only non-daemon thread, which causes the virtual machine instance to exit.


Happy Reading