Aymer
Aymer

Reputation: 331

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?

Upvotes: 4

Views: 140

Answers (3)

James Dunn
James Dunn

Reputation: 8274

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) {...}

Upvotes: 3

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28538

thread safety is required where a function is accessing a static shared variable. like a function which is updating a shared document, so if two thread in parallel updated changes of one thread will get ignore. Or a static variable which is shared across the application, singleton object.

Above are some situation where thread safety required In your case you are not updating any shared resource so this is a thread safe.

Upvotes: 1

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279940

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.

Upvotes: 5

Related Questions