When I use synchronized
on a method in an interface, the compiler emits an error. Can you tell me why this happens?
What is the reason (logically) that synchronized
cannot be applied to a method on an interface
?
I tried to make an Interface over Threadpool in this link.
Help me to make Interface in my above code.
Because synchronized
is an implementation detail. One implementation of the method might need to make the method synchronized, whereas another one might not need it. The caller doesn't care whether the method is synchronized or not. It's not part of the contract, which tells what the method does. Which synchronization technique, if any, is used to fulfill the contract is irrelevant.
synchronized is an implementation detail and doesn't belong in an interface.
You could have all sorts of implementations that might be threadsafe that don't involve the use of the keyword synchronized.
You might consider using some annotation to indicate the intention that implementations should be thread safe. For example http://jetbrains.dzone.com/tips/concurrency-hot-try-jcip explains how to use the JCIP concurrency annotations.
BTW. Instead of using synchronized, you may want to get cozy with the java concurrent framework. Using low level constructs like synchronized directly is considered a bit of an anti pattern these days.
The simple answer is synchronized is talking about method implementation, but in interface all methods are abstract that means no implementation.