Reputation: 1756
When I am using static properties in a static java method this method is not any more thread save.
What about using a static method inside my static java method? Will this mess up my values?
Here some examples:
I guess this isn't thread save at all:
public static String staticText;
public static Integer staticNumber;
public static String doA(String input1, Integer input2){
staticText = input1;
staticNumber = input2;
return staticText + staticNumber;
}
This would be thread save:
public static String doB(String input1, Integer input2){
return input1 + input2;
}
And now my question, what's about this method:
public static String doC(String input1, Integer input2){
return doB(input1, input2);
}
Is the method doC still thread save? I just want to make sure that the method call to doB inside doC doesn't brake the thread safety.
Upvotes: 0
Views: 74
Reputation: 16209
Some general rules of thumb that I think will help you:
As long as you only use local variables all methods (static or non-static) will be thread safe because the local variables are instantiated anew for each invocation and thus cannot interfere between threads.
If you create a new instance of a class as a local variable, then accessing instance fields of that instance will also be thread safe.
If you write to a static field then that is not thread safe because static fields can be accessed from anywhere within the same class loader (generally that means anywhere from within the running JVM). Writing to a static field will make it possible that another thread writes to it at the same time which can cause strange effects.
You really should try to understand what the terms in your question mean. The way you ask it now indicates you do not grasp the concepts. You can find a lot of information about this online, for example:
Upvotes: 0
Reputation: 1075039
static
and thread safety have nothing whatsoever to do with each other. The one defines whether a field is related to the class as a whole (static
) or to instances (not static
). The other relates to thread concurrency and/or serialization.
If the static method you're calling from another static method does something that may be problematic if done concurrently by multiple threads, you'll need to deal with that in the usual ways (synchronizing, using the various features of java.util.concurrent
, etc.). The fact the method is static
, and the fact it's called from another static
method, has nothing to do with it at all.
Upvotes: 5