JavaZone X : The Streaming


Advertisements
Video

Tell your name?


Recently I came across the following code snippet – wanted to share with everyone.

if (obj == null) {
    System.Out.println( obj.getClass().getName() );
}

To explain in plain english what the programmer is trying to do:

Even if you are NULL tell me your name 😛

Tell your name?

How to make a Perfect Singleton?


In the previous post I mentioned about writing a post about how to write a perfect Singleton class without using Double Checked Locking. In this post I am going to discuss the same topic.

It seems to me that there are many ways to implement a Java Singleton which are listed below:

If you DO NOT NEED Lazy Initialization

and most of the time you don’t, then simply use a static member and initialize it right there (or in a static block). The class loader guarantees that only one thread will perform any class’s static initialization. By the way, if the only accessible static field or method is getInstance() and no code directly accesses Singleton.class or invokes Class.forName(“Singleton”), you essentially get lazy initialization for free thanks to the class loader.

public class Singleton {
	private static final Singleton instance = new Singleton();
	public static Singleton getInstance() {
		return instance;
	}
}

If you NEED lazy initialization

and you are OK with the overhead of always acquiring the mutex, then use this form:

public class Singleton {
	private static final Singleton instance;

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

	return instance;
	}
}

If you NEED lazy initialization

and you CANNOT stomach the overhead of always acquiring the mutex (this is the least likely case), then leverage the class loader’s behavior to guard the construction of the singleton. This solution relies on the fact that a class will not be loaded and initialized until referenced. The static inner class Instance will only be loaded when the outer class’s getInstance() method references Instance.value.

public class Singleton {
	private static class Instance {
		static final Singleton value = new Singleton();
	}

	public static Singleton getInstance() {
		return Instance.value;
	}
}

The inner class idiom is good. The Singleton is essentially a Factory and the instance itself a product of the Factory, so it is a separate abstraction. The Declaration suggests using a separate class but doesn’t mention the possibility of an inner class – an oversight possibly. Java inner classes don’t get the respect they deserve, they can be quite useful.

Nice solution, but is that class loading behaviour guaranteed in the Java specifications?
The Java Language Standard states that class loaders can prefetch or otherwise group the loading of classes. So, no the behavior in option 3 above is not guaranteed. However, it generally holds true since most class loaders do not prefetch classes.

Using Enums in Java 5 for Singleton

As Joshua Bloch suggested in his book Effect Java, 2nd Edition we can use Enums for making a Singleton and with it we

Summary of what has been said else where

  • The compiler / JVM can rearrange code within synchronized blocks for optimisation.
  • The compiler / JVM can move code into a synchronized block for optimisation.
  • The compiler / JVM cannot move code out of a synchronized block.
  • Threads can store local copies of variables that are not declared volatile or protected by a synchronized block so may not see changes made by other threads. (And volatile has a known bug prior to the implementation of JSR-133 – it doesn’t appear to actually do anything).

For these reasons you have to really know what you’re doing when trying to avoid synchronisation, and usually the only truly safe approach is to synchronise around the whole thing that needs to be thread safe. The extra cost is on the order of microseconds, and there are usually far better places to look to improve application performance.

How to make a Perfect Singleton?

The Guy Infront of You


This entry is dedicated to my friend – sali Note: This is a rant so if you are not interested in reading you can have a look at other posts 🙂

It is just a rant about how not to conduct an interview and also realize that interviews shouldn’t be taken lightly especially when it comes to interviewing a senior person. Anyways here goes the story…

Once upon a time in there was a Oracle Financials person (yea I would call him person) was given the task to develop a Oracle Financials for a Customer in Java. Without showing any concerns the person went on to find Java resources from the local market. He was referred different people and was so excited about developing the team that he didn’t even reviewed the resumes forwarded to him and just went on calling people for the interview. Again in excitement he didn’t even care to send out official emails for interview schedule and company address etc.

Anyways the process went on and a senior resource was called for the interview. Here comes the interesting part of the story – the actual interview conversation:

Q: So how are you? Did you have any problems finding our office? A: Hi, I am very good. Yes, I did had problems finding the office. There is no board identifying the office. (The only landmark near the office is actually a vegetable shop and a burger shop) Anyways I am here.

Q: So can you tell me about your experience? A: Yea, I am working on JEE for past N years and have worked on these many technologies…

Q: (Interrupting the interviewee) You haven’t worked on Eclipse?!?! A: (Thinking why is he asking for the IDE?!?!) Yes I have worked on Eclipse. It is basically a RCP but the biggest reason for its fame is as the premier Java IDE. But you can use any IDE if you are talking about it as an IDE. Its up to the user/developer what IDE he wants to work on as almost everyone has its own preferences.

Q: So you worked in this company as well? A: Yea, I worked there as a [Job Title] and worked for N years. Major responsibilities were…

Q: (Again Interrupting) Did you know this guy there? He worked as [his Job Title] A: While I was there he wasn’t there. I guess he joined after I left. (Thinking either this guy is totally dumb or hes really smart as this was a good attempt to verify if I actually worked there or not)

Q: So why are you looking to switch from your current employer? A: (Amazed – anyways till this time it was clear that this guy is dumb) I think you guys called me for a discussion. Anyways basic reasons for any switch are: 1) Learning Opportunities. 2) Growth. 3) Monetary benefits.

Q: So how much are you earning? A: My basic salary is this much and I am entitled to these benefits.

Q: Actually we are looking for a Software Engineer… A: (Totally shocked and angry at the same time) Wait. Did you had the time to check my resume? I am not interested in joining as a Software Engineer. I would like to tell you somethings that should have been followed so that the waste of time that is going on here wouldn’t have happened. The standard process is to send an email and tell the person that you are hiring/interviewing for this position so that there isn’t a waste of time. Here the interviewer started to give all sort of reasons of why he wasn’t following the procedure and started to blame different people. Oh – wow so you are blaming your own team that they don’t do what they are supposed to do. Just imagine what he would have been saying after hiring. This is definitely a NO in the interview process – Never do that in front of the resource you are hiring. Tells a lot about your personality.

Q: If you have any questions I am here to answer. A: (Thinking although this was a total waste of time anyways lets ask about the business and his experience – never waste an opportunity) Yea, I have many. Heres the conversation:

Q: Please tell me about the products and business are of the company? A: We are in Investment Banking. We provide support for banks in this area.

Q: Which part of Investment Banking are you guys in and are there any plans to grow/enter in any other areas? A: We are in every part of Investment banking. We are hiring for a project where the customer wants us to develop (the already developed product) in Java. Proudly saying We say Yes to everything the customer says.

Q: So actually customer is deciding what the company does? A: Yea, it is the Customer who takes decision.

Q: How much experience do yo have? Can you please give a brief introduction of yourself. A: I have 12+ years of experience in Oracle Financials. And I worked in this this this countries before coming back here.

Q: How much experience in Java? A: None. I have never worked on Java (feeling very proud about this statement)

Q: So who is the Architect of this Application? A: The Guy in front of you.

Closing remarks by the interviewee – So you are the Architect of an application in a technology that you haven’t worked on. This answered all the questions as to why he was very concerned about using Eclipse. As he himself had no idea of Java so he thought Eclipse was Java.

I guess this was it. This Guy Infront of You answered every question asked and completely silenced that interviewee. Good work on that 🙂

The Guy Infront of You

Auto Name Suggestion Horror


Recently a Bug was reported in our product about a certain swing window taking a lot of time to appear. Naturally the first thing you do is debug out the issue to find out what is going on behind the scenes that a simple window is taking that long to appear.

As I was stepping through the code using the eclipse debugger i found a call to a method getUniqueName() which was taking a hell of a time to return and the CPU was going mad while I was waiting for the call to return. Inside the method I found this beautifu piece of code that I would like to share with everyone. Here is the master piece:

private String getUniqueName(String baseName, BranchObject newBranch)
{
    String retVal = baseName;
    IBranchLink [] branches = m_javaCommand.getUtilBranches();

    for (int iCheck = 1; iCheck < Integer.MAX_VALUE; iCheck++)
    {
        for (int iBranch = 0; iBranch < branches.length; iBranch++)
        {
            BranchObject branch = (BranchObject)branches[iBranch];
            if ((newBranch != branch) && branch.toString().equals(retVal))
            {
                retVal += iCheck;
            }
            else
            {
                break;
            }
        }
    }
}

The purpose of the code was to search for a unique name to be given to the object that was created wnen the save button was hit on the swing window. For example if the base name is Image then this code will search out the objects to see if there is any object named Image if yes then it tries Image1 and then Image2 until it finds a unique name. Altough the code above doesn’t do this but there is one obvious mistake in the code.

I have fixed the problem but lets see if anyone out there can find the most obvious mistake in the code which was trying was driving the CPU crazy?

Auto Name Suggestion Horror

See if you can spot the mistake in this code?


Heres the code…

public void fillSlots(String s, ScriptEntity.ScriptEntityType t, int startHour, int startMinute, int frequency)
{
    frequency = frequency / MINUTES_IN_ONE_HOUR;
    if (frequency == 0) {
        return;
    }

    int iX = startMinute / MINUTES_IN_ONE_SLOT; 
    // X index: 0 minute -- iX (0); 15 minute -- iX (1);
    // 30 minute -- iX (2); 45 minute -- iX (3).
    int iY = startHour % Y_INDEX; // Y index

    for (int i = iY; i < Y_INDEX; ) {
        fillSlot(s, t, iX);
        i =+ frequency;
    }
}

Hint: Infinite loop !!!

See if you can spot the mistake in this code?

QA Friendly Java Profiler


We have been experiencing some issues with our product under a reasonable load. So our QA department jumped in and decided to load test the product. They decided to run our servers under a profiler and put a massive load on these servers inorder to find out what is going on.

I was having a discussion with the QA manager about this and I was asked to recommend JProfiler to the management so that a license could be acquired. To be frank I am not a very big fan of JProfiler. I usually don’t go with these commercial profilers unless the tools available with the JDK are simply not enough – which is rare. Even in that situation I use the YourKit Java Profiler. This is when I was asked “Is it QA friendly?

Well, this seems to me a wrong question because:

  • The profilers are never QA firendly as their target audience is never QA people, they are meant for the developers as its the developers who have written all the code and they who know their code the best and can put all the information to good use that the profilers produce.
  • Since the developers know how their code works they know what to profile and what not to profile. Profilers usually make the product slow and it really helps if you know what to profile. As you you don’t waste a lot of time waiting for the test case to complete and analyzing results.
  • QA generally regards everything as bug, if the profiler produces a dump having tons of byte[] than QA files this as a bug/root cause of the load issues. But in fact this can be wrong. And developers have to find out the root cause by themselves and it turns out that they end up wasting time finding the root cause of a problem which never existed.

So in my opinion all these activities should be left to the developers and the QA should act as a helping hand in these scenarios coming up with a reproducible test case that the developrs can use to find out the root cause be it using profilers or reviewing the code.

QA Friendly Java Profiler