以下实用程序类是线程安全的吗? [英] Is the following utility class thread-safe?

查看:118
本文介绍了以下实用程序类是线程安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先让我们看一下实用程序类(为简单示例,删除了大多数javadoc):

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
    }
}

最后,有下面的Spring辅助bean实际调用了'setContext'方法:

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将立即调用setApplicationContext方法.假设nincompoop以前没有调用ApplicationContextUtils.setContext(),它应该在实用程序类中锁定对上下文的引用,从而允许成功调用getContext()(这意味着isInitialized()返回true).

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).

感谢您帮助我成为一个更好的程序员,StackOverflow!

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

关于, LES

P.S.我没有进入为什么我需要这个实用工具类的原因-我确实确实确实有需要从应用程序中的任何地方的静态上下文中访问它(在加载spring上下文之后,当然).

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).

推荐答案

否.这不是线程安全的.

No. It's not thread safe.

不能保证对context类变量的写入对于通过getContext()读取该变量的线程是可见的.

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

至少,将context声明为volatile.理想情况下,通过这样的调用将context重新定义为AtomicReference:

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();
  }

}

请注意,除了线程安全性之外,这还利用传递给getBean()方法的Class实例提供了类型安全性.

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

我不确定您打算如何使用isInitialized()方法.这对我来说似乎不是很有用,因为一旦您调用它,情况可能会发生变化,并且您没有很好的通知方式.

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.

这篇关于以下实用程序类是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆