• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Singleton and Multiple threads

 
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I understand that a Singleton can only have one instance at any given time.

My question is can multiple threads use the same instance? If so what are the thread-safety issues with this? specifically:

1- Would class static variables be shared amongst the threads?
2- Would local variables to non staic methods be shared amongst the threads?



The reason I ask this is because I have designed a Data Access Facade Layer as a singleton. During instantiation it would initialize the data source, as I don't want it to be initialized more than once. Then I have member methods (instance methods) which perform insert, select, update ...etc to the database. Each of those methods gets its own connection, statement, resultset ...etc

Was just wondering if the above has any thread safety issues as it will be used by multiple threads.


Thanks for replying in advance

P.S. The above class will be running in Tomcat and called from a servlet, not sure if this is relevent.
 
Sheriff
Posts: 28411
102
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here's the thread tutorial that will probably answer many of your questions:

http://java.sun.com/docs/books/tutorial/essential/threads/

Yes, class variables can be accessed by all threads. Likewise instance variables. Local variables are not shared among all threads (but it's possible for them to reference objects that are being accessed by several threads, so you still have to take care.)
reply
    Bookmark Topic Watch Topic
  • New Topic