48

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.

Community
  • 1
  • 1
devsda
  • 4,112
  • 9
  • 50
  • 87

3 Answers3

89

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • I am very impressed from your answer. Can you elaborate second line of your answer. Can you help me to make interface over threadpool(see link) that I asked in my question. – devsda Jan 25 '13 at 11:40
  • 1
    I don't understand what you want to achieve, and in your other question, you've been told by several posters to forget about that and use standard thread pools instead. Anyway, whatever interface you want to create, just don't declare any method synchronized. It doesn't belong to the interface, but to the concrete implementation of the interface. – JB Nizet Jan 25 '13 at 11:45
  • Actually I made code that uses Inbuild Class. But my teacher asked me to make that by simple data structures, for better understanding. thats why I tried to build code without using inbuilt classes. If I remove `sychronized` keyword then code creates some problems, like removing tasks from list concurrently, that I don't want. So tell me any compromised path for this scenerios, that I should follow. – devsda Jan 26 '13 at 08:30
  • If you must use synchronized, then do it. Just don't put it on methods in interfaces, since it won't compile. – JB Nizet Jan 26 '13 at 15:25
11

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.

Jilles van Gurp
  • 7,927
  • 4
  • 38
  • 46
5

The simple answer is synchronized is talking about method implementation, but in interface all methods are abstract that means no implementation.

user3674202
  • 61
  • 1
  • 1