Sing Sandibar
Sing Sandibar

Reputation: 714

Thread safety and method arguments

I have a class Helper with one single method int findBiggestNumber(int [] array) and no instance variables.

If I make an object Helper h = new Helper(); and let 10 different threads use that object's only method findBiggestNumber to find their array's biggest number, will they interfere with each other? My fear is that for example thread-1 starts calculating its array's biggest number when the parameter in findBiggestNumber is referencing an array in for example thread-8. Could that happen in my example?

Upvotes: 1

Views: 509

Answers (2)

b4hand
b4hand

Reputation: 9770

Without your implementation of findBiggestNumber, it's impossible to say if it is thread safe since you could be mutating the array passed as an argument. If that is true, and you pass the same array to multiple threads, then there is potentially a race condition; otherwise, it is thread safe.

findBiggestNumber could also be modifying global or static data which would also make it thread unsafe.

Upvotes: 0

Dermot Blair
Dermot Blair

Reputation: 1620

No the problem you described could not happen. As your Helper class has no members, it is thread safe.

Thread safety issues arise when mutable (changeable) data is shared between multiple threads. However in your example, Helper does not contain any data (i.e. variables) that will be shared between multiple threads as each thread will pass their own data (int[] array) into Helper's findBiggestNumber() method.

Upvotes: 1

Related Questions