• Post Reply Bookmark Topic Watch Topic
  • New Topic

synchronized in interface  RSS feed

 
Chinmay Bajikar
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have written this interface,

public interface MandateSync
{
public synchronized void doXXX();
}

On compiling it we get the following error,

MandateSync.java:3: modifier synchronized not allowed here
public synchronized void doXXX();

Why is synchronized not allowed there?
Also is there any other way to get around tht?
So tht the implementor of this interface always write a synchronized API.

Thanks,
Chinmay
^
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So far as I know, the short answer is "no". You cannot use "synchronized" in an interface and you cannot force an implementation to be synchronized. The best you can do is use the javadoc to tell the implementor what should be done.

Actually, I think "synchronized", as part of a method declaration, is a bit of an odd language feature. It is really just shorthand for "synchronized(this)" within the (instance) method, an implementation feature.

I don't know whether "synchronized" is even inherited. For instance, is it legal to override a synchronized method with a non-synchronized method? According to this (unofficial) reference, it is not inherited, which would certainly explain why you cannot put it in an interface.
[ October 01, 2004: Message edited by: Peter Chase ]
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is not inherited, because it wouldn't make much sense.

After all, what you want the implementation to be is *thread-safe* - and how to make an object threadsafe heavily depends on its implementation. Some implementations might be thread-safe without any synchronization, for some, simple synchronization at the method level might suffice, and for others you might need more elaborate constructs.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!