dcsimg
Instance variables in static methods.
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Travis_T
Posted On:   Thursday, September 27, 2001 09:32 PM

This may be a dumb question, because I thought that instance variables in static methods are scoped to the specific instance of that method call. This then would make them thread safe, right? However, I came across an error that might be explained by instance variables within a static method actually being static to the method and shared across all threads. Are instance variables in a static method thread safe? public static nothing(String b){ String it = null; it = b; System.out.println(it); } Could two different classes calling nothing("input") simultaneously step on each other?    More>>

This may be a dumb question, because I thought that instance variables in static methods are scoped to the specific instance of that method call. This then would make them thread safe, right? However, I came across an error that might be explained by instance variables within a static method actually being static to the method and shared across all threads.


Are instance variables in a static method thread safe?


			
public static nothing(String b){
String it = null;
it = b;
System.out.println(it);
}


Could two different classes calling nothing("input") simultaneously step on each other?

   <<Less

Re: Instance variables in static methods.

Posted By:   Jai_Chhugani  
Posted On:   Friday, September 28, 2001 11:29 AM

You can only access static variables in a static method. (The term instance variable is confusing). And static variables are shared by all instances of a class. So if multiple threads call a static method they could step over each other. The way to avoid this is to use something like --

class Foo {
private static String classShared;
public static void method(String arg)
{
synchronized(Foo.class) {
classShared = arg;
}
}
}
About | Sitemap | Contact