aspose file tools
The moose likes Threads and Synchronization and the fly likes Multi-Threaded program using a singleton object Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Multi-Threaded program using a singleton object" Watch "Multi-Threaded program using a singleton object" New topic
Author

Multi-Threaded program using a singleton object

d jones
Ranch Hand

Joined: Mar 13, 2006
Posts: 76
Hi,

This is a question about a multi-threaded program.

Imagine we have a singleton class and we call an instance of it from
2 different threads.

Both threads will now have a reference to the same object in memory.

If the singleton class has a mehod which isn't synchronized and it accepts
2 numbers and just adds them.

If we call this method from Thread 1 and pass in 2 numbers
and also call it from thread 2 and pass in 2 different numbers.
This method doesn't use any class variables and only works on the parameters passed in.

Will the 2 calls to this method always operate independently of each other?
Or would there ever be a chance where the 2 numbers passed in from thread 1 and thread 2 could get confused and add the first parameter from thread 1 to the second parameter from thread 2?

Many Thanks,
Dan
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 16815
    
  19

Originally posted by d jones:
Hi,
If the singleton class has a mehod which isn't synchronized and it accepts
2 numbers and just adds them.

If we call this method from Thread 1 and pass in 2 numbers
and also call it from thread 2 and pass in 2 different numbers.
This method doesn't use any class variables and only works on the parameters passed in.

Will the 2 calls to this method always operate independently of each other?
Or would there ever be a chance where the 2 numbers passed in from thread 1 and thread 2 could get confused and add the first parameter from thread 1 to the second parameter from thread 2?


In the condition that you described, the two threads will operate independently of each other.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Multi-Threaded program using a singleton object
 
Similar Threads
Passed with 148 / 155
Passed Part One with 87%
Locking Schemes: Strategic View
Database Connection Singleton
Threads 003: Server-Side Strategies