Search This Blog

Monday, May 14, 2018

How Collections.synchronized works in Java

Synchronised collections are the "thread safe" Collections introduced by earlier Java versions(1.2 thru 1.4), which addresses synchronization by making all the public methods of the collection "Synchronized". 

Any compound operation needs to be supported with "client side Locking"

Example for a compound operation is any operation , that has "check and do", say "AddLast" element, which would first check/aquire the Size and then add the last element.
Even though both the operations, are protected by synchronised keyword, in between these operations, there is a possibility of a add/Remove operation, which can alter the size.

A remove operation in between Getsize() and Add()  can hence cause AddLast () to throw "OutofBound" Exception,
A add operation in between Getsize() and Add() can cause AddLast to add an entry before Last, and hence not performing the intended function

Java guards the collections like - 

        public boolean add(E e) {
            synchronized (mutex) {return c.add(e);}
        }

        public boolean remove(Object o) {
            synchronized (mutex) {return c.remove(o);}
        }


        public boolean containsAll(Collection<?> coll) {
            synchronized (mutex) {return c.containsAll(coll);}
        }

        public boolean addAll(Collection<? extends E> coll) {
            synchronized (mutex) {return c.addAll(coll);}
        }

        public boolean removeAll(Collection<?> coll) {
            synchronized (mutex) {return c.removeAll(coll);}
        }

        public boolean retainAll(Collection<?> coll) {
            synchronized (mutex) {return c.retainAll(coll);}
        }

        public void clear() {
            synchronized (mutex) {c.clear();}
        }

I love to discuss if you have any questions about the above post.

How Collections.unmodifiable works in Java

Some of the interviewers ask this question generally and if you used this utility method then you must know about the internal working of it as well.
So lets discuss how it works internally -
An unmodifiable collection is often a wrapper around a modifiable collection which other code may still have access to. So while you can't make any changes to it if you only have a reference to the unmodifiable collection, you can't rely on the contents not changing.
An immutable collection guarantees that nothing can change the collection any more. If it wraps a modifiable collection, it makes sure that no other code has access to that modifiable collection. Note that although no code can change which objects the collection contains references to, the objects themselves may still be mutable - creating an immutable collection of StringBuilder doesn't somehow "freeze" those objects.
Basically, the difference is about whether other code may be able to change the collection behind your back.
Make sure to mark all the methods which are responsible for modifying the collection structure , they must be guarded like -

        public boolean add(E e) {
            throw new UnsupportedOperationException();
        }

        public boolean remove(Object o) {
            throw new UnsupportedOperationException();
        }

        public boolean addAll(Collection<? extends E> coll) {
            throw new UnsupportedOperationException();
        }

        public boolean removeAll(Collection<?> coll) {
            throw new UnsupportedOperationException();
        }

        public boolean retainAll(Collection<?> coll) {
            throw new UnsupportedOperationException();
        }

        public void clear() {
            throw new UnsupportedOperationException();
        }

Saturday, May 12, 2018

Why We use SerialVersionUID ?

In java all the Serializable classes are automatically given a unique identifier if you explicitly not defined. The unique identifier of the class is maintained by serialVersionUID field. So the serialVersionUID is a unique identifier of the serializable classes, and the value of serialVersionUID is used at the time of de-serialization to verify that the sender and receiver of a serialized object have loaded a class for that object that are compatible with respect to serialization.

The default value of serialVersionUID is computed based on your class's field, method, interfaces etc. It may be vary from environment to environment or compiler to compiler. That's why you always need to define explicitly the value of serialVersionUID. It's better to redefine the value of serialVersionUID each time you changed the structure of your class.

Q&A Section

Just made this page for Question and Answer section, so lets have a good and healthy discussion here. The idea is to have more and more insights of the java technology.

As per my understanding , having a good discussion on the topics or questions we can get more insights . 

Visual VM

Recently I got a task to measure the performance of a Java Application and then started looking out lot more tools available on internet for free . There are few performance measurement tool like VisualVm, JConsole(taking heap dump and then analyzing dump using MAT) , jstat, jhat etc. So considering the above all I thought to share visual VM uses and getting handy with it.

What is VisualVM

It is a tool automatically available after JDK is installed. The executable file could be found on your <JDK installation folder>/bin as displayed below.
/wp-content/uploads/2015/09/clipboard1_792507.png
In order to measure the performance of your application, it is necessary for the application to be recognized by VisualVM first.
There is a plugin named “VisualVM launcher for Eclipse” which can help us about it.

Install and configure VisualVM launcher

1. download the zip from http://visualvm.java.net/eclipse-launcher.html. Unzip the file and put it to the plugin folder of your Eclipse installation folder. In my laptop it looks like below. There should be a site.xml inside the unzipped folder.
/wp-content/uploads/2015/09/clipboard2_792508.png
2. In Eclipse, choose menu “Help->Install New Software”, click “Local”, add locate the folder to the one you finish in step1.
/wp-content/uploads/2015/09/clipboard3_792509.png
Then the local downloaded plugin is successfully parsed and ready for install.
/wp-content/uploads/2015/09/clipboard4_792510.png
finish the installation.
/wp-content/uploads/2015/09/clipboard5_792511.png
3. Restart Eclipse, then you can find a new option via the path below. Configure two paths accordingly.
/wp-content/uploads/2015/09/clipboard6_792512.png
For “JDK Home”, if you configure the JRE path by mistake, later when you try to measure your application, the VisualVM will fail to load with the following error message:
/wp-content/uploads/2015/09/clipboard7_792513.png
Now the plugin is ready to use.

Do performance measurement

1. Select your Java project, choose context menu “Run as”->”Run configuration”, create a new Application configuration by specifying VisualVM launcher as its launcher, instead of the default Eclipse JDT launcher.
/wp-content/uploads/2015/09/clipboard8_792514.png
2. For example I have a Java application which sorts an array by QuickSort algorithm written by myself and I would like to get its performance data, then I set a breakpoint on line 57, before my main logic is executed.
Then launch the application in debugging mode with the application configuration created in previous step.
Afterwards VisualVM will automatically be launched and successfully recognize the execution of my application.
Click Profiler tab:
/wp-content/uploads/2015/09/clipboard9_792515.png
Current status: profiling inactive. Click CPU button:
/wp-content/uploads/2015/09/clipboard10_792516.png
Now profiling is activated:
/wp-content/uploads/2015/09/clipboard11_792517.png
3. Go back to Eclipse and click F8 to finish execution. Once finished, VisualVM will immediately capture this event and notify you. Just click Yes to get performance result.
/wp-content/uploads/2015/09/clipboard12_792518.png
The result is displayed as below:
/wp-content/uploads/2015/09/clipboard13_792519.png