Mono-state is thread safe?

Tags:

From: pool0078@hanmail.net (Min-Koo Seo)
Newsgroups: comp.programming.threads
Subject: Mono-state is thread safe?
NNTP-Posting-Host: 165.132.121.251
Message-ID: <4c458db8.0406110047.29a3a946@posting.google.com>

Assume the following mono state class.

(1)


public class Mono {

  private static SomeClass c;
  
  
  public Mono() {
  
     if (c == null) {
        c = new SomeClass(...);
     }
  }
}

public class SomeClass {

  public SomeClass(...) throws Exception {
  
  }
}

Suppose that several threads concurrently instantiate Mono class. In this case,
the constructor of Mono is thread-safe? I doubt it.

I learned that initializing static field is thread-safe. So, you may recommend
that I have to make the Mono class as following:

(2)


public class Mono {
  
  private static SomeClass c = new SomeClass(...);
  
  pubilc Mono() {
  }
}

However, if Mono class is written as (2), there is no way to catch the Exception
which can be thrown from SomeClass’s constructor. So javac will raise compile error.

Of course, the following can be a workaround:

(3)


public class Mono {

   private static SomeClass c;
   
   static {
   
      try {
        c = new SomeClass(...);
      }
      
      catch(Exception e) {
        throw new RuntimeException(e);
      }
   }
   
   public Mono() {
   }
}

I think (3) is thread-safe, however catch the exception in static constructor is
too messy.

Please give a guide line of making mono-state pattern which has class as a static
field.

Regards,
Minkoo Seo

글쓴이:Alexander Terekhov (terekhov@web.de)
제목:Re: Mono-state is thread safe?

View this article only
뉴스그룹:comp.programming.threads
날짜:2004-06-11 02:55:55 PST

Min-Koo Seo wrote:
[…]
> Please give a guide line of making mono-state pattern which has class as a static
> field.

http://www.cs.umd.edu/users/pugh/java/memoryModel/jsr-133-faq.html#dcl

Or


  class Foo {

    private static Foo theInstance;

    private static final ThreadLocal tlsInstance =
      new ThreadLocal() {
          protected synchronized Object initialValue() {
            if (theInstance == null)
              theInstance = new Singleton();
            return theInstance;
          }
        };

    public static Foo getInstance() {
      return (Foo)tlsInstance.get();
    }  
  } 

regards,
alexander.

From: pool0078@hanmail.net (Min-Koo Seo)
Newsgroups: comp.programming.threads
Subject: Re: Mono-state is thread safe?
References: <4c458db8.0406110047.29a3a946@posting.google.com> <40C981AC.F42CB1AE@web.de>
NNTP-Posting-Host: 165.132.121.251
Message-ID: <4c458db8.0406110640.29c8b3ae@posting.google.com>


> class Foo {
>
> private static Foo theInstance;
>
> private static final ThreadLocal tlsInstance =
> new ThreadLocal() {
> protected synchronized Object initialValue() {
> if (theInstance == null)
> theInstance = new Singleton();
> return theInstance;
> }
> };
>
> public static Foo getInstance() {
> return (Foo)tlsInstance.get();
> }
> }

I really appreciate your posting, alexander.

I’m sorry that my question is not about ‘DCL’ or ‘SINGLETON’ pattern. Rather, I want to make my class as ‘mono state w/ thread-safe’ property.

Mono state pattern is more flexible in that (1) It can be easily subclassed. (2) Many instances can be made if I want.

The main idiom of mono pattern lies in making fields that should be shared as static, and I’m talking about ‘initializaing static fields in thread-safe way.’

I know that your codes works perfectly and I can make use of your pattern as follows:


   class Mono {
 
     private static Foo someSharedVars;
 
     private static final ThreadLocal tlsInstance =
       new ThreadLocal() {
           protected synchronized Object initialValue() {
             if (theInstance == null)
               theInstance = new Singleton();
             return theInstance;
           }
         };
 
     public void doJob() {
       ((Foo)tlsInstance.get()).job();
     }  
   } 

However, as you know, ThreadLocal is not fast enough because Thread.getCurrentThread() should be called before accessing ThreadLocal variable. I want to find a more efficient static field initialization way which is not messy and which can catch the exception.

I hope this makes my question more clearer.

글쓴이:Bruce Krawetz (bmk@wdl.lmco.com)
제목:Re: Mono-state is thread safe?
View: Complete Thread (4 글)
Original Format
뉴스그룹:comp.programming.threads
날짜:2004-06-11 13:20:03 PST

Min-Koo Seo wrote:
> <snip>
>
>> class Foo {
>>
>> private static Foo theInstance;
>>
>> private static final ThreadLocal tlsInstance =
>> new ThreadLocal() {
>> protected synchronized Object initialValue() {
>> if (theInstance == null)
>> theInstance = new Singleton();
>> return theInstance;
>> }
>> };
>>
>> public static Foo getInstance() {
>> return (Foo)tlsInstance.get();
>> }
>> }
>
> </snip>
>
> I really appreciate your posting, alexander.
>
> I’m sorry that my question is not about ‘DCL’ or ‘SINGLETON’ pattern.
> Rather, I want to make my class as ‘mono state w/ thread-safe’
> property.
>
> Mono state pattern is more flexible in that (1) It can be easily
> subclassed. (2) Many instances can be made if I want.
>
> The main idiom of mono pattern lies in making fields that should be
> shared as static, and I’m talking about ‘initializaing static fields
> in thread-safe way.’
>
> I know that your codes works perfectly and I can make use of your
> pattern as follows:
>
> class Mono {
>
> private static Foo someSharedVars;
>
> private static final ThreadLocal tlsInstance =
> new ThreadLocal() {
> protected synchronized Object initialValue() {
> if (theInstance == null)
> theInstance = new Singleton();
> return theInstance;
> }
> };
>
> public void doJob() {
> ((Foo)tlsInstance.get()).job();
> }
> }
>
> However, as you know, ThreadLocal is not fast enough because
> Thread.getCurrentThread() should be called before accessing
> ThreadLocal variable. I want to find a more efficient static field
> initialization way which is not messy and which can catch the
> exception.
>
> I hope this makes my question more clearer.

How about synchronizing the constructor itself?

Or maybe even:


         ...
 synchronized ( class() ) {
  if (c == null) {
          c = new SomeClass(...);
 } ...

자.. 이젠 포기. -_-;

Comments

2 responses to “Mono-state is thread safe?”

  1. trax Avatar

    스레드에 관한한 최고라 생각하지만…. 수년간 지치지도 않는 분인듯.
    하지만, 다소 편협한 부분도 있어요. 뉴스그룹 안본지가…참…

  2. 민구 Avatar
    민구

    네.. 저도 일부러 보는건 아니고, 궁금증이 생길때만 열어봅니다..

    물론 그분의 싸움박질(?)도 잘 알고 있고, 심지어 오라클에대해서 전문가인 Tom Kyte 역시 포스팅할 때 ‘what is ur opinion?’ 과 같은 식으로 말을 줄여썼다고 죽도록 욕하기도 하더군요.. 무척 실망스러움.

    기술이전에 사람이 되야하는데 그게 정말 쉽지 않은 일인거 같아요.

Leave a Reply

Your email address will not be published. Required fields are marked *