Sign in to follow this  
Alundra

static ... bad design ?

Recommended Posts

Hi,

using a singleton need to check if the instance is allocated.That demand this check eveytime we need to use the singleton.

The alternative is to use a static but recently i have listen that using static is not good because of multithreading.

Using static is a bad design ?

 

Thanks

Share this post


Link to post
Share on other sites

Hi,using a singleton need to check if the instance is allocated.That demand this check eveytime we need to use the singleton.
The alternative is to use a static but recently i have listen that using static is not good because of multithreading.

You haven't really described why you think this is a necessary design decision, but based on sheer probability and the fact that you mentioned a singleton to begin with, I'd wager decent money that your specific use case is "bad" design.

The bad design is, obviously, having to check on access whether something has been initialized: it would be equally bad for non-singleton objects. The actual alternative is not between a singleton and a static variable, but between silly "on demand" initialization (like in Hodgman's code snippet) and a correct object lifetime (ensuring that static variables are initialized before access, like in Java where the first reference to a class pauses client code to load the class and run its static initialization).

Share this post


Link to post
Share on other sites

Using any kind of shared mutable state is not going to play nice with multi-threading. Even if you fix initialisation problems, you still need to deal with the thread safety when accessing and modifying the state itself.

 

This is regardless of whether you expose such state as a global, a static value, a singleton, or even passing a reference.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this