Reputation: 16671
I want to know if the following workingCopy
which is a local variable to a function is THREAD SAFE
private static final Lock lock = new ReentrantLock();
private final List<String> Ids= new LinkedList<String>();
private void foo(){
List<String> workingCopy = null;
final boolean locked = lock.tryLock();
try
{
workingCopy = new LinkedList<String>(Ids);
Ids.clear();
}
catch (final Exception e)
{
log.debug(e.toString());
}
finally
{
if (locked)
{
lock.unlock();
}
}
for (final String copy: workingCopy)
{ /// }
}
Or is there a better way to do the following
Upvotes: -1
Views: 559
Reputation: 1149
when you are creating multiple threads each will create own stack.they never share each other.local variable remains here so they are thread safe.
when you sharing objects they are pass by reference they point to same memory address so they must be in critical session area, must provide external synchronisation. like @icza mentioned ,in your problem its thread safe String is immutable
Upvotes: 0
Reputation: 418645
Is a local variable inside a java function thread safe
The question involves multiple threads accessing the local variable:
Local variable's value:
Local variables are not visible outside of the method or block in which they are declared. So only "locally" started threads come into play. Locally started threads can only access local variables if they are declared final
, but then the variable's value cannot be changed. So the variable's value (either primitive or reference) is safe.
The Object referenced by the local variable:
If the local variable references an immutable object (such as String
), then again you have no problem as it can't be changed (that's the definition of immutable). If the local variable references a mutable object (such as LinkedList
), then without synchronization it won't be thread safe just like any other object stored in instance or class attributes - no difference.
The referenced object may passed to other methods as parameter, and then it is "out of your hands". The constructor of the object might also do this so even if you don't pass it around, you cannot be sure.
Back to your question
Your workingCopy
variable is not accessed by multiple threads, so there is no danger, but the answer to the original question is: it is not thread safe becase it is not immutable.
Upvotes: 1
Reputation: 7128
Yes, only shared variables (instance data, static data) are to be under mutual exclusion, local variables are created on stack, and on every call, created on different memory locations, so no point of sharing one with another
Upvotes: 5