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

  • Home
  • SEARCH
  • 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 448689
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T21:41:41+00:00 2026-05-12T21:41:41+00:00

First let’s look at the utility class (most javadoc has been removed to simply

  • 0

First let’s look at the utility class (most javadoc has been removed to simply the example):

public class ApplicationContextUtils {

    /**
     * The application context; care should be taken to ensure that 1) this
     * variable is assigned exactly once (in the
     * {@link #setContext(ApplicationContext)} method, 2) the context is never
     * reassigned to {@code null}, 3) access to the field is thread-safe (no race
     * conditions can occur)
     */
    private static ApplicationContext context = null;

    public static ApplicationContext getContext() {

    if (!isInitialized()) {
        throw new IllegalStateException(
            "Context not initialized yet! (Has the "
                + "ApplicationContextProviderBean definition been configured "
                + "properly and has the web application finished "
                + "loading before you invoked this method?)");
    }

    return context;
    }

    public static boolean isInitialized() {
    return context == null;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(final String name, final Class<T> requiredType) {
    if (requiredType == null) {
        throw new IllegalArgumentException("requiredType is null");
    }
    return (T) getContext().getBean(name, requiredType);
    }

    static synchronized void setContext(final ApplicationContext theContext) {

    if (theContext == null) {
        throw new IllegalArgumentException("theContext is null");
    }

    if (context != null) {
        throw new IllegalStateException(
            "ApplicationContext already initialized: it cannot be done twice!");
    }

    context = theContext;
    }

    private ApplicationContextUtils() {
    throw new AssertionError(); // NON-INSTANTIABLE UTILITY CLASS
    }
}

Finally, there is the following helper Spring managed bean that actually calls the ‘setContext’ method:

public final class ApplicationContextProviderBean implements
    ApplicationContextAware {

    public void setApplicationContext(
        final ApplicationContext applicationContext) throws BeansException {
    ApplicationContextUtils.setContext(applicationContext);
    }
}

Spring will call the setApplicationContext method once after the app is started. Assuming a nincompoop has not previously called ApplicationContextUtils.setContext(), that should lock in the reference to the context in the utility class, allowing calls to getContext() to success (meaning that isInitialized() returns true).

I just want to know if this class violates any principles of good coding practices, with respect to thread safety in particular (but other stupidities found are welcome).

Thanks for helping me to become a better programmer, StackOverflow!

Regards,
LES

P.S. I didn’t go into why I need this utility class – let it suffice that I indeed do have a legitimate need to access it from a static context anywhere in the application (after the spring context has loaded, of course).

  • 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-12T21:41:42+00:00Added an answer on May 12, 2026 at 9:41 pm

    No. It’s not thread safe.

    Writes to the context class variable are not guaranteed to be visible to threads that read that variable through getContext().

    At the very least, declare context to be volatile. Ideally, redefine context as an AtomicReference, set through a call like this:

    if(!context.compareAndSet(null, theContext))
      throw new IllegalStateException("The context is already set.");
    

    Here’s a more complete example:

    public class ApplicationContextUtils {
    
      private static final AtomicReference<ApplicationContext> context = 
        new AtomicReference<ApplicationContext>();
    
      public static ApplicationContext getContext() {
        ApplicationContext ctx = context.get();
        if (ctx == null)
          throw new IllegalStateException();
        return ctx;
      }
    
      public static boolean isInitialized() {
        return context.get() == null;
      }
    
      static void setContext(final ApplicationContext ctx) {
        if (ctx == null) 
          throw new IllegalArgumentException();
        if (!context.compareAndSet(null, ctx))
          throw new IllegalStateException();
      }
    
      public static <T> T getBean(final String name, final Class<T> type) {
        if (type == null) 
          throw new IllegalArgumentException();
        return type.cast(getContext().getBean(name, type));
      }
    
      private ApplicationContextUtils() {
        throw new AssertionError();
      }
    
    }
    

    Note that in addition to thread safety, this also provides type safety, taking advantage of the Class instance passed into the getBean() method.

    I’m not sure how you plan to use the isInitialized() method; it doesn’t seem very useful to me, since as soon as you call it, the condition could change, and you don’t have a good way to be notified.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Let say I have the following desire, to simplify the IConvertible's to allow me
I've found several jQuery syntaxes for nullifying the enter on a form. First one:
I was reading JavaScript: The Good Parts and the author mentions that JavaScript is
I'm trying to build a C++ extension for python using swig. I've followed the
I am attempting to pull some information from my tnsnames file using regex. I
This is beyond both making sense and my control. That being said here is
After having read Ian Boyd 's constructor series questions ( 1 , 2 ,
I am using a 3rd-party rotator object, which is providing a smooth, random rotation

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.