Can I make an overridden method synchronized?
Asked Answered
T

1

7

I am overriding a method from superclass, however I want this method to be synchronized. Is it allowed? What could be the alternative?

Tiresome answered 21/3, 2014 at 7:52 Comment(0)
C
8

Yes, it's allowed as it doesn't change the contract but the implementation.

Think that you could always simply add a synchronized block :

synchronized(this) { 

just at the start of the method, which would achieve about the same result. There could also be other (possibly hidden) locks deeper in the method, which makes this really part of the implementation rather than the API.

Cudbear answered 21/3, 2014 at 7:53 Comment(2)
You mean Synchronized block right? Well I should try this. Thanks.Tiresome
@Tiresome You don't need to use a synchronized block as you're allowed to make the whole method synchronized. Use a synchronized block only if you don't always need to synchronize (or if a big part of the method can be unprotected).Ramon

© 2022 - 2024 — McMap. All rights reserved.