There is a public calculate() method a singleton class. If there are 2 threads to call the calculate() at the same time. I wonder if one thread must wait until another thread executing calculate() is finished?
If it is not a singleton class. I changed the mthod to static public calculate(). I still wonder if one thread must wait until another thread executing calculate() is finished?
Thank you!
Chaohua
Jeff Albertson
Ranch Hand
Joined: Sep 16, 2005
Posts: 1780
posted
0
Whether or not you have a singleton, nothing automatically waits without some synchronization code. And don't change a method that should not static to be static! [ January 03, 2006: Message edited by: Jeff Albrechtsen ]
if you don't put volatile key word for the variable, thread will have a their own local copy even though variable is static when threads are not synchronized. [ January 03, 2006: Message edited by: Jignesh Patel ]
chaohua wang
Ranch Hand
Joined: Dec 22, 2002
Posts: 62
posted
0
Thank you, guys,
I am still confused about static method. I know a static varialbe has only one in memory. I think static method also has only one in memory, can not make a copy for the threads. So 2 threads can only call it one by one until one calling is done.
Ernest Friedman-Hill
author and iconoclast
Marshal
Originally posted by Jignesh Patel: if you don't put volatile key word for the variable, thread will have a their own local copy even though variable is static when threads are not synchronized.
No. Some writes to a single non-volatile variable may be hidden from other threads for some period of time. You absolutely cannot look upon this as a feature you depend on for program correctness!
I think static method also has only one in memory, can not make a copy for the threads.
In general, there is only ever a single copy of the code for any method, static or not (barring complications like multiple class loaders, which we'll ignore for the moment.) But this does not stop multiple threads from using that code at the same time, any more than you and a friend have any problem both looking out a single window at the same time.
Only the "synchronized" keyword can mark a method so that only one thread can use it at a time.
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
posted
0
Extending on what Ernest said, every method call gets its own stack space for local variables and the like - whether they are in the same thread (recursion) or not.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.