M
martin
Hi,
I've a question concerning threads and shared objects:
Assume an object of the following class SharedObject
is used by two different threads.
class SharedObject
{
private String s;
public void method (int i)
{
// preparation code (value of i never changes)
synchronized (this)
{
// do something with member s
// and use local variable i
// (value of i never changes)
}
// some other code (value of i never changes)
}
}
What I know is that access to member s should
be protected either by defining the whole method
synchronized or by putting a synchronized block
around the the critical sections of the method.
But what about the local variable i, if i use
a synchronized block and a thread is interrupted
during the preparation code?
Example:
....
SharedObject s;
....
// thread1 calls
s.method(5);
// thread2 calls
s.method(10);
....
assume thread1 is interrupted during the preparation
code and thread2 becomes active. Before thread2
finishes with s.method(10) it's interrupted and
thread1 becomes active again.
What is the value of i now (5 or 10)?
I did some tests whith many thread-instances using
a shared object and it seems, that local variables are
created separately for each thread.
Is this right?
Can i rely on this, or does it depend on the implementation of the JVM?
Is there a separate stack of local variables for each thread?
Maybe someone could explain that?
Thanks in advance!
Martin
I've a question concerning threads and shared objects:
Assume an object of the following class SharedObject
is used by two different threads.
class SharedObject
{
private String s;
public void method (int i)
{
// preparation code (value of i never changes)
synchronized (this)
{
// do something with member s
// and use local variable i
// (value of i never changes)
}
// some other code (value of i never changes)
}
}
What I know is that access to member s should
be protected either by defining the whole method
synchronized or by putting a synchronized block
around the the critical sections of the method.
But what about the local variable i, if i use
a synchronized block and a thread is interrupted
during the preparation code?
Example:
....
SharedObject s;
....
// thread1 calls
s.method(5);
// thread2 calls
s.method(10);
....
assume thread1 is interrupted during the preparation
code and thread2 becomes active. Before thread2
finishes with s.method(10) it's interrupted and
thread1 becomes active again.
What is the value of i now (5 or 10)?
I did some tests whith many thread-instances using
a shared object and it seems, that local variables are
created separately for each thread.
Is this right?
Can i rely on this, or does it depend on the implementation of the JVM?
Is there a separate stack of local variables for each thread?
Maybe someone could explain that?
Thanks in advance!
Martin