Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread and mutable params

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.

  1. Given I don't have any class variable, is it thread safe if I call objectA.foo(new Customer()) from different threads?

  2. What if I change foo to static and call A.foo(new Customer()) from different threads? is it still thread safe?

like image 712
Aymer Avatar asked Jan 12 '23 12:01

Aymer


2 Answers

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.

like image 74
Sotirios Delimanolis Avatar answered Jan 14 '23 01:01

Sotirios Delimanolis


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) {...}
like image 44
James Dunn Avatar answered Jan 14 '23 01:01

James Dunn