Joro Seksa
Joro Seksa

Reputation: 1583

Proper synchronization use in java

I have a list of Firm objects.

Each object has few properties which never change after initialization of the object. One of the propeties is a list holding User objects which may grow or shrink over time.

i want for each Firm object to know how many User objects it has.

So my question is should i do it like this

List<Firm> firmsList = getFirmsList();

for(int i=0; i<firmsList.size(); i++)
{
    Firm firm = firmsList.get(i);
    synchronized(firm)
    {
         int usersCount = firm.getUsers().size();  
    } 
}

or should i synchronize the User object too? (Currently the list of User objects is accessed only within the Firm object )

Upvotes: 0

Views: 39

Answers (2)

barthel
barthel

Reputation: 950

Add a convenience method like Firm#getUserSize() or return a unmodifiable list java.util.Collections.unmodifiableList(List<? extends T>) to become a immutable Firm.

Depending on working code around Firm#getUsers() may return a synchronized Collection instead.

Upvotes: 0

Jesper
Jesper

Reputation: 206836

You say that Firm is immutable (its properties will never change after initialization of the object). If that's the case, then you do not need synchronization at all.

Upvotes: 1

Related Questions