Saturday, June 27, 2015

Modify an unmodifiable Collection

The Java Collection framework provides an elegant solution to create an unmodifiable Collection like Lists,Sets,Maps from an existing one.Sounds too good.Will it server our purpose?One day was debugging an issue about mutable objects and unmodifiable list.Got a very peculiar behavior.

Lets consider below code snippet.
.
public class UnmodifibleList {
    public static void main(String[] args) {
        String s1=    "Good";  
        String s2=   "Morning";  
        final List modifiableList = new ArrayList();
        modifiableList.add(s1);  
        modifiableList.add(s2);  
        final List unmodifiableList =    Collections.unmodifiableList(modifiableList);
        System.out.println("Before modifying: " + unmodifiableList );
        modifiableList .add("nice");
        modifiableList .add("day"); 
        System.out.println("After modifying: " + unmodifiableList);
   }
}


And the Output as follows:

Before modifying: [Good, Morning]
After modifying: [Good, Morning, nice, day]

Is it seems  strange? Unmodifiable list gets modified after the method call  Collections.unmodifiableList()

What the java doc says:

Returns an unmodifiable view of the specified list. This method allows modules to provide users with "read-only" access to internal lists. Query operations on the returned list "read through" to the specified list, and attempts to modify the returned list, whether direct or via its iterator, result in an UnsupportedOperationException.
The returned list will be serializable if the specified list is serializable. Similarly, the returned list will implement RandomAccess if the specified list does.
Parameters:
list the list for which an unmodifiable view is to be returned.
Returns:
an unmodifiable view of the specified list.
But it does not say if we modify the underlying collection the returned unmodifiable list will also be modified.
Steps to avoid this:
 public class UnmodifibleList {
    public static void main(String[] args) {
        String s1=    "Good";  
        String s2=   "Morning";  
        final List modifiableList = new ArrayList();
        modifiableList.add(s1);  
        modifiableList.add(s2);  
        final List unmodifiableList =      Collections.unmodifiableList(new ArrayList(modifiableList));
        System.out.println("Before modifying: " + unmodifiableList );
        modifiableList .add("nice");
        modifiableList .add("day");  
        System.out.println("After modifying: " + unmodifiableList);
   }


Please look at the line in the above code where  we are calling 
 Collections.unmodifiableList().Here we are creating a brand new ArrayList and passing the original list inside it.


And the Output as follows:

 Before modifying: [Good, Morning]
After modifying: [Good, Morning]


Mutable Object and unmodifiable Collection:
  
Suppose We have a  mutable object and our collection will contain the mutable objects.Please follow the below code snippets to get the better understanding.


public class UnmodifibleMutableList {
    public static void main(String[] args) {
        StringBuffer s1= new StringBuffer("Good");   
        StringBuffer s2= new StringBuffer("Morning");   
        final List modifiableList = new ArrayList();
        modifiableList.add(s1);   
        modifiableList.add(s2);   
        final List unmodifiableList = Collections.unmodifiableList(modifiableList);
        System.out.println("Before modification: " + unmodifiableList );
        s1.replace(0, 3, "ba");
      System.out.println("After modification: " + unmodifiableList);}
}

 

Here notice that  StringBuffer is a mutable class .After calling  Collections.unmodifiableList(); 
we are doing some manipulation with the StringBuffer s1.And that will be reflected in unmodifiable list.

 And the Output as follows:

Before modification: [Good, Morning]
After modification: [bad, Morning]

We have to be conscious that if we modify any of the objects within any of the lists, then all the lists containing the same object will observe the modification.But this is not the case in case of String.As String is immutable and thus cannot be changed once created.

Why do we double check for null instance in Singleton lazy initialization

The algorithm for getting a singleton object of a class by using double checking  for null instances as follows

  1.  public class SigletonTest {
  2.  private static volatile SigletonTest instance = null;
  3.           // private constructor
  4.         private SigletonTest() {
  5.         }
  6.          public static SigletonTest getInstance() {
  7.             if (instance == null) {
  8.                 synchronized (SigletonTest.class) {
  9.                     // Double check
  10.                     if (instance == null) {
  11.                         instance = new SigletonTest();
  12.                     }
  13.                 }
  14.             }
  15.             return instance;
  16.         }
  17.   }

But The question is why the  instance is null checked twice in line no 7 and line no 10.It  seems it is sufficient to check  the instance as null once after synchronization block.The code as follows

public class SigletonTest {
        private static volatile SigletonTest instance = null;

        private SigletonTest() {
        }
         public static SigletonTest getInstance() {
                synchronized (SigletonTest.class) {
                    // single check
                    if (instance == null) {
                        instance = new SigletonTest();
                    }
                }
            return instance;
        }
  }

But In case of the above code ,however, the first call to getInstance() will create the object and all the  threads trying to access it during that time need to be synchronized; after that all calls just get a reference to the member variable. Since synchronizing a method could in some extreme cases decrease performance . The overhead of acquiring and releasing a lock every time this method is called seems unnecessary. Once the initialization has been completed, acquiring and releasing the locks would appear unnecessary.

So the first version is more efficient than second one.