Tuesday 30 October 2012

Access specifier in Java : A love story

Access specifier in java is an important topic since it controls the flow of application. Also we can't write a simple application without any one of the four access specifier. So now you understand the importance of access specifiers.

So let's look into different access specifiers in java. We have public, protected, default and private access specifiers in java. Where exactly we can use this in a java application?

Public - No doubt in this, if we need to make instance or method accessible to entire outside world make it as public.

Private - This is also simple, If we want to make instance or method accessible only to the containing class make it as private.

Protected - This is somewhat confusing, where exactly we have to use it? If we need to share some instance or method to all the child classes with in the same package or different package mark it as protected.

Default -Hmm...So what is this?  If we need to share some instance or method to all the child classes with in the same package mark it as default. Here if any try to access default members from outside the package will result in compilation error.

Order of accessibility

private<default<protected<public

So here is a story to remember this stuff:

Suppose you are belongs to a big family. Also you have a secret love (We can say it as an instance variable).

If you want to keep your love as public makes it as a public love so that everyone knows about it.

If you want to keep your love as a secret for yourself, make it as a private love so that only you know about it.

If you want to keep your love with in your close family mark is as a default love (Note: here close family means any family which has a close relationship with your family....in java term it is subclass under the same package).

If you want to keep your love with in your big family mark is as a protected love (Note: here big family means any family which has a relationship with your family and located anywhere....in java term subclass under different package).

Hope this Helps!!!

Wednesday 10 October 2012

Java puzzle 1

Hi Guys,

While going through some websites, I have found this interesting java puzzle and thought of sharing it with you!! J

Problem: You have to print “I am added 30 Students to a LKGClass of strength 10!!” by running the Tester class.

Restrictions: You are not allowed to modify the LKGClass but allowed to modify the Tester class. You are allowed to use any java programming tactics.

public class Student{
}

import java.util.HashSet;
import java.util.Set;

public class LKGStudent{

private static final int STRENGTH=10;
private Set< Student > student=new HashSet< Student >();

public synchronized void addStudent(Student s){
                if(student.size()==STRENGTH){
                                throw new IllegalStateException("I'm full");
    }
                else{
                student.add(s);
                }
}

public synchronized void solvedPuzzle(){
                if(student.size()==30){
                //The goal of this puzzle is to reach this line!
                System.out.println("I am added 30 Students to a LKGClass of strength 10!!");
                }             
}
}

public class Tester{

//This tester is a starting point and doesn’t print "I am added 30 Students to a LKGClass of strength 10!!" //try by modifying this class!!

public static void main(String [] args){

LKGStudent lkg=new LKGStudent();

for(int i=0;i<20;i++){
                lkg.addStudent(new Student());
}
lkg.solvedPuzzle();

}

}

Hope this Helps!!

Friday 5 October 2012

Java Volatile Variable

Java Volatile Variable
Most of the time we used to hear one term called volatile variable. What is the difference between a normal variable and a variable varaible?
For understanding the concept of volatile variable, it is recommended that we have some basic idea of locking and visibility.
Locking and Visibility: Imagine a thread called Thread A enters into a synchronized block, it acquires a lock on the object also simultaneously one more thread called Thread B try to read the same object state, Can Thread B read the instance variables or will it get new value which is updated by thread A. The answer is Thread B will get all the values seen by Thread A while entering into the synchronized block. Synchronization is not only responsible for locking the object but also for memory visibility. When Thread A leaves a synchronized block, it will update all state variables to the memory.  Since processor has lots of registers and caches, the state of a variable may not be updated all the time to the memory. Synchronization allows you to forcefully updating the sate of a variable to the memory before leaving the synchronization block.
Volatile variable: Since normal variable may not give the up-to-date value of a variable in a concurrent thread scenario, we have to use synchronization for getting the up-to-date value. There is another way to get the up-to-date value of a variable by declaring it as volatile variable. If we declare a variable as volatile, compiler and runtime will take it with special care and never store these variables in caches. So a read to a volatile variable always give a value which is most recent write by another thread.
Locking can guarantee both visibilty and atomicity, but volatile variable can guarantee only visibility. So remember it is not recommended to relay heavily on volatile variables.
Hope this Helps!!

Encapsulation and Abstraction, a real time example!

Most of the time we used to hear these two main OOP's concepts i.e. Abstraction and Encapsulation. Whenever I read about this two main OOP's concepts in any of the book or blog, I used to get some predefined definitions and failed to get the real meaning. But recently I got a very good real time example and I think this will help you guys.

Encapsulation definition from Wiki: "Encapsulation is to hide the variables or something inside a class, preventing unauthorized parties to use. So the public methods like getter and setter access it and the other classes call these methods for accessing".
Abstraction definition from Wiki:"Abstraction involves the facility to define objects that represent abstract "actors" that can perform work, report on and change their state, and "communicate" with other objects in the system."
So after reading this wiki, can you make out something? I think the answer will be a big NO!!(If Yes, please close this window, because you are already a Geek :-P )
Consider the below real time example:
Let’s imagine you own a Ferrari Car and you are the only one knows how to drive it in your family. One day a terrible breakdown happened to your car and you bring one mechanic to home and he checked it. But he is unable to repair it. So you contacted Ferrari company and some chief mechanic came to your home and repaired it(Since your car is under warranty, your pocket is still big :-))This is a real time example for the above mentioned OOP's concepts, How?
Encapsulation:
As a driver you know how to start the car by pressing the start button and internal details of the starting operations are hidden from you. So the entire starting process is hidden from you otherwise we can tell starting operation is encapsulated from you.
OR
The driving wheel is encapsulated the process of rotating the wheel from you.
Abstraction:
Before mentioning anything about abstraction, we can take three different users here (I am calling them as entity)
1) You 2) Local Mechanic 3) Expert
You Entity: Since you know only to start the car by pressing a button and all other operations behind the scene are abstracted from you.
Local Mechanic Entity: Our local mechanic knows some of the implementation of starting the car, i.e. he can open car's bonnet and check the battery cable or chock etc. So in short Local Mechanic Entity knows some of the implementations of the car.
Expert Entity: Since our expert (Designer of the car) mechanic knows all the operations of our car, he can repair it very quickly. So in short Expert Entity knows all the implementations of the car.
The car's operation is completely abstracted from you and it is partially implemented to Local Mechanic Entity and fully implemented to Expert Entity. So you are an abstract class having only abstract methods, Local Mechanic Entity has extended You(Since he is also an ordinary user) and he implemented some of the methods and last our expert Entity extending Local Mechanic and implementing all the methods.
Also in terms of complexity "Whenever abstraction decreases, complexity increases"(Since our Expert Entity has very less abstraction, his complexity of work also increases)
In Java, garbage collection is also a best example for explaining abstraction.
As a java programmer GC is abstracted completely from you and as a language designer, one needs to understand the internal details of the JVM.
Hope this Helps!!

Atomicity in Java's double and long !

 Everybody knows that java has lots of primitive data types like byte, int, float, long, double, etc.

 Can we use these primitive variables in a multi threaded programming environment? The answer is 'YES' provided you have knowledge on atomicity and synchronization.

Atomicity is a very simple concept. Consider you have an integer variable named counter and you want to increment its value by one. So normal way to achieve this by using '++count' and this will work perfectly fine in a single threaded environment. But if you observe closely this '++count' operation, we can see that it is a compound operation. '++ count' is composed of three independent operations i.e. Read (The variable is read from the memory) + Modify (Increment the variable by 1) + Write (Update the new value to the memory location). So if you want to increment count by one in a multithreaded environment, we have to make these three operations to be atomic (occurs in one shot). How can we achieve this? Very simple surround the '++count' operation in a synchronized block or instead of int data type use AtomicInteger from java.util.concurrent.atomic package.

 Here is the key point of this article. Almost all the primitive variables Read and Write operations are atomic except for long and double. Since long and double are of 64 bit size, JVM is permitted to treat a 64 bit read or write as two separate operations i.e. while reading a long or double, JVM first read the first 32 bit and then read the second 32 bit and this constitute two distinct atomic operations for a read operation. Similar is the case of a write operation.

 So in conclusion, it is not safe to use mutable long and double variables in a multi threaded program without proper synchronization methods.

Hope this Helps!!