Can we synchronize abstract methods in Java?


An abstract method is the one that does not have a body. It contains only a method signature with a semi colon and, an abstract keyword before it.

public abstract myMethod();

To use an abstract method, you need to inherit it by extending its class and provide implementation (body) to it. If a class contains at least one abstract method, you must declare it abstract.

Example

 Live Demo

import java.io.IOException;
abstract class MyClass {
   public abstract void display();
}
public class AbstractClassExample extends MyClass{
   public void display(){
      System.out.println("subclass implementation of the display method");
   }
   public static void main(String args[]) {
      new AbstractClassExample().display();
   }
}

Output

subclass implementation of the display method

Synchronization − If a process has multiple threads running independently at the same time (multi-threading) and if all of them trying to access the same resource an issue occurs.

To resolve this, Java provides synchronized blocks/ synchronized methods. If you define a resource (variable/object/array) inside a synchronized block or a synchronized method, if one thread is using/accessing it, other threads are not allowed to access.

synchronized (Lock1) {
   System.out.println("Thread 1: Holding lock 1...");
}

Synchronizing abstract methods

No, you can’t synchronize abstract methods in Java. When you synchronize a method that implies that you are synchronizing the code in it, i.e. when one thread is accessing the code of a synchronized method no other thread is allowed to access it. So synchronizing abstract methods doesn’t make sense, if you still try to do so a compile-time error will be generated.

Example

import java.io.IOException;
public abstract class MyClass {
   public abstract synchronized void display();
}

Output

Compile-time error −

MyClass.java:3: error: illegal combination of modifiers: abstract and synchronized
   public abstract synchronized void display();
                                     ^
1 error
raja
Published on 10-Sep-2019 14:06:50
Advertisements