Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4098186
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T20:16:10+00:00 2026-05-20T20:16:10+00:00

I’m looking for a piece of code which behaves a bit like a singleton

  • 0

I’m looking for a piece of code which behaves a bit like a singleton but isn’t (because singleton’s are bad 🙂 What I’m looking for must meet these goals:

  1. Thread safe
  2. Simple (Understand & use, i.e. few lines of code. Library calls are OK)
  3. Fast
  4. Not a singleton; for tests, it must be possible to overwrite the value (and reset it after the test).
  5. Local (all necessary information must be in one place)
  6. Lazy (run only when the value is actually needed).
  7. Run once (code on RHS must be executed once and only once)

Example code:

private int i = runOnce(5); // Set i to 5
// Create the connection once and cache the result
private Connection db = runOnce(createDBConnection("DB_NAME"));

public void m() {
    String greet = runOnce("World");
    System.out.println("Hello, "+greet+"!");
}

Note that the fields are not static; only the RHS (right hand side) of the expression is … well “static” to some degree. A test should be able to inject new values for i and greet temporarily.

Also note that this piece of code outlines how I intend to use this new code. Feel free to replace runOnce() with anything or move it to some other place (the constructor, maybe, or an init() method or a getter). But the less LOC, the better.

Some background information:

I’m not looking for Spring, I’m looking for a piece of code which can be used for the most common case: You need to implement an interface and there won’t ever be a second implementation except for tests where you want to pass in mock objects. Also, Spring fails #2, #3 and #5: You need to learn the config language, you must set up the app context somewhere, it needs an XML parser and it’s not local (information is spread all over the place).

A global config object or factory doesn’t meet the bill because of #5.

static final is out because of #4 (can’t change final). static smells because of classloader issues but you’ll probably need it inside runOnce(). I’d just prefer to be able to avoid it in the LHS of the expression.

One possible solution might be to use ehcache with a default setup which would return the same object. Since I can put things in the cache, this would also allow to override the value at any time. But maybe there is a more compact/simple solution than ehcache (which again needs an XML config file, etc).

[EDIT] I’m wondering why so many people downvote this. It’s a valid question and the use case is pretty common (at least in my code). So if you don’t understand the question (or the reason behind it) or if you have no answer or you don’t care, why downvote? :/

[EDIT2] If you look at the app context of Spring, you’ll find that more than 99% of all beans have just a single implementation. You could have more but in practice, you simply don’t. So instead of separating interface, implementation and configuration, I’m looking at something which has only an implementation (in the most simple case), a current() method and one or two lines of clever code to initialize the result for current() once (when it is called for the first time) but at the same times allows to override the result (thread safe, if possible). Think of it as an atomic “if(o==null) o = new O(); return o” where you can override the o. Maybe an AtomicRunOnceReference class is the solution.

Right now, I just feel that what we all have and use daily is not the optimum, that there is a baffling solution which will make us all slap our heads and say “that’s it”. Just as we felt when Spring came around a few years ago and we realized where all our singleton problems came from and how to solve them.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T20:16:10+00:00Added an answer on May 20, 2026 at 8:16 pm

    Here is a solution that fulfills all my requirements:

    /** Lazy initialization of a field value based on the (correct)
    * double checked locking idiom by Joschua Bloch
    *
    * <p>See "Effective Java, Second Edition", p. 283
    */
    public abstract class LazyInit<T>
    {
        private volatile T field;
    
        /** Return the value.
        *
        *  <p>If the value is still <code>null</code>, the method will block and
        *  invoke <code>computeValue()</code>. Calls from other threads will wait
        *  until the call from the first thread will complete.
        */
        @edu.umd.cs.findbugs.annotations.SuppressWarnings("UG_SYNC_SET_UNSYNC_GET")
        public T get ()
        {
            T result = field;
            if (result == null) // First check (no locking)
            {
                synchronized (this)
                {
                    result = field;
                    if (result == null) // Second check (with locking)
                    {
                        field = result = computeValue ();
                    }
                }
            }
            return result;
        }
    
        protected abstract T computeValue ();
    
        /** Setter for tests */
        public synchronized void set (T value)
        {
            field = value;
        }
    
        public boolean hasValue()
        {
            return field != null;
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm looking for suggestions for debugging... If you view this site in Firefox or
I have a jquery bug and I've been looking for hours now, I can't
link Im having trouble converting the html entites into html characters, (&# 8217;) i
Seemingly simple, but I cannot find anything relevant on the web. What is the
I want to count how many characters a certain string has in PHP, but
Does anyone know how can I replace this 2 symbol below from the string
this is what i have right now Drawing an RSS feed into the php,
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.