[concurrency-interest] Thread safe or not ?

David Holmes dholmes at dltech.com.au
Fri Sep 23 01:35:10 EDT 2005


Hanson,

SystemParameter.K is a static final long value that is initialized during
static initialization from a newly constructed - and hence otherwise
inaccessible - object. So as it stands it is always threadsafe to access it,
as static initialization is itself threadsafe.

I don't know why the bean variable is volatile if it is only accessed during
static initialization. So it may not be minimal synchronization.

However the comment:
        // This part can be replaced by accessing an IoC framework
        // such as Spring to retrieve an externally configured
        // SystemParameterBean instance.

is not correct. If you use an externally configured bean object to
initialize K then you need to be guaranteed that that beans k field has been
correctly set and may not be concurrently set while being read from getK. As
these are long values then atomicity of reads/writes does not apply and you
may read a garbage value.

Hope that helps.

David Holmes

  -----Original Message-----
  From: concurrency-interest-bounces at cs.oswego.edu
[mailto:concurrency-interest-bounces at cs.oswego.edu]On Behalf Of Hanson Char
  Sent: Friday, 23 September 2005 3:19 PM
  To: concurrency-interest at altair.cs.oswego.edu
  Subject: [concurrency-interest] Thread safe or not ?


  Assuming JDK5, is the following code always thread safe when
SystemParameter.K is concurrently accessed  ?  If so, is the synchronization
used in the code minimal ?  If not, why not ?

  Thanks in advance.

  Hanson

  public class SystemParameter {
      private static volatile SystemParameterBean bean = init();
      public static final long K = bean.getK();
      static {
          bean = null;    // hint to GC
      }
      private static SystemParameterBean init() {
          // This part can be replaced by accessing an IoC framework
          // such as Spring to retrieve an externally configured
          // SystemParameterBean instance.
          SystemParameterBean bean = new SystemParameterBean();
          bean.setK(20);
          return bean;
      }
  }

  public class SystemParameterBean {
      private long k;

      public long getK() {
          return k;
      }
      public void setK(long k) {
          this.k = k;
      }
  }

-------------- next part --------------
An HTML attachment was scrubbed...
URL: /pipermail/attachments/20050923/223de60f/attachment.htm


More information about the Concurrency-interest mailing list