Reputation: 6148
i have Static Method and it is calling another static method within itself.
for example :
public List<Object> static first(int id){
List<Object> list=new ArrayList<Object>();
list.add(a);
list.add(b);
list.add(c);
//calling another static method
second(id,list);
return list;
}
public String static second(int id,List<Object> listRef){
listRef.add(a);
listRef.add(b);
listRef.add(c);
}
My Question IS:
Multiple thread is calling public static method first(int id);
with different id.
This is thread safe way Or Not? As i am declaring arrayList within method And i thing it's reference may share by other threads.
Problem is That Array Is stored in heap memory not in Individual Threads Stack.So i think sharing of Array reference by many threads may happen.
Upvotes: 1
Views: 191
Reputation: 9741
Each thread
gets its own copy of the method
. Static methods are just methods which belong to the Class
instead of object. As long as you are not manipulating any shared variables
or resources
, it is thread safe.
Upvotes: 2
Reputation: 593
what kind of objects are a,b & c? As this is just adding of stuff into a list and then calling another static method, I do not see any issues
So yes its thread safe..
Upvotes: 1
Reputation: 22166
It is thread safe as long as you don't call second
directly from each thread. To that end, you should consider making second
a private method.
Upvotes: 1
Reputation: 73568
Yes, it is thread-safe. Your ArrayList is a local variable and is not shared by threads (unless you explicitly do something to share it).
In this case every thread will simply have their own ArrayList.
Upvotes: 10