Hal Vaughan wrote:
Being self taught, this is one thing I've always had trouble with -- I
finally get it straight in one situation and I find I'm not sure about
another.
I have a class that keeps calling an internal method. If I define variables
within the method, I would expect that they're new and clean each time I
call the method. If I'm calling from within the class, is that true? Or
should I re-initialize the variables each time the method is called? Could
someone clarify this for me?
Thanks!
Hal
Hal,
Variables that are declared within a method are unique to each method
invocation. They are not shared by a class instance or by different
threads, etc.
Variables declared at the class level are shared by a single class
instance; different threads accessing the same instance will share the
variables.
Variables declared as static at the class level are shared by everybody.
These are essentially globals.
To elucidate further:
public class Scope
{
// A static variable is shared by all
private static int instanceCount = 0;
// An instance variable belongs to the
// instance and may be accessed by multiple
// threads using the same instance
private int total = 0;
public Scope()
{
// For ultimate safety, synchronize
// access to the static variable
synchronized (Scope.class)
{
instanceCount++;
}
}
public synchronized void add(int addend)
{
// This method is synchronized to protect
// the total variable. If your program
// can guarantee that the object will not
// be modified by multiple threads, this
// is unnecessary
total += addend;
}
public void doIt(int count)
{
// No synchronization necessary
// Each invocation gets it own i
int i = count;
while (i > 0)
{
System.out.println(i);
i--;
doIt(i);
}
}
public static void main(String[] args)
{
Scope s = new Scope();
Scope t = new Scope();
s.add(2);
t.add(20);
s.add(4);
System.out.println("s.total = " + s.total);
System.out.println("t.total = " + t.total);
System.out.println("instanceCount = "
+ instanceCount);
System.out.println("s.doIt(5)");
s.doIt(5);
}
}
HTH,
Ray
--
XML is the programmer's duct tape.