Archive

Archive for October, 2012

Singleton Design Pattern- Java Tech Guy must read!

Singleton design pattern is the first design pattern I learned it many years back. In early days when someone asks me, “do you know any design pattern?” I quickly and promptly answer “I know singleton design pattern” and the question follows, “do you know anything other than singleton” and I stand stumped!

What is Singleton Design Pattern…Have a look on the below image.

Image

A java beginner will know about singleton design pattern. At least he will think that he knows singleton pattern. The definition is even easier than Newton’s third law. Then what is special about the singleton pattern. Is it so simple and straightforward, does it even deserve an article? Do you believe that you know 100% about singleton design pattern? If you believe so and you are a beginner read through the end, there are surprises for you.

There are only two points in the definition of a singleton design pattern,

  1. There should be only one instance allowed for a class and
  2. We should allow global point of access to that single instance.

GOF says, “Ensure a class has only one instance, and provide a global point of access to it.

The key is not the problem and definition. In singleton pattern, trickier part is implementation and management of that single instance. Two points looks very simple, is it so difficult to implement it. Yes it is very difficult to ensure “single instance” rule, given the flexibility of the APIs and many flexible ways available to access an instance. Implementation is very specific to the language you are using. So the security of the single instance is specific to the language used.

Strategy for Singleton instance creation

We suppress the constructor and don’t allow even a single instance for the class. But we declare an attribute for that same class inside and create instance for that and return it. Factory design pattern can be used to create the singleton instance.

public class Singleton {

  private static Singleton singleInstance;

    private Singleton() {}

  public static Singleton getSingleInstance() {

    if (singleInstance == null) {

      synchronized (Singleton.class) {

        if (singleInstance == null) {

          singleInstance = new Singleton();

        }

      }

    }

    return singleInstance;

  }

You need to be careful with multiple threads. If you don’t synchronize the method which is going to return the instance then, there is a possibility of allowing multiple instances in a multi-threaded scenario. Do the synchronization at block level considering the performance issues. In the above example for singleton pattern, you can see that it is thread safe.

But still something is wrong in the above code…keep reading you will get to to know what is wrong in the above code.

Early and lazy instantiation in singleton pattern

The above example code is a sample for lazy instantiation for singleton design pattern. The single instance will be created at the time of first call of the getSingleInstance() method. We can also implement the same singleton design pattern in a simpler way but that would instantiate the single instance early at the time of loading the class. Following example code describes how you can instantiate early. It also takes care of the multithreading scenario.

public class Singleton {

  private static Singleton singleInstance = new Singleton();

  private Singleton() {}

  public  static Singleton getSingleInstance() {

    return singleInstance;

  }

}

Singleton and Serialization

Using serialization, single instance contract of the singleton pattern can be violated. You can serialize and de-serialize and get a new instance of the same singleton class. Using java api, you can implement the below method and override the instance read from the stream. So that you can always ensure that you have single instance.

If you just write…

public class Singleton implements Serializable {

//…

This code becomes ‘broken’ simply by adding one interface implementation. Solution for this is to override the below method:

private Object readResolve() throws ObjectStreamException{

 

}

Case When more than one instance occurs:

Following points we have to take care while creating a singleton pattern:

Case I: Multiple Singletons in Two or More Virtual Machines

When copies of the Singleton class run in multiple VMs, an instance is created for each machine. That each VM can hold its own Singleton might seem obvious but, in distributed systems such as those using EJBs, Jini, and RMI, it’s not so simple. Since intermediate layers can hide the distributed technologies, to tell where an object is really instantiated may be difficult.

Systems based on distributed technologies such as EJB, RMI, and Jini should avoid Singletons that hold state.

Case II: Multiple Singletons Simultaneously Loaded by Different Class Loaders

When two class loaders load a class, you actually have two copies of the class, and each one can have its own Singleton instance. That is particularly relevant in servlets running in certain servlet engines , where each servlet by default uses its own class loader. Two different servlets accessing a joint Singleton will, in fact, get two different objects.

Case III: Singleton Classes Destroyed by Garbage Collection, then Reloaded

When a Singleton class is garbage-collected and then reloaded, a new Singleton instance is created. Any class can be garbage-collected when no other object holds reference to the class or its instances. If no object holds a reference to the Singleton object, then the Singleton class may disappear, later to be reloaded when the Singleton is again needed. In that case, a new Singleton object will be created. Any static or instance fields saved for the object will be lost and reinitialized.

You can avoid class garbage collection in the older VMs by holding a reference to the Singleton class or object in some other object that persists for the program’s life. You can also set your VM to have no class garbage collection

Case IV: Multiple Instances Resulting from Incorrect Synchronization

One of the common Singleton implementations uses lazy initialization of the one instance. That means that the instance is not created when the class loads, but rather when it is first used. (See Listing 2.) A common mistake with that implementation is to neglect synchronization, which can lead to multiple instances of the singleton class.

// error, no synchronization on method
public static Singleton getInstance() {
if (_instance==null) {
_instance = new Singleton();
}

Return  _instance;
}

Two Singletons will be created if the constructor runs and simultaneously another thread call’s the method.

Multiple instances can be created even if you add a synchronized(this) block to the constructor call, as in Listing  below:

// Also an error, synchronization does not prevent
// two calls of constructor.
public static Singleton getInstance() {
if (_instance==null) {
synchronized (Singleton.class) {
_instance = new Singleton();
}
}
return _instance;
}

In the correct solution, seen in Listing below, make getInstance() a synchronized method:

// correct solution
public static synchronized Singleton getInstance() {
// . . .

Double-checked locking is another common solution but, unfortunately, it does not work, see the code below.

// Double-checked locking — don’t use
public static Singleton getInstance() {
if (_instance==null) {
synchronized (Singleton.class) {
if (_instance==null) {
_instance = new Singleton();
}
}
}
}

Case V: Multiple Singletons Arising when Someone has Sub-classed your Singleton

The Singleton Design Pattern is meant to give you control over access to the Singleton class. While I have mostly discussed the control of instantiation, other code can access your class another way: by sub classing it.

The uniqueness of the class cannot be imposed as a compile-time constraint on the subclass unless you use a private constructor. If you want to allow subclassing, for example, you might make the constructor protected. A subclass could then expose a public constructor, allowing anyone to make instances. Since an instance of a subclass is an instance of your superclass, you could find multiple instances of the Singleton.

Case VI: Copies of a Singleton Object that has Undergone Serialization and Deserialization

If you have a serialized object and deserialize it twice in different bjectOutputStreams, or with calls ObjectOutputStream.reset() between deserializations, you get two distinct objects, not two references to the same object.

We already discussed above how to avoid the situation by overriding readResolve();

Case VII: Override the Object clone method to prevent cloning

We can still be able to create a copy of the Object by cloning it using the Object’s clone method. This can be done as shown below

SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone();

This again violates the Singleton Design Pattern’s objective. So to deal with this we need to override the Object’s clone method which throws a CloneNotSupportedException exception.

public Object clone() throws CloneNotSupportedException {

throw new CloneNotSupportedException();

}

The below program shows the final Implementation of Singleton Design Pattern in java, by using all the steps mentioned above.

class SingletonClass {

private static SingletonClass singletonObject;

/** A private Constructor prevents any other class from instantiating.

*/ private SingletonClass() {

// Optional Code }

public static synchronized SingletonClass getSingletonObject() {

if (singletonObject == null) {

singletonObject = new SingletonClass();

} return singletonObject;

}

public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException();

}

}

When to use Singleton class?

There is no straightforward answer to this question. A scenario which is acceptable to some will be unacceptable to others.

However, it is commonly accepted that the singleton can yield best results in a situation where various parts of an application concurrently try to access a shared resource. An example of a shared resource would be Logger, Print Spooler, etc.

The following points are suggested to be considered while designing a singleton class:

  1. Singleton classes must be memory-leak free. The instance of the singleton class is to be created once and it remains for the lifetime of the application.
  2. A real singleton class is not easily extensible.
  3. Derive the singleton class from an interface. This helps while doing unit testing (using Dependency Injection).

Don’t forget to add your comments.

 

Common Interview Questions

October 14, 2012 1 comment

After a long time thought off to blog something about the common Interview questions and finally am writing here…

Please review these typical general interview questions and think about how you would answer them. Read the questions listed; you will also find some strategy suggestions with it.

1. Tell me about yourself:
The most often asked question in interviews. You need to have a short statement prepared in your mind. Be careful that it does not sound rehearsed. Limit it to work-related items unless instructed otherwise. Talk about things you have done and jobs you have held that relate to the position you are interviewing for. Start with the item farthest back and work up to the present.

2. Why did you leave your last job?
Stay positive regardless of the circumstances. Never refer to a major problem with management and never speak ill of supervisors, co-workers or the organization. If you do, you will be the one looking bad. Keep smiling and talk about leaving for a positive reason such as an opportunity, a chance to do something special or other forward-looking reasons.

3. What experience do you have in this field?
Speak about specifics that relate to the position you are applying for. If you do not have specific experience, get as close as you can.

4. Do you consider yourself successful?
You should always answer yes and briefly explain why. A good explanation is that you have set goals, and you have met some and are on track to achieve the others.

5. What do co-workers say about you?
Be prepared with a quote or two from co-workers. Either a specific statement or a paraphrase will work. Jill Clark, a co-worker at Smith Company, always said I was the hardest workers she had ever known. It is as powerful as Jill having said it at the interview herself.

6. What do you know about this organization?
This question is one reason to do some research on the organization before the interview. Find out where they have been and where they are going. What are the current issues and who are the major players?

7. What have you done to improve your knowledge in the last year?
Try to include improvement activities that relate to the job. A wide variety of activities can be mentioned as positive self-improvement. Have some good ones handy to mention..

8. Are you applying for other jobs?
Be honest but do not spend a lot of time in this area. Keep the focus on this job and what you can do for this organization. Anything else is a distraction.

9. Why do you want to work for this organization?
This may take some thought and certainly, should be based on the research you have done on the organization. Sincerity is extremely important here and will easily be sensed. Relate it to your long-term career goals.

10. Do you know anyone who works for us?
Be aware of the policy on relatives working for the organization. This can affect your answer even though they asked about friends not relatives. Be careful to mention a friend only if they are well thought of.

11. What kind of salary do you need?
A loaded question. A nasty little game that you will probably lose if you answer first. So, do not answer it. Instead, say something like, That’s a tough question. Can you tell me the range for this position? In most cases, the interviewer, taken off guard, will tell you. If not, say that it can depend on the details of the job. Then give a wide range.

12. Are you a team player?
You are, of course, a team player. Be sure to have examples ready. Specifics that show you often perform for the good of the team rather than for yourself are good evidence of your team attitude. Do not brag, just say it in a matter-of-fact tone. This is a key point.

13. How long would you expect to work for us if hired?
Specifics here are not good. Something like this should work: I’d like it to be a long time. Or As long as we both feel I’m doing a good job.

14. Have you ever had to fire anyone? How did you feel about that?
This is serious. Do not make light of it or in any way seem like you like to fire people. At the same time, you will do it when it is the right thing to do. When it comes to the organization versus the individual who has created a harmful situation, you will protect the organization. Remember firing is not the same as layoff or reduction in force.

15. What is your philosophy towards work?
The interviewer is not looking for a long or flowery dissertation here. Do you have strong feelings that the job gets done? Yes. That’s the type of answer that works best here. Short and positive, showing a benefit to the organization.

16. If you had enough money to retire right now, would you?
Answer yes if you would. But since you need to work, this is the type of work you prefer. Do not say yes if you do not mean it.

17. Have you ever been asked to leave a position?
If you have not, say no. If you have, be honest, brief and avoid saying negative things about the people or organization involved.

18. Explain how you would be an asset to this organization
You should be anxious for this question. It gives you a chance to highlight your best points as they relate to the position being discussed. Give a little advance thought to this relationship.

19. Why should we hire you?
Point out how your assets meet what the organization needs. Do not mention any other candidates to make a comparison.

20. Tell me about a suggestion you have made
Have a good one ready. Be sure and use a suggestion that was accepted and was then considered successful. One related to the type of work applied for is a real plus

21. What irritates you about co-workers?
This is a trap question. Think real hard but fail to come up with anything that irritates you. A short statement that you seem to get along with folks is great.

22. What is your greatest strength?
Numerous answers are good, just stay positive. A few good examples: Your ability to prioritize, Your problem-solving skills, Your ability to work under pressure, Your ability to focus on projects, Your professional expertise, Your leadership skills, Your positive attitude .

23. Tell me about your dream job.
Stay away from a specific job. You cannot win. If you say the job you are contending for is it, you strain credibility. If you say another job is it, you plant the suspicion that you will be dissatisfied with this position if hired. The best is to stay genetic and say something like: A job where I love the work, like the people, can contribute and can’t wait to get to work.

24. Why do you think you would do well at this job?
Give several reasons and include skills, experience and interest.

25. What are you looking for in a job?
See answer # 23

26. What kind of person would you refuse to work with?
Do not be trivial. It would take disloyalty to the organization, violence or lawbreaking to get you to object. Minor objections will label you as a whiner.

27. What is more important to you: the money or the work?
Money is always important, but the work is the most important. There is no better answer.

28. What would your previous supervisor say your strongest point is?
There are numerous good possibilities: Loyalty, Energy, Positive attitude, Leadership, Team player, Expertise, Initiative, Patience, Hard work, Creativity, Problem solver

29. Tell me about a problem you had with a supervisor
Biggest trap of all. This is a test to see if you will speak ill of your boss. If you fall for it and tell about a problem with a former boss, you may well below the interview right there. Stay positive and develop a poor memory about any trouble with a supervisor.

30. What has disappointed you about a job?
Don’t get trivial or negative. Safe areas are few but can include: Not enough of a challenge. You were laid off in a reduction Company did not win a contract, which would have given you more responsibility.

31. Tell me about your ability to work under pressure.
You may say that you thrive under certain types of pressure. Give an example that relates to the type of position applied for.

32. Do your skills match this job or another job more closely?
Probably this one. Do not give fuel to the suspicion that you may want another job more than this one.

33. What motivates you to do your best on the job?
This is a personal trait that only you can say, but good examples are: Challenge, Achievement, Recognition

34. Are you willing to work overtime? Nights? Weekends?
This is up to you. Be totally honest.

35. How would you know you were successful on this job?
Several ways are good measures: You set high standards for yourself and meet them. Your outcomes are a success.Your boss tell you that you are successful

36. Would you be willing to relocate if required?
You should be clear on this with your family prior to the interview if you think there is a chance it may come up. Do not say yes just to get the job if the real answer is no. This can create a lot of problems later on in your career. Be honest at this point and save yourself future grief.

37. Are you willing to put the interests of the organization ahead of your own?
This is a straight loyalty and dedication question. Do not worry about the deep ethical and philosophical implications. Just say yes.

38. Describe your management style.
Try to avoid labels. Some of the more common labels, like progressive, salesman or consensus, can have several meanings or descriptions depending on which management expert you listen to. The situational style is safe, because it says you will manage according to the situation, instead of one size fits all.

39. What have you learned from mistakes on the job?
Here you have to come up with something or you strain credibility. Make it small, well intentioned mistake with a positive lesson learned. An example would be working too far ahead of colleagues on a project and thus throwing coordination off.

40. Do you have any blind spots?
Trick question. If you know about blind spots, they are no longer blind spots. Do not reveal any personal areas of concern here. Let them do their own discovery on your bad points. Do not hand it to them.

41. If you were hiring a person for this job, what would you look for?
Be careful to mention traits that are needed and that you have.

42. Do you think you are overqualified for this position?
Regardless of your qualifications, state that you are very well qualified for the position.

43. How do you propose to compensate for your lack of experience?
First, if you have experience that the interviewer does not know about, bring that up: Then, point out (if true) that you are a hard working quick learner.

44. What qualities do you look for in a boss?
Be generic and positive. Safe qualities are knowledgeable, a sense of humor, fair, loyal to subordinates and holder of high standards. All bosses think they have these traits.

45. Tell me about a time when you helped resolve a dispute between others.
Pick a specific incident. Concentrate on your problem solving technique and not the dispute you settled.

46. What position do you prefer on a team working on a project?
Be honest. If you are comfortable in different roles, point that out.

47. Describe your work ethic.
Emphasize benefits to the organization. Things like, determination to get the job done and work hard but enjoy your work are good.

48. What has been your biggest professional disappointment?
Be sure that you refer to something that was beyond your control. Show acceptance and no negative feelings.

49. Tell me about the most fun you have had on the job.
Talk about having fun by accomplishing something for the organization.

50. Do you have any questions for me?
Always have some questions prepared. Questions prepared where you will be an asset to the organization are good. How soon will I be able to be productive? and What type of projects will I be able to assist on? are examples.

All The Best

All The Best

String Literals and String Pool

The String Pool:
Sun made an optimization that is rather confusing to many new Java programmers called the String Pool. It allows for Strings, which are one of the most used Objects to optimize themselves and save space. An important point to make is that the String Pool only applies to String literals, meaning their value was assigned, not constructed using a String constructor. Let me start off with an example:

public class Main {

public static void main(String[] args) {
String s1 = “abc”;
String s2 = “abc”;

System.out.println(“s1 = ” + s1);
System.out.println(“s2 = ” + s2);
System.out.println(“s1 == s2? ” + (s1 == s2));
System.out.println(“s1.equals(s2)? ” + (s1.equals(s2)));

}

}
If you run this program, you get this:

s1 = abc
s2 = abc
s1 == s2? true
s1.equals(s2)? true

Most beginners are told to only compare strings using the .equals() method, simply because it is safer for beginners, however, what is confusing about my program above is that the == operator actually said those two were the same memory location too. How is s1 == s2? I clearly defined 2 different variables! An important concept about Java that you may not know is that symbols (variable names) aren’t actually the object that they are defined as. They actually hold a reference to the spot in memory where the actual object is kept. Since Strings are SO commonly used, Strings literals that are the same are given the same address so that it saves memory and doesn’t have to make another. Think about it as if there can only be one of each String in there and anything matching is assigned a reference to that String. However, once all references are gone, then the object is erased. However, once they change, the addresses are different:

public class Main {

public static void main(String[] args) {
String s1 = “abc”;
String s2 = “abc”;

System.out.println(“s1 = ” + s1);
System.out.println(“s2 = ” + s2);
System.out.println(“s1 == s2? ” + (s1 == s2));
System.out.println(“s1.equals(s2)? ” + (s1.equals(s2)));

s2 += “abc”;

System.out.println(“s1 = ” + s1);
System.out.println(“s2 = ” + s2);
System.out.println(“s1 == s2? ” + (s1 == s2));
System.out.println(“s1.equals(s2)? ” + (s1.equals(s2)));

}

}

This outputs this:

s1 = abc
s2 = abc
s1 == s2? true
s1.equals(s2)? true
s1 = abc
s2 = abcabc
s1 == s2? false
s1.equals(s2)? false

HOWEVER, if for any reason you want the variables to not occupy the same location in memory, there are two ways to do this. First, you can use the String constructor, since those are not put into the pool:

public class Main {

public static void main(String[] args) {
String s1 = “abc”;
String s2 = new String(“abc”);

System.out.println(“s1 = ” + s1);
System.out.println(“s2 = ” + s2);
System.out.println(“s1 == s2? ” + (s1 == s2));
System.out.println(“s1.equals(s2)? ” + (s1.equals(s2)));

}

}

This code says that == is false. And just to prove a point, let’s make both of them use constructors:

public class Main {

public static void main(String[] args) {
String s1 = new String(“abc”);
String s2 = new String(“abc”);

System.out.println(“s1 = ” + s1);
System.out.println(“s2 = ” + s2);
System.out.println(“s1 == s2? ” + (s1 == s2));
System.out.println(“s1.equals(s2)? ” + (s1.equals(s2)));

}

}

That code yields:

s1 = abc
s2 = abc
s1 == s2? false
s1.equals(s2)? true

OR you can assign them in different steps, forcing it to occupy a different address for each addition. (First they are the same, then s1 is moved to another spot to add on the “c” and the same for s2):

public class Main {

public static void main(String[] args) {
String s1 = “ab”;
String s2 = “a”;
s1 += “c”;
s2 += “bc”;

System.out.println(“s1 = ” + s1);
System.out.println(“s2 = ” + s2);
System.out.println(“s1 == s2? ” + (s1 == s2));
System.out.println(“s1.equals(s2)? ” + (s1.equals(s2)));

}

}

Output:

s1 = abc
s2 = abc
s1 == s2? false
s1.equals(s2)? true

However, there is a way for a literal and a constructor value (assuming value is the same) to == each other. The magic of intern() method of the String class. What this method does is it looks at its value, and if it matches a value ALREADY IN the String pool, it returns a reference to the object in the pool, else it adds itself to the pool. Observe:

public class Main {

public static void main(String[] args) {
String s1 = “abc”;
String s2 = new String(“abc”);
s2 = s2.intern();

System.out.println(“s1 = ” + s1);
System.out.println(“s2 = ” + s2);
System.out.println(“s1 == s2? ” + (s1 == s2));
System.out.println(“s1.equals(s2)? ” + (s1.equals(s2)));

}

}

This returns:

s1 = abc
s2 = abc
s1 == s2? true
s1.equals(s2)? true

Cool huh? This happens because s1 is ASSIGNED to “abc” and is added to the pool. s2, however, is constructed to “abc”, but not added to the pool. But the intern() method sees that the VALUE “abc” is already in the pool and thus returns the reference to s1. I got a challenge problem for you now. Will s1 == s2 in the following code?

public class Main {

public static void main(String[] args) {
String s1 = new String(“abc”);
String s2 = new String(“abc”);
s2 = s2.intern();

System.out.println(“s1 = ” + s1);
System.out.println(“s2 = ” + s2);
System.out.println(“s1 == s2? ” + (s1 == s2));
System.out.println(“s1.equals(s2)? ” + (s1.equals(s2)));

}

}

… The answer is no. The intern() method is called, but neither s1 nor s2 is in the pool so all the intern() method does is add it to the pool. To make THESE ==, you must call intern() twice so that there is already a reference in the pool (from the first call).

public class Main {

public static void main(String[] args) {
String s1 = new String(“abc”);
String s2 = new String(“abc”);
s2 = s2.intern();
s1 = s1.intern();

System.out.println(“s1 = ” + s1);
System.out.println(“s2 = ” + s2);
System.out.println(“s1 == s2? ” + (s1 == s2));
System.out.println(“s1.equals(s2)? ” + (s1.equals(s2)));

}

}

This returns:

s1 = abc
s2 = abc
s1 == s2? true
s1.equals(s2)? true

That’s all I have on that for now! I encourage you all to experiment with this, as I’m sure there is SOMETHING that I missed in this huge concept. Happy reading.

Categories: Uncategorized