shu
shu

Reputation: 115

which method should be synchronized in delegation pattern in Java

In delegation pattern, if I have a concrete class and a wrapper class:

class Wrapper {
    Concrete concrete = new Concrete();
    void fn() {
        concrete.fn();
    }
}

class Concrete {
    void fn() {
        ...
    }
}

If the method fn() should be synchronized, then where should I put the synchronized keyword? If we assume Concrete::fn() will only be called by Wrapper::fn(), is it true that either place is fine?

Upvotes: 1

Views: 137

Answers (2)

TheEllis
TheEllis

Reputation: 1736

Generally the rule is to synchronize as little logic as possible, so if it's a choice between Concrete.fn() and Wrapper.fn() then you should synchronize Concrete.fn(). You also may want to look at whether you need to synchronize the whole method or a smaller block of logic within the method.

Also if the requirement is to always have Concrete.fn() synchronized and you synchronize Wrapper.fn(), then any future code that calls Concrete.fn() will also need to be synchronized. If you synchronize Concrete.fn(), you have ensured you don't forget about the synchronization requirement for any future implementations.

Upvotes: 1

J. Dow
J. Dow

Reputation: 563

I see multiple possible issues with using synchronized on Wrapper:fn():

  • synchronized should be used sparingly: only lock those parts, that need to be synchronized.

  • the locking mechanism should be a concern of the concrete implementation - if possible (you may have a implementation which don't need to be synchronized)

Upvotes: 2

Related Questions