How can I ensure that an overridden method is synchronized - java

I have a class of common code that is thread safe.
One of the methods in that class is abstract and needs to be overridden for different implementations.
I need to ensure or at least flag to other developers that all implementations of this method need to be thread-safe.
What is the best way to do this?
Is there a keyword or annotation to this effect?
I have already tried abstract synchronized but that combination of keywords is not allowed.

You can't do it directly. One thing you can do is have the method be concrete, but invoke an abstract method:
public synchronized final void foo() {
doFoo();
}
protected abstract void doFoo();
That way, doFoo() will always* be invoked under the synchronization established by foo().
* unless someone invokes it directly, so you should name and document it to make it clear that they shouldn't.

From Synchronized method in subclass
Synchronized is the implemenation detail of a method.
You can override a sync method with a method without declaring that as sync and vice versa.
The same holds true for the overloading also.
You can also have a look at, A synchronized method in the superclass acquires the same lock as one in the subclass.

This link to the JLS confirms that we can't mix abstract and synchronized.
Though much weaker than a keyword or standard annotation, but stronger than documentation: perhaps try a Marker interface?
... provides a means to associate metadata with a class where the
language does not have explicit support for such metadata.
This is a stretch, but might help, in that the derived class makes a declaration (edit: new example tests the declaration):
interface EatMethodIsThreadSafe {}
abstract class Animal {
public Animal() {
if (! (this instanceof EatMethodIsThreadSafe)) {
throw new IllegalArgumentException("eat method must be thread safe");
}
}
public abstract void eat();
}
public class Bear extends Animal implements EatMethodIsThreadSafe {
public synchronized void eat() {}
public static void main(String...args) { Bear b = new Bear(); }
}

Related

How to ensure Thread safety of subclass' methods from a superclass?

I attended an interview and I was asked to design a class for the following requirement.
Assume I have a class A and it can have any number of children, i.e., subclasses.
The class A has a method called doSomething() which is synchronized. The requirements are :
It is mandatory that all subclasses of A override the doSomething() method.
All subclasses' overriden doSomething() method must be Thread safe in nature.
All subclasses' must have the provision to implement their own logic for their doSomething() method implementations.
Class A's constructor is upto me(the designer) to decide how to implement.
The designer has no control on how many subclasses would be created or how they would be created,i.e., the designer can only write code for the superclass only.
I suggested to make the class abstract and also the doSomething() method abstract. This would imply classes extending my class necessarily provide their own doSomething() method.
However, I could not answer as to what exactly in my class A would ensure Thread safety for my child classes and that too just for the doSomething() method.
He gave a hint though, he said the trick is to be done in A class' constructor.
Any ideas?
After a very long research I found out that synchronization cannot be inherited if the method is overridden and without explicitly adding the keyword synchronized in the the overridden method's signature!!
And because this issue is mainly addressed to prevent other users (i.e. developers) from violating the use of your class (as they are extending it).
I came up with a way to work around it by availing of the Reflection class in Java.
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class A {
public A(){
assertSynch("doSomething");
}
// method to assert a particular method is synchronized in the subclass
private void assertSynch(String methodName) {
Class<? extends A> subclass = this.getClass(); // this returns the subclass
Method[] methods = subclass.getDeclaredMethods();
for (Method meth : methods) { // loop through the methods in subclass
if(meth.getName().equals(methodName)) { // when it reaches your method
String modVal = Modifier.toString(meth.getModifiers()); // get its modifier
if(!modVal.contains("synchronized")) { // check if it contains the keyword "synchronized"
try { // if not -> throw an Exception with clear message about the reason and exit
throw new Exception(methodName +
" must be synchronized to ensure class thread safety!");
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
}
}
}
public synchronized void doSomething() {}
}
public class B extends A{
public B() { } // it implicitly calls the superclass constructor
#Override
public void doSomething() { } // it will make the program to throw the above exception
}
I would say better to make the base class doSomething method public final synchronized (final to make sure subclass can't override it) and call another protected abstract method. public synchronized final void doSmoething ensure that any call to doSomething method will be synchronized / thread safe and doSmoethingImpl abstract method will provide flexibility to give the method own definition in a subclass.
abstract class A {
public synchronized final void doSmoething() {
doSmoethingImpl();
}
protected abstract void doSmoethingImpl();
}
class B extends A {
#Override
protected void doSmoethingImpl() {
// definition in class B
}
}
Note: Above solution will not directly satisfy your point 1 but doSmoethingImpl() will give you scope to achieve the similar functionality indirectly.

Implementing a method that is present in both interface and abstract class in java

I am trying to understand what happens if a method is present in both an abstract class and an interface. Below, I posted a scenario that gives you a clear idea of what I am referring to.
interface act
{
void read();
}
abstract class enact
{
void read() {
System.out.println("hello");
}
}
public class second extends enact implements act
{
public void read() {
// does method read() correspond to Interface or abstract class?
}
}
Surprisingly,there is no compilation error when I write this code. Any suggestions would be highly helpful.
I am just curious to know whether the method read() relates to interface or abstract class
Or neither, really. It depends on the apparent type in the context where you actually use it. E.g. whether you do
enact example = new second();
or
act example = new second();
Both allow you to compile the code:
example.read();
because the read() method is defined in both apparent types, act and enact. But in both cases, it's the read() definition defined in the "second" class that really matters. That's what gets executed.
I am not sure what kind of problems you expect so I will try to show that there are no problems with this scenario.
You are calling methods from references like:
Second sc = new Second();//you should name your classes with upper-case
sc.read();
and this will execute code from Second class because that is type of object stored in sc reference (this is how polymorphism works - or to be precise dynamic binding).
You could also create instance of Second class and pass it to reference of Act type (all types in Java should start with upper-case, including interfaces, and enums) like
Act act = sc;// or Act act = new Second();
act.read();
Since read() method is polymorphic (only final, private or static methods aren't) at runtime JVM will look for code to execute in class which instance is stored in art interface, so since it is instance of Second class code of read() from that class will be executed (if you would not override it in that class code inherited from Enact abstract class will be executed).
My understanding is as follows. Let's start by considering a simpler setting. Class Second is abstract, and implements two interfaces, Act and React. Both interfaces declare a non-default void read() method. In this case, Second inherits multiple declarations of the same method, no implementation, and the compiler is happy (JLS 8.4.8.4).
interface Act {
void read();
}
interface React {
void read();
}
public abstract class Second implements Act, React {
}
If one or both interface methods are default methods, we get a compiler error (JLS 8.4.8.4, 9.4.1.3), unless Second inherits an abstract read() method from a superclass (JLS 8.4.8.4), as in the following scenario, where Second actually ends up inheriting three read() methods.
interface Act {
default void read() {}
}
interface React {
void read();
}
abstract class First {
abstract void read();
}
public abstract class Second extends First implements Act, React {
}
In the absence of such a superclass, Second must give an implementation of read(), thus preventing the inheritance of the conflicting methods (JLS 9.4.1.3). Of course, Second must do the same if all interface methods are abstract and we don't want to declare the class itself as abstract.
If Second does give a concrete implementation of read(), as in the following example, this method does not "relate" to one or the other of the interface methods: it simply overrides, and prevents the inheritance of, any and all superinterface methods with the same signature -- more precisely, with a signature which the signature of read() in Second is a subsignature of -- as if there were only one such method (JLS 8.4.8.1). (In some corner cases it may be impossible for a method to simultaneously satisfy all the contracts of the methods it is meant to override. James Gosling offers a nice example of this in section 4.3.2 of his -- and colleagues' -- The Java Programming Language.)
interface Act {
void read();
}
interface React {
void read();
}
public class Second implements Act, React {
#Override
public void read() {}
}
Your case is similar.
interface Act {
void read();
}
abstract class Enact {
void read() {}
}
public class Second extends Enact implements Act {
#Override
public void read() {}
}
The only real difference is that read() in Enact is a concrete method (the fact that Enact is abstract is irrelevant), but things don't change very much: the declaration in Second overrides both read() in Act and read() in Enact (JLS 8.4.8.1). At the same time, it is a valid implementation of the Act interface, so there is really no problem here.
Note that this code would compile even if Second did not override read(): Second would inherit read() from Enact, and the inherited method would be considered as an equally valid implementation of Act (JLS 8.4.8, 8.4.8.1, 9.4.1.3).

Java 8 default method readability

Java 8 introduces the concept of default methods. Consider the following interface with a default method :
public interface IDefaultMethod {
public abstract void musImplementThisMethod();
public default void mayOrMayNotImplementThisMethod() {
System.out.println(" This method is optional for classes that implement this interface ");
}
}
And a class that implements this interface :
public class DefaultMethodImpl implements IDefaultMethod {
#Override
public void musImplementThisMethod() {
System.out.println("This method must be implementd ");
}
#Override
public void mayOrMayNotImplementThisMethod() {
// TODO Auto-generated method stub
IDefaultMethod.super.mayOrMayNotImplementThisMethod();
}
}
I have a question about the readability of the following call in the mayOrMayNotImplementThisMethod :
IDefaultMethod.super.mayOrMayNotImplementThisMethod();
I understand that the reason for explicitly specifying the interface name in the above call is to avoid confusion in case multiple interfaces implemented by the class have the same method. What I don't understand is the meaning of the super keyword in this context. When we say IDefaultMethod.super, what exactly are we referring to here? Wouldn't IDefaultMethod.mayOrMayNotImplementThisMethod() be more readable than IDefaultMethod.super.mayOrMayNotImplementThisMethod()? Removing the super keyword makes it more readable at the cost of distinguishing between a static or non static method call.
I will try to contribute to the discussion by following my own reasonings about this.
Using Classes
First, let's see how this work with simple Java classes:
class Barney {
void foo() { System.out.println("Barney says foo"); }
}
class Fred extends Barney {
#Override void foo() { super.foo(); }
}
In this case if we invoke the method foo in a Fred instance it will ask for the implementation of the foo method in its super class and execute that one.
Evidently, none of these others would work:
#Override void foo() { foo(); } //means this.foo() so infinite recursion
#Override void foo() { Barney.foo(); } //means a static method
There is a third configuration that we could do:
class Barney {
void foo() { System.out.println("Barney says foo"); }
class Fred extends Barney {
#Override void foo() { Barney.this.foo(); }
}
}
In this case if we invoke foo in a instance of Fred, since this instance would have a bond with its enclosing instance, this invocation would invoke the foo method in the enclosing instance of Barney.
For instance
new Barney().new Fred().foo();
So, the use of Barney.this here is used to navigate between instances in an inner/outer relation.
Using Interfaces
Now let's try to repeat the same ideas with interfaces.
interface Barney {
default void foo() { System.out.println("Barney says foo"); }
}
interface Fred extends Barney {
#Override default void foo() { Barney.super.foo(); }
}
As far as I can tell, this is exactly the same thing as with classes, it is just that in this case since an interface can inherit from more than one interface we simply qualify the super keyword with the name of the interface we are targeting in this case.
The meaning is the same, we want to invoke the "implementation" of the foo method in the super interface explicitly named.
As with classes, the following would not work:
#Override default void foo() { super.foo(); } //can't be sure of which interface
#Override default void foo() { this.foo(); } //infinite recursion
#Override default void foo() { Barney.foo(); } //static method
#Override default void foo() { Barney.this.foo(); } //not an inner class relation
So, the logical choice here is Interface.super.method().
A question here would be whether we cab ever have a use case like Interface.this.method when using interfaces.
Not really, because interfaces represent a static context, therefore there is never a concept like that of inner classes between interfaces. So this is never possible.
interface Barney {
default void foo() { System.out.println("Barney says foo"); }
interface Fred extends Barney {
#Override default void foo() { Barney.this.foo(); }
}
}
Basically, this is not possible because the code above does not mean that an instance of Fred would need to exist within the context of an instance of Barney. This is just a static inner interface and instances of it can exist independently of any instances of the parent interface.
So, that's why this would not be a good choice.
So, as you can see, after all this the use of super kind of makes sense, or at least I hope I have explained myself well enough to convey that idea.
This is simply an extension to default methods of the usual approach to accessing members of superclasses (JLS 15.11):
The form T.super.Identifier refers to the field named Identifier of the lexically enclosing instance corresponding to T, but with that instance viewed as an instance of the superclass of T.
Essentially, there can be ambiguity about which member is being referred to when a class has more than one ancestor (whether because of default methods or just because it has multiple superclasses in a hierarchy). The super keyword is the analog of Outer.this in an inner class; it means that you want to get "this, but the stuff I would see inside the body of that superclass instead of the member inside this subclass".
super refers to a class or interface you inherit from. It is means you want to call a method ignoring the fact it has been overridden.
If you used this you would be referring to this class (or a sub-class) and thus have infinite recursion.
Java 8 interfaces also have static methods.
If you say,
IDefaultMethod.mayOrMayNotImplementThisMethod();
Then it is a way to call static method, which also seems correct as it is similar to how we access static members of class.
For default method, if 'super' is not used then they might have used 'this', which does not make sense as 'this' belongs to class where we are making method call.
My opinion is, you are correct as it does not provide good readability but seems it is as per language design.

How to hide method of parent interface in Java?

I have 3 classes.
public interface Operation {
void move();
void delete();
void search(String criteria);
}
public abstract class AbstractOperationProcessor implements Operation {
public void move() {
// some logic
}
}
public class DailyMailProcessor extends AbstractOperationProcessor{
// need to hide this method because I don't want to provide them to customer
public void delete() {}
public void search(String criteria) {}
}
What I need is to hide methods delete() and search(String) from API. How can I do it without changing interface Operation and abstract class AbstractOperationProcessor?
You cannot. The best you can do is implement stubs that throw something like NotImplementedException and document this fact.
I would use this as an opportunity to examine the definition of the top-level interface. If you need to hide some of its methods then the real problem may be that it aggregates unrelated functionality. You may need to split it into two separate interfaces.
Remember, you can "inherit" (i.e. implement) multiple interfaces.
As the other answers already stated: You cannot hide a method of a superclass. There is also a good reason that you cannot do this: Polymorphism allows you to pass any object of a subtype where an object of a supertype is needed. In your case, if you have a method
void foo(Operation op){op.delete()}
you can call
foo(new DailyMailProcessor())
As you can see, foo does not know the exact type of op, but because delete is in Operation's interface, the method delete can be called.
If you happen to want to remove some methods from a subtype's interface, you are probably not implementing a behavioral subtype! I suggest you have a look at the Liskov Principle, which is one of the fundamental principles in object oriented programming.
If, what you have is not a behavioral subtype, you are wrongly trying to achieve code reuse by inheritance. You should use composition instead. Favor composition over inheritance (Item 16, Effective Java). The reason to favor composition in your case is obvious: You do not have to throw an UnsupportedOperationException (as mentioned in the other answers) and hereby gain static safety.
Edit: To clarify what I mean when telling you to use composition: Instead of having class DailyMailProcessor extending Operation, give it an member variable of type Operation and forward calls to the methods you want to support to the member variable.
public interface Operation {
void move();
void delete();
void search(String criteria);
}
public class DailyMailProcessor {
private Operation op;
public DailyMailProcessor {/*instantiate op*/}
void move() {op.move();}
}
You cannot do that. Every method declared in the interface should be implemented by the class. What you can do is you just implement those methods but do not give any definition to it.
Edit:
As suggested in the comments, UnsupportedOperationException might be a better choice.
Original answer:
There is the IllegalStateException just for that. Just make all the methods you don't want to implement throw that. Just do:
public class DailyMailProcessor extends AbstractOperationProcessor {
public void delete() {
throw new IllegalStateException();
}
public void search(String criteria) {
// do something useful here
}
}
the best solution that handle your probleme, if, and only if you want to have it in an elegante way, is to use a component system and it would look some this like that:
abstract class Component {
abstract void perform();
}
abstract class Move extends Component {
void perform() { ... }
}
class AbstractOperationProcessor {
List<Component> components;
...
}

Overload and hide methods in Java

i have an abstract class BaseClass with a public insert() method:
public abstract class BaseClass {
public void insert(Object object) {
// Do something
}
}
which is extended by many other classes. For some of those classes, however, the insert() method must have additional parameters, so that they instead of overriding it I overload the method of the base class with the parameters required, for example:
public class SampleClass extends BaseClass {
public void insert(Object object, Long param){
// Do Something
}
}
Now, if i instantiate the SampleClass class, i have two insert() methods:
SampleClass sampleClass = new SampleClass();
sampleClass.insert(Object object);
sampleClass.insert(Object object, Long param);
what i'd like to do is to hide the insert() method defined in the base class, so that just the overload would be visible:
SampleClass sampleClass = new SampleClass();
sampleClass.insert(Object object, Long param);
Could this be done in OOP?
There is no way of hiding the method. You can do this:
#Override
public void insert(Object ob) {
throw new UnsupportedOperationException("not supported");
}
but that's it.
The base class creates a contract. All subclasses are bound by that contract. Think about it this way:
BaseObject b = new SomeObjectWithoutInsert();
b.insert(...);
How is that code meant to know that it doesn't have an insert(Object) method? It can't.
Your problem sounds like a design problem. Either the classes in question shouldn't be inheriting from the base class in question or that base class shouldn't have that method. Perhaps you can take insert() out of that class, move it to a subclass and have classes that need insert(Object) extend it and those that need insert(Object, Object) extend a different subclass of the base object.
I don't believe there's a clean way to completely hide an inherited method in Java.
In cases like this, if you absolutely can't support that method, I would probably mark that method as #Obsolete in the child class, and have it throw a NotImplementedException (or whatever the equivalent exception is in Java), to discourage people from using it.
In the end, if you inherit a method that does not make sense for your child class, it could be that you really shouldn't inherit from that base class at all. It could also be that the base class is poorly designed or encompasses too much behavior, but it might be worth considering your class hierarchy. Another route to look at might be composition, where your class has a private instance of what used to be the base class, and you can choose which methods to expose by wrapping them in your own methods. (Edit: if the base class is abstract, composition might not be an option...)
As Cletus points out, this is really a design problem, in that you are trying to create a child class that does not obey the contract of its parent class.
There are rare circumstances where working around this by e.g. throwing an exception might be desirable (or at least an acceptable compromise -- for example, the Java Collections Framework) but in general it's a sign of poor design.
You may wish to read up on the Liskov substitution principle: the idea that (as Wikipedia puts it) "if S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program". By overriding a method to throw an exception, or hiding it any other way, you're violating this principle.
If the contract of the base class' method was "inserts the current object, or throws an exception" (see e.g. the JavaDoc for Collection.add()) then you could argue you're not violating LSP, but if that is unexpected by most callers you may want to rethink your design on these grounds.
This sounds like a badly designed hierarchy -
If no default exists and the user shouldn't call the method at all you can mark the method as #Deprecated and throw an UnsupportedOperationException as other posters have noted. However - this is really only a runtime check. #Deprecated only throws a compiler warning and most IDEs mark it in some way, but there's no compile time prevention of this. It also really sucks because it's possible to get the child class as a parent class reference and call the method on it with no warning that it's "bad" at all. In the example below, there won't be any indication until runtime that anything's wrong.
Example:
// Abstract base builder class
public abstract class BaseClassBuilder {
public final doBuild() {
BaseClass base = getBase();
for (Object obj : getObjects() {
base.insert(obj);
}
}
protected abstract BaseClass getBase();
protected abstract Object[] getObjects();
}
// implementation using SampleClass
public class SampleClassBuilder extends BaseClassBuilder {
#Override
protected BaseClass getBase() {
return new SampleClass();
}
#Override
protected Object[] getObjects() {
Object[] obj = new Object[12];
// ...
return obj;
}
}
However, if a sensible default exists, you could mark the inherited method as final and provide the default value inside of it. This handles both the bad hierarchy, and it prevents the "unforseen circumstances" of the above example.
Example:
public abstract class BaseClass {
public void insert(Object object) {
// ...
}
}
public class SampleClass extends BaseClass {
public static final Long DEFAULT_PARAM = 0L;
public final void insert(Object object) {
this.insert(object, DEFAULT_PARAM);
}
public void insert(Object object, Long param) {
// ...
}
}

Categories