Java Singleton

Featured

After going through a couple job interviews, I quickly realized that there are many differing “opinions” (yes even among seasoned Java programmers) about the best way to initialize a singleton class. For the record, there are really only two fundamental ways of initializing a singleton properly in java: eager or lazy. Then there is a neat trick to try to get the best of both worlds so that makes a total of three. Depending on the person you talk to, one of these methods may be preferred over the others but all three listed below are thread safe.

Eager Initialization

In eager initialization, the singleton is instantiated when the programs starts whether or not it gets used. The problem with this approach is that valuable resources are allocated whether or not they ever get used. If the singleton has a large memory footprint, this may not be a good choice.

Example 1. Eager Initialization

public class Singleton {

    // Eager initialization happens here.
    static private Singleton instance = new Singleton();

    // Prevent instantiation by public.
    private Singleton() {
    }

    public static Singleton getInstance() {
        return instance;
    }
}

Eager initialization relies on the fact that the JVM will initialize the class members upon loading the class. And the class is loaded when it is first referenced.

Lazy Initialization

On the other end of the spectrum, we have lazy initialization which the object only get instantiated on the first time the getInstance() method is called. This has the advantage of not allocating the resources unless it is actually needed.

The problem with this approach is that the getInstance() method needs to be synchronized. Therefore there is a performance hit when acquiring the singleton.

Example 2. Lazy Initialization

public class Singleton {

    static private Singleton instance = null;

    // Prevent instantiation by public.
    private Singleton() {
    }

    synchronized public static Singleton getInstance() {
        if (instance == null) {
            // Lazy initialization happens here
            // on the first call to this method.
            instance = new Singleton();
        }
        return instance;
    }
}

Do not try to circumvent the synchronized method by using a DCL (double check locking) mechanism as it does not work with the java memory model. Read more about that by following the resources links below.

Initialize-on-demand holder class idiom

There is one final way to get the best of both worlds and that is to use “Initialize-on-demand holder class” idiom which can be found in “Effective Java” by Joshua Bloch. This method relies on the JVM only intializing the class members upon first reference to the class. In this case, we have a inner class that is only referenced within the getInstance() method. This means SingletonHolder will get initialized on the first call to getInstance().

Example 3. Initialize-on-demand

public class Singleton {

    // Prevent instantiation by public.
    private Singleton() {
    }

    public static Singleton getInstance() {
        return SingletonHolder.instance;
    } 

    /**
     * Singleton implementation helper.
     */
    private static class SingletonHolder {
        // This gets initialized on first reference
        // to SingletonHolder.
        static final Singleton instance = new Singleton();
    }
}

Now the singleton object will not get allocated until it is used and we did not need to incur the overhead of a synchronized method call.

Happy programming,
Chiao

References and Resources

Make a viking costume

As always, when working with knifes and other tools, use extreme caution and wear safety glasses.

Supplies needed

  • 24″x24″ hardboard
  • black, white, brown and silver acrylic paint
  • large black construction paper

Tools needed

  • Utility knife
  • flush saw (other types may also work)
  • drill
  • sand paper
  • large and small paint brush

You need 4 basic colors: black, white, brown and silver. The black and silver will be used the most as they will be the undercoat and base color respectively.

Make a viking shield

I started with a 24″x48″ hard board for the shield (right). Since the biggest side of the hard board is 24″, that was the biggest my shield could be. Mark off 12″ from two adjacent edges and mark it with a thumb-tack; this is the center of your shield. Now use a string with pencil tied to the end and wrap the other end of the string arond the tack so that the pencil reaches the edge of the board. Now you move the pencil at the full extension around the tack and draw a circle. With a flush saw, cut the shield out along the line you just drew. I used a flush saw because it is flexible and does a nice job of cutting along the circular line. Other types of saws may also work.

To create the effect of many wooden boards joined together, cut seams in the hard board. Draw lines down the middle of the shield and then continue to mark parallel lines about 4″ apart (bottom-left). Using a utility knife carefully cut v-shaped seams down each line (bottom-middle).

04_cutting_seams05_sanding_shield

Since the hard board had a glossy smooth surface, I sanded it down with rough sand paper. This will give it a rough wood like effect (top-right).

With a large nail, score random lines on the surface of the shield (bottom left).  The lines should be in the same direction as the seams cut earlier.  You can see the effects of the scoring and the seams that were cut (bottom right). Now we are ready to paint!

06_scoring_wood_lines07_ready_to_paint

Give the shield an light undercoat of black paint (bottom). This provides an initial layer for the base coat to stick to later. The reason for using black is to give the shield a darker look. Let the shield dry for a day.

09_undercoat_finished08_black_undercoat

Let’s start on the shield boss while we wait for the shield to dry.

13_creating_the_boss

14_boss_undercoatViking shields have a metal cap in the middle of the shield called a boss. This acts as a cover for the hole that will be in the middle of the shield; which is also where your handle will be. For a boss, I used a 28 oz. styrofoam bowl (left). The bowl will be fixed onto the shield with the bottom facing forward. This means only the bottom of the bowl needs to be painted. Start by giving the bowl a blackundercoat. Since the bowl will eventually be silver, make sure the black undercoat is solid. Silver will show better when painted over a black surface. For me, it took 3 to 4 coats of black paint to finally achieve a nice solid color (right). Wait for the black coats to dry and then paint the bowl silver. Again, this should take 3 to 4 coats.

Once you decided on your boss, you need to cut a hole that is about 0.5″ smaller than the diameter of the boss (bottom left). This is because you will attach the boss to the shield by the lip of the boss. Again, you can use the pencil and string to draw the circle. But I could not use the flush saw to cut this inner circle because it was too small. I ended up using the utility knife which took a really long time.

10_center_hole11_brown_coat

Once the black undercoat for the shield has dried, paint the base color brown over it (top middle). Be careful not to get too much paint into the seams that you created as it will fill them up. If you do get too much paint in them, just use your brush or a paper towel and soak it up. This brown might seem very bright but that is ok because we are going to use a technique called washing to bring back the dark textures of the shield.

12_black_washAfter the brown has dried, “wash” the shield with black paint. Washing is the techique of using very watery paint or ink and applying it over the whole surface. Since the paint is watery, most of it will flow into the seams and textures of the surface. This brings out the different depths and creates a shadow and outline like effect. It also makes the base color a bit darker as some of the wash stays on the surface (right). Just take some black paint and add water to it until the paint can flow easily. It may be safer to make it more watery than less the first time you do it because if it is not dark enough, you can always give the shield another wash. But if it too thick, then you will essentially be painting the shield black instead of just giving it a wash.

To finish up the paint job, we will highlight the shield with a technique called drybrushing. Make sure the wash has fully dried before doing this. To drybrush, you take the base color and make it brighter; usually by mixing in white paint. In this case, our base color is brown and just add a few drops of white into it. This brown should be noticably brighter than the original brown. Dip the brush in the paint and then wipe the paint off the brush with your paper towel. This might seem extremely stupid but trust me, it is very important that most of the paint gets wiped off the brush. In fact, you should have a hard time seeing the paint after your done. Now with the almost paint-less brush, start brushing the surface of the shield starting with the edges. This will require many many strokes for you to see any effect. And it will require you to get more paint and wipe it off again and again but do not be tempted to leave more paint on the brush. If you do it long enough, you will start seeing highlights on edges of the shield. Along with the washes, this will give the shield a realistic 3D effect (bottom). From the picture, you can see the edges around the seams tend to be brighter. These are not blemishes in the picture but actual highlights on the shield.

15_secure_boss

Before securing the boss to the shield, I stacked another styrofoam bowl under the painted one and glued both of them together. This helps make the boss stronger. Center the boss over the inner hole. Tape the boss from the back side of the shield to secure it temporarily. Then from the painted side, drill 4 evenly spaced holes through the lip of the boss all the way through the shield (top), making sure none of the holes will come in contact with the vertical handle in the back (bottom). Once the holes are drilled, screw the boss into the shield using machine screws with cap nuts. The cap nuts should be on the painted side.

16_secure_handle

The handle should be attached vertically relative to the seams in the shield. The seams should be horizontal. Like the boss, temporarily tape the handle to the shield. Six holes should be drilled through the handle and shield, three on each side of the boss hole. But unlike the boss holes, the handle holes should be drilled from the un-painted side. This is so you can center the holes in the handle (top). For the handle, also use machine screws and cap nuts. In addition, add a 0.25″ cut washer to the painted side. These are the large round coin sized discs (bottom left).

17_nut_closeup18_shield_finished

Finally, you see the finished product! (top right).

Make a viking hat

20_construction_paperFind a black piece of construction to save you the trouble of priming the hat with black paint (left). The best way in making the origami viking hat is to follow the instruction here: Instructions on folding a viking hat.  Make a couple of small hats with normal paper first for practice.  Try on the hat and see if it fits before you paint it.

21_oragami_viking_hat

Create a nose guard to make the hat look more serious. It is just a rectangular piece of construction paper with two half triangles cut out where it crosses your eye (right).

Paint the hat silver except for the two horns.  Look at the finished image below to see what the horns are.

If the hat does not stay on, punch a hole on the two sides of the hat and put a string through it.

Viking beard and sword

I did not know how to make a beard or sword so I decided to buy it from a costume shop.

26_beard_and_sword

Finished

viking_full

Four tubes of acrylic paint: $9.50

Large sheet of black construction paper: $2.35

Plastic sword and fake beard: $11

Home-made shield: $5

Dressing up in a make-shift viking costume with oragami hat: priceless

WordPress thumbnail generation disabled

No thumbnails in your wordpress? Read on…

I noticed last night that my wordpress is not generating thumbnails from uploaded images like it’s suppose to. You’ll noticed that the size options (thumbnail, medium, large) are all disabled except for the full size.

wordpress-size-options

After doing a lot of searching, I finally found out that in order for wordpress to generate thumbnails “by default”, you need to have GD library support for your php. It would have been nice if wordpress had documented that better.

The only reference I found was this:

http://wordpress.org/support/topic/235625

To be clear, wordpress does not generate thumbnails by default unless your php instance has GD support.

Install php gd library

For me, installing GD library was easy:

# yum install php-gd

Check for gd

To check if you have GD loaded in php:

# php -m
[PHP Modules]
bz2
calendar
ctype
curl
date
dbase
exif
ftp
gd
gettext
gmp
hash
iconv