Answer: Oracle provides ports of the Java 2
Platform for Windows 95, Windows 98, Windows NT, Windows 2000,
Solaris-SPARC, Solaris-Intel, and Linux.
Sunday, 24 March 2013
FAQ #1 Why there are no global variables in Java?
Answer: Global variables are globally accessible. Java does not
support globally accessible variables due to following reasons:
- The global variables breaks the referential transparency.
- Global variables creates collisions in namespace.
Singleton Design pattern
Singleton Design patterns is the most simple of all the design patterns in Java. It is also the most frequently asked interview question. So lets go ahead and understand what this design pattern is all about.
Understanding Singleton Design pattern
Singleton as the name suggests there can be only one instance of the class.There are various cases in which we strictly need only one instance of the class. Like for example we Window manager or Print spoolers or filesystems. There are only two main points in the definition of Singleton Design pattern -
- There must be only instance allowed for the class.
- This single instance of the class must be allowed global point of access.
Singleton instance creation
Lets see the code first and then we will try to understand it.
package designPatterns;
public class SingletonPatternDemo {
private static volatile SingletonPatternDemo singleInstance;
private SingletonPatternDemo() {
} // Constructor
public static SingletonPatternDemo getSingleInstance() {
if (singleInstance == null) {
synchronized (SingletonPatternDemo.class) {
if (singleInstance == null) {
singleInstance = new SingletonPatternDemo();
}
}
}
return singleInstance;
}
}
Lets understand the code written above. First of all we have the package and the class declaration. Carefully analyze the next line private static SingletonPatternDemo singleInstance; we have a reference to the object of class SingletonPatternDemo. Note that it is just the reference and we have not created any associated object yet. Another view point can be that we have not yet used any space on heap for any object. This reference is defined as private and static. It is private which mean we cannot directly access it using class objects For Ex. objectName.singleInstance is not allowed. See Access modifiers for more details. Next it is also defined to be static which means the variable belongs to the class and not individual objects. We will get to static keyword in subsequent tutorials but for now you understand it this way - we can access the variable using SingletonPatternDemo.singleInstance i.e className.instanceVariableName. Next we have defined our constructor to be private which means we cannot create any objects by using the new keyword. Only way to create a object is the getSingleInstance() function which is public and static and returns an object of SingletonPatternDemo class. Again static means we can access it using the class Ex. SingletonPatternDemo.getSingleInstance().
Inside the getSingleInstance() method we first check whether instance of the class is already created. If it is already created we return the same instance of the class(as we are allowed to have only one instance of the class) but if there is no instance of the class that is already created we create one and return it.What we have inside the getSingleInstance() method is what we call a Double locking mechanism which i will
explain explicitly.But before that lets understand what synchronized is.
Note :
Also note that the singleton instance is defined to be volatile. This keyword is used for consistency of data across threads. You know that each thread has it's cache where the data reference by the thread is cached and when a thread modifies the data it is still in it's local cache and may not be visible to other threads. To avoid this problem variables can be declared volatile. By declaring a variable as volatile we essentially instruct JVM not to cache the variable in threads cache. Instead all the reads and writes must directly happen in the main memory.Understanding synchronized keyword
This keyword is used when we are dealing with multi-threading. Note that only member functions can be defined as synchronized not the member variables or class itself. When we declare a function to be synchronized it means only one thread can access it at a given point of time. Other than synchronized functions we can have synchronized blocks like the one we have used in the above code. It also means the same - only one thread can access the block at a given point of time. We will cover this in depth when we go through what do we mean by a class being thread-safe and related advanced topics but till then given information should suffice.Next lets understand what is the Double locking mechanism we talked about.
Understanding Double locking mechanism
Lets see the above code again
if (singleInstance == null) {
synchronized (SingletonPatternDemo.class) {
if (singleInstance == null) {
singleInstance = new SingletonPatternDemo();
}
}
This is double locking mechanism. Lets see how this works. Now our aim was to allow only single instance of the class. In multi-threading scenario lets say one thread checks singleInstance finds it to be null and enters the synchronized block. Lets say now there is s context switch or time quantum of the process is over. Next thread takes over, checks if singleInstance is null which is true so even this thread will enter the first if block. Now if we did not have the second check in the synchronized block both thread would go ahead and create an instance of the class. Final result would be we having two instances of our class which is against our Singleton goal. Hence we do a double check once again in the synchronized block. Now since it is in synchronized block only one thread will execute it at a given time and create a instance. When second thread enters this block it will find singleInstance is not null and will not create a new instance. This method is what we call double locking mechanism.
Early and lazy instantiation in singleton pattern
What we did in above code example is lazy instantiation which means we create instance of the class only when it is needed. On the other hand we have Early instantiation which means we create the instance once as soon as the class is loaded and return the same when user need it. Code for Early instantiation is as follows -
package designPatterns;
public class SingletonPatternDemo {
private static SingletonPatternDemo singleInstance = new
SingletonPatternDemo() ;
private SingletonPatternDemo() {
} // Constructor
public static SingletonPatternDemo getSingleInstance() {
return singleInstance;
}
}
So we create instance of the class as soon as class is loaded and just return it when getSingleInstance() is called. This demonstrates Early instantiation.
You must have notice there is no synchronization involved in early initialization. Since Singleton instance is static variable it initialized when class is first loaded into memory so creation of instance is inherently thread-safe.
Note :
You must have notice there is no synchronization involved in early initialization. Since Singleton instance is static variable it initialized when class is first loaded into memory so creation of instance is inherently thread-safe.
Note : In Java you must have used Runtime class quite some time. For example to execute processes from Java - Runtime.getRuntime().exec(). This Runtime class is a Singleton class. There is only one instance of this class per JVM.
yes as you must have notice it, they have use Early initialization ( not lazy init).
Is Singleton instance garbage collected?
Simple plain answer is No!
This was an issue prior to Java 1.2 in which if singleton instance did not have a global reference it would be garbage collected. This defeated the very purpose of singleton as next reference created a new instance of it. But this was fixed in Java 1.2.
New garbage collection model forbids any of the classes that it has loaded from being garbage collected unless all the classes are unreferenced (in which case the class loaded is itself eligible for GC). So unless the class loader is garbage collected the singleton class having static reference to singleton instance is never eligible for garbage collection. So you can be sure that the singleton instance will never be GCed.
When Singleton does not remain Singleton?
There are various ways Singleton property can be violated
- Use reflection to create new instance
- Deserialize and Serialize it again
- Clone it if it implements Cloneable interface.
- Use different class loaders etc.
- Create constructor and throw exception from it
- Implement Serializable and return same instance in readResolve() method
- throw exception from clone method
Related Links
- When is a Singleton not a Singleton(oracle)?
- When is a singleton not a singleton(Java World)?
- Race Condition, Synchronization, atomic operations and Volatile keyword.
- Double-checked locking wiki.
- 10 Singleton Pattern Interview Questions in Java(JavaRevisited)
- Why Enum Singleton are better in Java(JavaRevisited)
Friday, 22 March 2013
Introduction to Design Patterns
What are design patterns?
Programmers usually face some common problems while designing and formulating their programs. Various such problems patterns are identified and their solution is documented which we call design patterns.
Understanding a bit more.
Let us try to understand these design patterns by considering one such design problem.
Single printer in a company
Lets say we have a single printer in the entire company and we have an associated service class which provides printer service to every employee who wishes to print something. Now what sub goals do you have while designing such a service class. You have only one printer and hence you need only one instance of this service class. To achieve this goal you would design your class is such a way that at all time you can have only one instance of the service class. This design pattern is commonly know as Singleton Design pattern. We will look into it in more details but i guess this example will suffice in achieving our goal to understand what these design patterns are all about.
Another example would be your logging class. You want only one instance of logger to be used. So you would prefer using Singleton Pattern.
Important principles in OO Design
- Code for interface not implementation.
- Prefer composition over inheritance.
- Interacting Objects should be loosely couple.
- For each class design aim for low coupling and high cohesion.
- Classes should be open for extension but closed for modification.
These are used in almost all design patterns and form like the basic guidelines. So do keep these in mind. We will use them while discussing about design patterns in detail.
Types of design patterns
Design patterns are categorized into 3 types as follows -
- Creational Design patterns
- Singleton Pattern
- Factory Pattern
- Abstract Factory Pattern
- Builder Pattern
- Prototype Pattern
- Structural Design Patterns
- Adapter Pattern
- Composite Pattern
- Proxy Pattern
- Flyweight Pattern
- Facade Pattern
- Bridge Pattern
- Decorator Pattern
- Behavioral Design Patterns
- Template Method Pattern
- Mediator Pattern
- Chain of Responsibility Pattern
- Observer Pattern
- Strategy Pattern
- Command Pattern
- State Pattern
- Visitor Pattern
- Iterator Pattern
- Memento Pattern
We will see each of them in details in coming tutorials.
Places where design patterns are used in Java
Singleton pattern is used in Java.lang.Runtime , java.util.Calendar, Java.awt.Toolkit, Java.awt.Desktop classes, Factory pattern is used along with various Immutable classes likes Integer e.g. Integer.valueOf and Observer pattern which is used in Swing and many event listener frameworks.Book that I would recommend to study Design Patterns for the beginners is -- "Head first Design Patterns"
Or you can refer to the book written by the Gang of Four themselves -
- "Design Patterns"- Elements of Reusable Object-Oriented Software
![]() |
Related Posts
Sunday, 17 March 2013
Interview Question #5 What is the difference between creating string as new () and as a literal?
This is a very common and most basic interview question asked in Java and yet programmers are not able to explain it properly.
- When we create a String using new operator it is created in heap and not added to String pool whereas String created as literals are created in String pool itself which exist in PermGen area of heap.
- Let us take example to understand this better -
- Case1) Lets create two string literals with different names.
String firstLanguage = "Java";
String secondLanguage = "Java";
Now if we say
if(firstLanguage == secondLanguage )
{
System.out.println("Both references point to same String \n");
}
else
{
System.out.println("Both references point to different Strings \n");
}
Output : Both references point to same String
Explaination : When we create firstLanguage as literal it is created and stored in String pool. Now when we try to create secondLanguage JVM know that such a string already exists in the pool and hence returns reference of the same String and hence the output shown above.
Note : '==' operator will return true only if both references or variables point to same object. In case of String if you really need to check if content of two strings are equal you must use .equals() method. - Case2) Now lets create two String objects and repeat the same exercise we did above.
String firstLanguage = new String("Java");
String secondLanguage = new String("Java");
Now if we say
if(firstLanguage == secondLanguage )
{
System.out.println("Both references point to same String \n");
}
else
{
System.out.println("Both references point to different Strings \n");
}
Output :Both references point to different Strings
Explaination : When we create firstLanguage as new() it is created and stored on the heap as a String object. Similarly when we create secondLanguage as new() it is again cretaed on heap as a different String object. Now since == operator returns true only when both variables point to same object which is not the case we get false.
Note : As mentioned above if you want to check whether contents of firstLanguage object and secondLanguage object are the same that you can use .equals() method. It will return true if content of both String objects are same.
- Case1) Lets create two string literals with different names.
Subscribe to:
Posts (Atom)



