Global Variables And Virtual Machines

I was perusing some code recently, found a Singleton, and thought "if I ran two copies of the application, would I need another one of these?"

Global variables are evil, but nobody really needs to be told that. The problem is when they're considered a necessary evil, or a convenient evil, tolerated in order to store data that most of your objects need easy access to, and that would be too much effort to pass around explicitly.

In an application that runs in regular process-space, the scope of a global variable encompasses the application, and nothing more. Running (in my case) Java on its virtual machine, the scope of a static variable encompasses the entire virtual machine, and any other applications (or copies of the same application) you may have running on it. Web application servers will run all your web applications in the same VM unless you order them not to. MacOS X claims to reduce Java overhead "through the sharing of Java class data and Hot Spot compiled code across invocations", so you can't trust the Operating System not to cheat and cram separate applications into the one VM.

Thus, in a Virtual Machine environment, something can be global only if it is the only one of these objects that you would wish to be in existence across multiple invocations of your application, and anyone else's application besides.

In LISPs, Perl, etc. you can create a new frame for your application and your application alone. Don't confuse Java with all virtual machines.

Don't get Java confused, either. On the Java VM the run-time scope of a public static member is not the entire VM, it is the objects in the VM that are instances of classes loaded by the same classloader that loaded the class of which the static in question is a member. [Not quite; that doesn't take into account classloader delegation.]

This is a very practical mechanism, which has been used since Applets to give programs their own namespace within a shared VM.

The Class Loader mechanism is powerful, but for various reasons it's not perfect. JSR 121 proposes a more thorough solution: jcp.org .

See original on c2.com