• Artemus Harper (unregistered)

    Standard Java Singleton 'hack':

    public class MySingleton { private static class SingletonHolder { public static final MySingleton INSTANCE = new MySingleton(); }

    public MySingleton instance() { return SingletonHolder.INSTANCE; }

    private MySingleton() { //constructor stuff } }

    The above is thread safe, and will only create an instance when instance() is called. This is because Java classes are loaded on demand, so once MySingleton is referenced, its static field is initialized.

  • @Deprecated (unregistered) in reply to Jim
    Jim:
    I really like that the article is called the Doubleton Patten.

    Just goes to show no one is safe when it comes to spelling errors that are not picked up by automated tools.

    -- Note from Alex: facepalm

    I think it is supposed to be "Doubleton Patent Pending"

  • ideo (unregistered) in reply to Anonymous
    Anonymous:
    sino:
    DeepThought:
    frits:
    Someone actually "published" an article on the Doubleton pattern. Needless to say it is full of WTFs and serves no useful purpose.

    Looks like a solution looking for a problem. You've got to love the fact that calling Doubleton.Instance will alternate the results between the two different instances. I can't for the life of me imagine where this would be welcome behavior in an application.

    Ok. I'll play your little game.

    Perhaps it could be of use in load-balancing requests over a stateless protocol?

    That would be a very naïve load balancing strategy so I don't think it really counts as a valid use (not for any intelligent person, at least). Any more suggestions? We'll find a home for that useless code eventually.
    grumble... Well, it's good enough for my company. Round-Robin, they call it.

    Session affinity? WTF's that?

    :/

  • radish (unregistered) in reply to sino

    The Gang of Four played the game as well. Quoted from the pattern's consequences section:

    "Permits a variable number of instances. The pattern makes it easy to change your mind and allow more than one instance of the Singleton class. Moreover, you can use the same approach to control the number of instances that the application uses. Only the operation that grants access to the Singleton instance needs to change."

    So, everyone that thinks the idea could only come from a moron needs to start evaluating whether or not they think the entire concept of patterns is now in question, since obviously the originators were morons.

  • quisling (unregistered) in reply to ideo
    ideo:
    Anonymous:
    sino:
    DeepThought:
    frits:
    Someone actually "published" an article on the Doubleton pattern. Needless to say it is full of WTFs and serves no useful purpose.

    Looks like a solution looking for a problem. You've got to love the fact that calling Doubleton.Instance will alternate the results between the two different instances. I can't for the life of me imagine where this would be welcome behavior in an application.

    Ok. I'll play your little game.

    Perhaps it could be of use in load-balancing requests over a stateless protocol?

    That would be a very naïve load balancing strategy so I don't think it really counts as a valid use (not for any intelligent person, at least). Any more suggestions? We'll find a home for that useless code eventually.
    grumble... Well, it's good enough for my company. Round-Robin, they call it.

    Session affinity? WTF's that?

    :/

    Wait, what? You're still using server-side Session State?

    That's soooooooo 2005!

    We're back to the stateless intarwebs, dincha know?

  • gravis (unregistered) in reply to somedudenamedbob
    somedudenamedbob:
    It starts there, and before you know it the world is cured of WTFs. What do you want Alex to do in his spare time?

    Ride BART.

  • Bart Simpson (unregistered) in reply to gravis
    gravis:
    somedudenamedbob:
    It starts there, and before you know it the world is cured of WTFs. What do you want Alex to do in his spare time?

    Ride BART.

    Eat my shorts!

  • Dani (unregistered)

    The analysis in the article seems a little bit flawed to me. The instance variable in the getInstance() method shouldn't be static, because that's not the variable getting checked in the if statement. And, assuming that Spring won't actually instantiate the PublicationService object until getBean() is called for the first time, the first call to getInstance() will only create one instance of PublicationService, not two.

    Of course, it's still broken; the very first call to getInstance is going to return one anonymous instance of PublicationService, and every subsequent call is going to return the Spring-managed instance. But it won't ever instantiate more than two instances, so it's not the rampant memory leak that the article suggests.

    The code actually isn't too far from being correct; change the second constructor to be a private static void method and pull the else clause of the getInstance() method out of the conditional and it will work as expected.

  • JavaDummy (unregistered)

    This is the worst C# code I have ever seen. All those c Pound developers need to switch to a real language like vb.

  • Henning Makholm (unregistered) in reply to tiller
    tiller:
    The public do nothing constructor is just stupid.
    I imagine it must be there for pubContext.getBean() to be able to instantiate the class through reflection.
  • zeno (unregistered)

    For instance, in a simple garbage collected language, things are allocated in heap 1, when collection occurs, objects still referenced are copied to heap 2, heap 2 is now the allocation heap, when collection occurs again, objects are copied to heap 1, and heap 1 becomes the allocation heap again. (This compacts the heap in the process as well)

    N-ton pattern is simply a funny name for a circular buffer with N slots...

  • Dan (unregistered) in reply to Jay
    Jay:
    Jim:
    Indeed I do. I also note that fewer people are able to do arithmetic these days because most of us have a calculator on our phone, so 'why do we need to know how?'. In a similar way, we all assume that, if there is no red squiggly line under a word, then it must be correct, so why check it.

    Sure. Like I always say: If the compiler didn't find any errors, the code must be right! The computer said so.

    All hail the compu-tor!

  • Fedaykin (unregistered)

    Looks like a munged attempt to refactor a singleton as a Spring managed bean.

  • Dan (unregistered) in reply to radish
    radish:
    The Gang of Four played the game as well. Quoted from the pattern's consequences section:

    "Permits a variable number of instances. The pattern makes it easy to change your mind and allow more than one instance of the Singleton class. Moreover, you can use the same approach to control the number of instances that the application uses. Only the operation that grants access to the Singleton instance needs to change."

    So, everyone that thinks the idea could only come from a moron needs to start evaluating whether or not they think the entire concept of patterns is now in question, since obviously the originators were morons.

    I'm on the side that questions the usefulness of singletons, myself. And their little caveat there creates a subtle difference in the original intent does it not? As a singleton, it is a storage point for global variables. As a N-ton, it's just a round-robin corner case.

  • RancidBeans (unregistered) in reply to Dani
    Dani:
    The code actually isn't too far from being correct; change the second constructor to be a private static void method and pull the else clause of the getInstance() method out of the conditional and it will work as expected.

    viz:

    public static PublicationService getInstance() {
        if (pubContext == null) {
          pubContext = PublicationService.loadContext(CONTEXTFILES);
        } 
        return (PublicationService)  pubContext.getBean("publicationService");
        }
    
    // public ctor needed for spring to instantiate
    public PublicationService()
    {
    }
    
    protected static loadContext(final String[] contextFiles) {
        // try to load an application context Spring file, 
        // it is okay if this fails
        try {
          final ClassPathXmlApplicationContext ctxt = 
            new ClassPathXmlApplicationContext(contextFiles);
          ctxt.registerShutdownHook();
          pubContext = ctxt;
        } catch (final Exception e) {
          LOG.info(" Unable to load ApplicationContext from " 
            + contextFiles[0], e);
        }
      }
    
    

    But this is not a good refactoring - it does not maintain the Clearly Documented Feature (TM), namely, that it's ok for the context load to fail. Here, we would get a NullPointerException. Failure to load the context under the original code, resulted in the static context remaining null, and a new services instance instantiated each time the 'singleton' is requested. Hence the "memory hog" reports.

    To play well in the face of errors, we might check if the context was initialized:

    public static PublicationService getInstance() {
        if (pubContext == null) {
          pubContext = PublicationService.loadContext(CONTEXTFILES);
        } 
        return context==null ? new PublicationService() : (PublicationService)  pubContext.getBean("publicationService");
        }
    
    

    But this is the same flavour of crap that was initially served up. A better, but more risky fix is to stop caching environmental/startup problems and allow these to bubble up and be handled properly, usually by the application not starting.

    I'm sure the coder was trying to be safe, just like those people who clench up in order to fart discretely. But sooner or later, approaches like this will lead to disaster when the silent failures are finally discovered due to some later catastrophic failure and soiled pants.

    Failure to load the Spring context is most likely fatal. But if the application really can manage without the Spring instantiated service, as claimed in the code, then why bother having all crap in the first place?

    captcha: paratus - one who quotes others

  • (cs) in reply to radish
    radish:
    The Gang of Four played the game as well. Quoted from the pattern's consequences section:

    "Permits a variable number of instances. The pattern makes it easy to change your mind and allow more than one instance of the Singleton class. Moreover, you can use the same approach to control the number of instances that the application uses. Only the operation that grants access to the Singleton instance needs to change."

    So, everyone that thinks the idea could only come from a moron needs to start evaluating whether or not they think the entire concept of patterns is now in question, since obviously the originators were morons.

    GoF fanboys scare me IRL.

  • blackanchorage (unregistered) in reply to Artemus Harper
    Artemus Harper:
    Standard Java Singleton 'hack':

    public class MySingleton { private static class SingletonHolder { public static final MySingleton INSTANCE = new MySingleton(); }

    public MySingleton instance() { return SingletonHolder.INSTANCE; }

    private MySingleton() { //constructor stuff } }

    The above is thread safe, and will only create an instance when instance() is called. This is because Java classes are loaded on demand, so once MySingleton is referenced, its static field is initialized.

    Not a hack, an elegant solution (lazy, but performant, so can be used always).

    Initialization on Demand Holder in wiki (so it must be true).

    Regards

  • blunder (unregistered) in reply to Anonymous
    Anonymous:
    Jim:
    I really like that the article is called the Doubleton Patten.

    Just goes to show no one is safe when it comes to spelling errors that are not picked up by automated tools.

    Do you ever consider that maybe, just maybe, the reason we're all so shit at spelling these days is because of an over-reliance on those automated tools? Maybe the only way we'll be safe from typos is if we stop relying on those tools and start relying on our brains.

    It's a pipe dream, I know.

    I'll believe you when you can show me that people actually use the tools.

    Also: let's all stop wearing glasses. That way, nearsighted people won't survive to procreate, and no one will need glasses anymore!

  • BeyondIronic (unregistered)

    secodn!

  • sino (unregistered) in reply to blunder
    blunder:
    Anonymous:
    Jim:
    I really like that the article is called the Doubleton Patten.

    Just goes to show no one is safe when it comes to spelling errors that are not picked up by automated tools.

    Do you ever consider that maybe, just maybe, the reason we're all so shit at spelling these days is because of an over-reliance on those automated tools? Maybe the only way we'll be safe from typos is if we stop relying on those tools and start relying on our brains.

    It's a pipe dream, I know.

    I'll believe you when you can show me that people actually use the tools.

    Also: let's all stop wearing glasses. That way, nearsighted people won't survive to procreate, and no one will need glasses anymore!

    How the hell do I upboat this?!?

  • Scrappy (unregistered) in reply to Johnny Awkward
    Johnny Awkward:
    TeKilla:
    frist

    Congratulations. You've got the ironic misspelling, but these days it's customary to ironically leave your first post until later in the conversation as well, thus making the post even more ironic.

    However, I'd like to propose that, in order to increase the irony even more, we type "frist" into the comment box and then close the browser before clicking on submit. That would be so ironic we just wouldn't be able to help but think what an amazing person you are, and laugh at your comic genius.

    Actually, considering the topic of doubleton's, I was expecting today's first post to say

    second

  • Anonymous coward (unregistered) in reply to Jay

    For memory buffer operations that cannot be done in-place, you might want to alternate between two buffers (e.g.: String operations between two string buffers; graphics operations between two surfaces).

  • Simon (unregistered) in reply to Dani

    Agreed - it's still bad code, but the WTF analysis is completely wrong. As you say, the first call is broken, but all it needs to fix it is to inline that protected constructor into the 'if' check, and move the 'else' condition to be always run.

    Buggy code, sure, but nowhere the near the usual "what lunatic wrote this" standards...

  • ThreadingDaemon (unregistered)

    None of this actually matters, because even getInstance() has no synchronization, and is a race condition.

    captcha: venio

  • Joe (unregistered) in reply to highphilosopher

    Actually when you really start to ponder it deeply the singleton pattern when dealing with concurrency can become one of the hardest pattern to correctly implement, especially in C++, Java got it a little easier, but there is still lots of room for errors.

  • Duc (unregistered) in reply to blackanchorage
    blackanchorage:
    Artemus Harper:
    Standard Java Singleton 'hack':

    public class MySingleton { private static class SingletonHolder { public static final MySingleton INSTANCE = new MySingleton(); }

    public MySingleton instance() { return SingletonHolder.INSTANCE; }

    private MySingleton() { //constructor stuff } }

    The above is thread safe, and will only create an instance when instance() is called. This is because Java classes are loaded on demand, so once MySingleton is referenced, its static field is initialized.

    Not a hack, an elegant solution (lazy, but performant, so can be used always).

    Initialization on Demand Holder in wiki (so it must be true).

    Regards

    Umm, this code doesn't work. There is no way anyone can get hold of the instance. It should be called no instance pattern ... lol

  • Doomday theories (unregistered) in reply to Anonymous

    By the same logic no one should ever drive cars, we should all walk! You know, because people are getting fat/unfit/etc.

    We use calculators because they can do simple maths faster and more accurately than we could ever hope to. Let your brain get exercise by doing logic puzzles that are beyond your simple friend the calculator and just like using a car instead of walking, save yourself some time.

    Also, for the guys above, please read the definition of the word "irony", you make my soul bleed.

  • Anonymous Coward (unregistered) in reply to KingOfIrony
    KingOfIrony:
    frist!

    "The use of words expressing something other than their literal intention!"

    Now that IS Irony!

  • Mathew (unregistered) in reply to Anonymous
    Anonymous:
    It always surprises me how often you see this basic pattern implemented incorrectly. It is a very simple concept that is very simple to implement but people screw it up all the time.

    Personally I love this pattern. There is something beautiful about its simplicity, I can't even quite put my finger on it. I'm going to go apply this pattern right now to a repository I'm working on (which uses the repository pattern - yes, I do love a good pattern).

    I've always been a fan of plaid myself.

  • Ms phan (unregistered) in reply to frits
    frits:
    Someone actually "published" an article on the Doubleton pattern. Needless to say it is full of WTFs and serves no useful purpose.
    "The author has also worked for Microsoft based at Redmond."

    I have to wonder how many "doubletons" are running around in Windows right now... is that why MS won't show us the Windows source?

  • MyHobbyIsResearch (unregistered) in reply to Ms phan
    frits:
    Someone actually "published" an article on the Doubleton pattern. Needless to say it is full of WTFs and serves no useful purpose.

    I know it's pretty obvious but it all makes sense: clearly, the author wanted to target embedded platforms with no file system. Just what you would expect from someone that has hobbies like "training, mentoring and research". He's teh smart!

  • MyHobbyIsResearch (unregistered)

    His other articles are full of WTFs too http://www.codeproject.com/script/Articles/MemberArticles.aspx?amid=1909449 I'd love to know BizTalk just to enjoy the blunders. The last ones http://www.codeproject.com/KB/dotnet/Surrogate_Serialization.aspx http://www.codeproject.com/KB/graphics/gdi_drawingpanel.aspx are enjoyable by a wide public. Our certified hero seems not to be aware of the existence of auto properties.

  • (cs) in reply to Anonymous
    Anonymous:
    Do you ever consider that maybe, just maybe, the reason we're all so shit at spelling these days is because of an over-reliance on those automated tools? Maybe the only way we'll be safe from typos is if we stop relying on those tools and start relying on our brains.

    The thing that really bugs me is when people use spellcheckers & then pick the wrong word, like roll instead of rôle for example. This seems to be happening more all the time, even in newspapers

  • foo (unregistered)

    Wow, does -anyone- really understand how Java works?

    Based on the discussion so far it really looks to me like none of you really do. Lots of guessing about what this or that may or may not do, no one can agree.

    I know nothing about Java/OOP, but it doesn't sound real deterministic to me. I've done a lot of programming in my time (yeah, get off my lawn!) but you all sounds like a bunch gibbering monkeys.

    I've got to think that Java itself is the TWTF here.

    Brand me a troll, but seriously, WTF?!?!?

  • jerk_programmer (unregistered) in reply to highphilosopher
    highphilosopher:
    The singleton pattern is usually the hardest for people to implement properly. I've never understood why. It's not a hard pattern, but sometimes people don't think through their code before they commit it.
    that's because of a biased sample. Singleton is nothing more than a kind of global variable; bad designs have a lot of globals, and people doing bad designs are not likely to implement anything else properly either.
  • jerk_programmer (unregistered) in reply to radish
    radish:
    The Gang of Four played the game as well. Quoted from the pattern's consequences section:

    "Permits a variable number of instances. The pattern makes it easy to change your mind and allow more than one instance of the Singleton class. Moreover, you can use the same approach to control the number of instances that the application uses. Only the operation that grants access to the Singleton instance needs to change."

    So, everyone that thinks the idea could only come from a moron needs to start evaluating whether or not they think the entire concept of patterns is now in question, since obviously the originators were morons.

    Right, the reference to gang of four as if they were some sort of authority. All they did was listing patterns that were in common use - good and bad alike - and giving those patterns cute names. That's all. If a particular brilliant design is common, it is in that book. If a particular codesod is common, it is also in this book. Simple as that. If you actually read the damn book, you may notice numerous statements to this sense.

  • gbs (unregistered) in reply to Megatron
    Megatron:
    You have got to love OOD, pure gibberish.
    It's not a problem of OOD. It's a problem of people applying design patterns without understanding them.
  • illtiz (unregistered) in reply to Doomday theories
    Doomday theories:
    By the same logic no one should ever drive cars, we should all walk! You know, because people are getting fat/unfit/etc.

    We use calculators because they can do simple maths faster and more accurately than we could ever hope to. Let your brain get exercise by doing logic puzzles that are beyond your simple friend the calculator and just like using a car instead of walking, save yourself some time.

    Also, for the guys above, please read the definition of the word "irony", you make my soul bleed.

    Uhm - you do realize that, while cars are actually faster than people and calculators are less error-prone, your spelling software is actually (hopefully) inferior to you in a lot of ways related to correct writing?

    Or were you being ironic there?

  • Anonanon (unregistered) in reply to illtiz
    illtiz:
    Doomday theories:
    By the same logic no one should ever drive cars, we should all walk! You know, because people are getting fat/unfit/etc.

    We use calculators because they can do simple maths faster and more accurately than we could ever hope to. Let your brain get exercise by doing logic puzzles that are beyond your simple friend the calculator and just like using a car instead of walking, save yourself some time.

    Also, for the guys above, please read the definition of the word "irony", you make my soul bleed.

    Uhm - you do realize that, while cars are actually faster than people and calculators are less error-prone, your spelling software is actually (hopefully) inferior to you in a lot of ways related to correct writing?

    Or were you being ironic there?

    But I'm sure your spelling software would disagree with you about whether "Uhm" is a word, and in this case it would be Spelling software: 1 - You: 0

  • Anonymous (unregistered) in reply to Doomday theories
    Doomday theories:
    By the same logic no one should ever drive cars, we should all walk! You know, because people are getting fat/unfit/etc.

    We use calculators because they can do simple maths faster and more accurately than we could ever hope to. Let your brain get exercise by doing logic puzzles that are beyond your simple friend the calculator and just like using a car instead of walking, save yourself some time.

    Enjoy your dwindling intellect - while it lasts.

  • illtiz (unregistered) in reply to Anonanon
    Anonanon:
    But I'm sure your spelling software would disagree with you about whether "Uhm" is a word, and in this case it would be Spelling software: 1 - You: 0
    I see your point, but choose to interpret the result differently: For correcting that "typo", Spelling software: 0 and one false positive.
  • noway! (unregistered)

    I have always found this doubleton pattern to be easier to nobulate on an embedded system.

  • (cs) in reply to Jim
    Jim:
    Indeed I do. I also note that fewer people are able to do arithmetic these days because most of us have a calculator on our phone, so 'why do we need to know how?'.

    ... snip ...

    No one wants to have to rely on their own brain when there are adequate, easier to use alternatives. Sad, but true.

    My son has recently discovered Isaac Asimov, so I've been having a lot of fun reacquainting myself with his work. In his anthology "Robot Dreams", there's a story called The Feeling of Power that suggests a frighteningly believable end result of this trend.

  • (cs) in reply to Anonanon
    Anonanon:
    illtiz:
    Doomday theories:
    By the same logic no one should ever drive cars, we should all walk! You know, because people are getting fat/unfit/etc.

    We use calculators because they can do simple maths faster and more accurately than we could ever hope to. Let your brain get exercise by doing logic puzzles that are beyond your simple friend the calculator and just like using a car instead of walking, save yourself some time.

    Also, for the guys above, please read the definition of the word "irony", you make my soul bleed.

    Uhm - you do realize that, while cars are actually faster than people and calculators are less error-prone, your spelling software is actually (hopefully) inferior to you in a lot of ways related to correct writing?

    Or were you being ironic there?

    But I'm sure your spelling software would disagree with you about whether "Uhm" is a word, and in this case it would be Spelling software: 1 - You: 0

    In illtiz's defence, it could be a portmanteau of "uh" and "um".

  • Nitrodist (unregistered) in reply to Duc
    Duc:
    blackanchorage:
    Artemus Harper:
    Standard Java Singleton 'hack':

    public class MySingleton { private static class SingletonHolder { public static final MySingleton INSTANCE = new MySingleton(); }

    public MySingleton instance() { return SingletonHolder.INSTANCE; }

    private MySingleton() { //constructor stuff } }

    The above is thread safe, and will only create an instance when instance() is called. This is because Java classes are loaded on demand, so once MySingleton is referenced, its static field is initialized.

    Not a hack, an elegant solution (lazy, but performant, so can be used always).

    Initialization on Demand Holder in wiki (so it must be true).

    Regards

    Umm, this code doesn't work. There is no way anyone can get hold of the instance. It should be called no instance pattern ... lol

    Umm, how about fix it or stfu?

    Just add 'static' to the instance() method. Jesus, it's not like it had compilation errors.

  • Quirkafleeg (unregistered) in reply to frits
    frits:
    In illtiz's defence, it could be a portmanteau of "uh" and "um".
    Hm.
  • (cs) in reply to foo
    foo:
    Brand me a troll, but seriously, WTF?!?!?

    Your comment boils down to "I admit knowing nothing about the dominant programming paradigm of the past 15-20 years, yet I must inform you how stupid YOU ALL are."

    Why should you not be branded a troll?

  • Megatron (unregistered) in reply to gbs
    gbs:
    Megatron:
    You have got to love OOD, pure gibberish.
    It's not a problem of OOD. It's a problem of people applying design patterns without understanding them.

    Which is OOD in practice.

  • anon anon anon (unregistered) in reply to sino

    You must be a redditor.

  • (cs) in reply to frits
    frits:
    Someone actually "published" an article on the Doubleton pattern. Needless to say it is full of WTFs and serves no useful purpose.

    I guess that guy never heard of n-sized object pools. And to boot, he has a master and has won multiple projects. Even more sad, the people in that forum making suggestions on how to improve this abomination.

    It ain't a pattern. A pattern is not just some arbitrary class. It does not list motivation (the problem domain), forces, application, collaborating forces, consequences and caveats, intent, all the things a composition should have to be a pattern.

    /facepalm.

Leave a comment on “The Doubleton Pattern”

Log In or post as a guest

Replying to comment #:

« Return to Article