I'm new to Java, so pls excuse if answer to below simple case is obvious.
class A{
public void foo(Customer cust){
cust.setName(cust.getFirstName() + " " + cust.getLastName());
cust.setAddress(new Address("Rome"));
}
}
I've a Singleton object (objectA
) created for class A
.
Given I don't have any class variable, is it thread safe if I call objectA.foo(new Customer())
from different threads?
What if I change foo to static and call A.foo(new Customer())
from different threads?
is it still thread safe?
Given I don't have any class variable, is it thread safe if I call objectA.foo(new Customer()) from different threads?
Of course it is. Your foo()
method doesn't change any state of the A
object (since it doesn't have any) and the object you pass, new Customer()
, as an argument to the method is not available to any other thread.
What if I change foo to static and call A.foo(new Customer()) from different threads? is it still thread safe?
As long as you don't have any mutable static
state, you're still good.
Yes, it will be thread-safe IF you call foo(new Customer())
from different threads. But this is only because each time you call new Customer()
you are making a new (and therefore different) Customer object, and all that foo does is alter the state of the Customer that is passed to it. Thus these threads will not collide, because even though they are calling the same method, they will be manipulating different customers.
However, if you were to create a customer variable first
Customer bob = new Customer()
and then call foo(bob)
from two different threads, it would not be thread safe. The first thread could be changing the address while the second thread is changing the name, causing inconsistent behavior and / or corrupt data.
If you want to make this method truly thread-safe, just declare the method synchronized:
public synchronized void foo(Customer cust) {...}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With