Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

thrading + class instance  RSS feed

 
Jigar Naik
Ranch Hand
Posts: 762
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi

i have one class C1 and other class C2
in class C2 when one instance of class C1 is being created and used the class C2 should not be able to create another instance of class C1.

so at a time one instance that is one thread.

how do i achieve that ???
 
Sunil Dixit
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I think you can do that using Thread-Local pattern.

Cheers,
Sunil Dixit
 
Jigar Naik
Ranch Hand
Posts: 762
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
whats Threadlocal pattern ?? can you exolain it in little more detail ???
 
Jeremy Botha
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

is one way.



would be another, not very elegant way.

There are several patterns, such as Singleton, which govern creating only one object. The easiest way I can thinking of creating only one object per 'session' is to use a private local variable as a reference, and only create an object if that reference is null.

J
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you really want one instance per thread, ThreadLocal is a utility class in the library. A ThreadLocal variable holds the real object you want to deal with and assures there is one per thread. It works rather like a Map where the key is the current thread.

Jeremy's example doesn't really address threading. If we make an instance of C2 and pass it to two threads, the two threads share the same instance of C1, too. Something like this would have one instance of C1 per thread:
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!