Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Design Pattern (JAVA) : Singleton Pattern -- multithreaded

"In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed." -- wiki

The general idea behind lazy initialization is to preserve memory in a resource constrained runtime environment; however, in some cases, lazy initialization puts system stability at risk due to failed initialization at runtime.

In a multi-threaded Java program, making class constructor private and check for singularity in getInstance() method is insufficient. When two threads invoke the getInstance() method simultaneously, there is still possibility of double instances being created due to interleaving.

1) using early initialization is one option to tackle the problem here. Object is created immediately when class is loaded in JVM. Thus, there is no interleaving issues. However, this could sacrifice some system performance.

2) making getInstance() method synchronized is another option; however, this is not absolutely necessary as the real problem here is that we wish to make the singularity checking portion synchronized only. Creating a synchronized method is an overkill.

3) Since JDK 1.5, we can use the 'enum' keyword to achieve this:

public enum Singleton {

INSTANCE;

//Singleton method
public void someMethod( ) {...}
}
Accessing the enum singleton :
Singleton.INSTANCE.someMethod( );

4) Finally the so called 'double checked locking' method:

public class Singleton {

/** The unique instance **/
private volatile static Singleton instance;

/** The private constructor **/
private Singleton() {}

public static Singleton getInstance() {
if (instance == null) {
synchronized(Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}

return instance;
}
}
[note, the getInstance() method is static method, thus we can not use synchronized(this) statement.

According to the JLS, variables declared volatile are supposed to be sequentially consistent, and therefore, not reordered.

Design Pattern (JAVA) : Singleton Pattern (2)

Singleton with lazy initialization implementation:

final class Singleton {
private static Singleton s;
private static int i;
private Singleton(int x) { i = x; }
public static Singleton getReference() {
s = new Singleton(47);
return s;
}
public int getValue() { return i; }
public void setValue(int x) { i = x; }
}

without lazy initialization:

final class Singleton {
private static Singleton s = new Singleton(47);
private int i;
private Singleton(int x) { i = x; }
public static Singleton getReference() {
return s;
}
public int getValue() { return i; }
public void setValue(int x) { i = x; }
}

So points to note about the singleton pattern:
1) we have to create our own private version of the constructor in order to suppress the default constructor which will be spawn by the compiler.
2) we will create a public getReference() or getInstance() method for client to access the class.
3) we will take extra caution about ensuring class members are static if we wish to implement lazy initialization.
4) we will make the class final in order to prevent client to extend this class and make it clone able accidentally.

Design Pattern (JAVA) : Singleton Pattern

Design patterns summarize proven solutions for typical object oriented programming problems and help to minimize the design effort and eliminate the common mistakes. To understand the necessity of design patterns, we can always look at the problems and begin by tackling it with alternative or brutal force methods, and learn to appreciate the beauty and implications of design patterns.

In many cases, we wish to maintain a single instance of certain class at run time, e.g., we may wish to keep one single connection to a specific database, or we wish to a have a single sequential number generator to avoid duplication.

We can approach the problem in a few ways, and let's analyze them one by one:
a) We can create a 'global' instance of the class, and let all clients use this instance for activities associated with the class. This is fine provided that every client knows about such arrangement and follow it rigidly and diligently. In other words, we are delegating part of the class design responsibility to the 'customers' of the class. This is a sub-optimal solution.

b) We can monitor and control the class instantiation inside the class definition; we could create a static class member which might be boolean or int, and let the class constructor check it before class creation; no class will be created if the check fails. Yes, this sounds logical and feasible. The next thing we need to consider is: what to do if the check fails? How does the client know about the class instantiation failure? Remember that constructor method does NOT return anything as normal method does. A simple solution would be to let the constructor method throw out an exception, and let the client check and handle the exceptions.

Okay, this looks better, but still a little bit troublesome, right?

c) Using static methods.
class PrintSpooler
{
static String str;
//a static class implementation of Singleton pattern
static public void set(String s)
{
str = s;
}

static public void print()
{
System.out.println(str);
}
}
//==============================
public class staticPrint
{
public static void main(String argv[])
{
PrintSpooler ps = new PrintSpooler();
ps.set("orginal?");

PrintSpooler ps2 = new PrintSpooler();
ps2.set("different?");
ps.print();
}
}

d) How about we make the constructor private, and force user to create an instance of the class using another normal member method? Yes, that is the deal.

class iSpooler
{

static boolean instance_flag = false; //true if 1 instance

private iSpooler() { }

//static Instance method returns one instance or null
static public iSpooler Instance()
{
if (! instance_flag)
{
instance_flag = true;
return new iSpooler(); //only callable from within
}
else
return null; //return no further instances
}

public void finalize()
{
instance_flag = false;
}
}

some tricky but fundmental interview questions (Java)

1. checked vs unchecked exceptions

what are the difference?
first, checked exceptions are checked by compiler at compiling time. So programmers are compulsory to handle them; while unchecked exceptions are NOT, and they are reported at runtime. There is actually no way or too expensive to check them at compile time, like array out of bound exception, negative array index, or something very serious, and not remediable.

2. are all methods of parent class inherited?

NO, constructors are of exceptions. They can not be inherited.

3. what is HashCode()?

HashCode() returns the memory address of the owner class. And, Equals() without overriding compares memory address of the two classes.

4.When To Use Interfaces
An interface allows somebody to start from scratch to implement your interface or implement your interface in some other code whose original or primary purpose was quite different from your interface. To them, your interface is only incidental, something that have to add on to the their code to be able to use your package.
When To Use Abstract classes

An abstract class, in contrast, provides more structure. It usually defines some default implementations and provides some tools useful for a full implementation. The catch is, code using it must use your class as the base. That may be highly inconvenient if the other programmers wanting to use your package have already developed their own class hierarchy independently. In Java, a class can inherit from only one base class.