Skip to main content

singleton - invokestatic - multiple threads

1 reply [Last post]
Joined: 2006-07-27

We made thousand (I = [0 .. 999]) singletonI classes.

public class singletonI extends abstractclass {
private static singletonI instance;

private singletonI(){}

public int getValue(){

public static singletonI getInstance() {
if (instance == null) {
instance = new singletonI();

return instance;

Each class has a getValue method. The body of the getValue
method can either be complex or simple. A simple body means that
the method returns the value 10 (return 10;). A complex body is
a body that uses other classes' getValue methods to
calculate a complex value, which it subsequently returns (for example return
singletonI.getInstance().getValue() + singletonI.getInstance().getValue();)

We also made one large singleton class in which we
store all methods of the thousand separate classes. The compelex getValue methods
invoke other getValue methods which are now stored in the same class.

Could someone explain me why the large class alternative is faster than the
thousand classes alternative? If take 10 threads the difference between the two alternatives
is even bigger.

java version "1.4.2_11"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_11-b06)
Java HotSpot(TM) Client VM (build 1.4.2_11-b06, mixed mode)

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2004-01-07

1.) First of all if you use multiple threads than your programm is broken anyway - your getInstance() method is NOT THREAD SAFE! The most scalable approach I know of is to use ThreadLocal in conjunction with synchronized, google a bit for more information.

2.) To be honest I don't know, what you told us here is a bit vague. If you've several small instance classes you've more overhead of course because:
- You've more code which is executed (getInstance, null-check, memory copies and so on)
- I don't know much about the generated code but it could be that it fits better into caches.

3.) Use an up2date version of java, run a long time and use the java server runtime.

lg Clemens