Urban pro

View My Profile

Friday, November 21, 2014

How to implement an interface in a class but prohibit the class from implementing the interface methods in that class ?

Hi Friends,

Today I will present an interesting scenario in front of you . Normally we , most of the time will not come across such a scenario while coding . But there are exceptions and this happens to be ab exceptional exception that we should get to know.

Scenario :  Consider an interface K which has 2 methods in it : methA(), methB(). Now we need to have two classes A and B  in such a way that they will implement the interface K . But Class  A will only over ride methA() and Class B will implement methB() . How can we achieve that ?

Solution :

Normally when you implement an interface in a concrete class you will have to override the methods present in the interface otherwise the compiler will give an error . So  how we accomplish the  un accomplish-able like scenario stated above .

The answer is an Abstract Class . Yes , you heard it right : abstract class. An abstract class can implement an interface but it is not obliged to override any of the methods in the interface .

So for  our scenario , we can do it the following way :

public interface K {

public void methA();

public void methB();

}

Now we can  write our abstract class like this :

public abstract class A implements K{

}

You can check the above piece of code by running it in IDE of your choice (Eclipse, Netbeans etc). It will not throw any compiler error, because, an abstract class is not required  to override  any method in the interface , but it can if you want it to .

Hence, in this case, as we want to override methA() in class A, we can re organize Class A as :

public abstract class A implements K{

      @Override
      public void methA(){

          System.out.println("methA");

      }

}

Now we can use the class B as a concrete class and have it extend B, like below :

public  class B extends A{


}

If you write just the above piece of code , the compiler will throw error and ask you to implement the un-implemented method methB(). That's because B is a concrete class and it implements K via A. Since, methA() is already overidden in class A , so the compiler asks the developer to override and implement methB() in class B.

In light of the above explanation we can organize the class B as :

public  class B extends A{

      @Override
      public void methB(){

          System.out.println("methB");

      }

}

You can refer this stack overflow thread for more details : http://stackoverflow.com/questions/197893/why-an-abstract-class-implementing-an-interface-can-miss-the-declaration-impleme

That's it for today. Hopefully this will enlighten people who are not  aware of this concept .


Wednesday, November 19, 2014

Java 8 : Interfaces and Default Methods

Hi ,

Today I am going to post a bit about some of the exciting features of Java 8.

Pre-requisites  :

1> Install java 8 SDK
2> Install Eclipse Luna (Eclipse 4.4.1)

Without Eclipse Luna 4.4.1 , it will be very difficult to run programs in Java 8. So please download and install the Eclipse Luna Build .

So, let's get started with the good stuff .

Default Methods :

Now in java 8 , we can have methods with default signature in interface, which will have body logic or implementation logic . 

So, let's say I have an interface called Person below :

public interface Person {

default void sayHello() {
              System.out.println("Hello there in Person!");
    }

}

As you can see if encapsulate a method name in the interface with default signature, you can add your logic in it.

Now what happens , when I have another interface with same method name but different implementation logic and I try to implement both of them in a single class ?

public interface Male {

default void sayHello() {
              System.out.println("Hi there in Male ");
    }

}

My implementation class(Sample.java) is shown below :


As you can see, here the compile time error is thrown because the compiler is not understanding which "sayHello()" method it should implement.

So to resolve this ambiguity, we can override the sayHello() method in  the implementation class itself  like this :

public class Sample implements Person, Male {

//override the sayHello to resolve ambiguity
public void sayHello() {
   
    }

}

OR

We can just call the appropriate / desired interface method directly inside .
To do this, we have to use the syntax : "Interface.super.methodname()"

public class Sample implements Person, Male {

//override the sayHello to resolve ambiguity
public void sayHello() {

Person.super.sayHello();
Male.super.sayHello();
   
    }

}

So a default method looks a lot like an abstract class implementation , does n't it ?
However, there is a subtle difference : An abstract class holds the state of its object as it can have constructors .But interfaces in java 8 with default methods cannot have constructors and as such cannot hold the state of an object. Default method should be used for backward compatibility. Whenever you want to add additional functionality in an existing legacy interface you can use default methods without breaking any existing implement or classes.


That's all on interfaces from java 8 perspective .  I will come up with a new feature of Java 8 on my next post which will be related to Lambda Expressions .

Sunday, November 2, 2014

Different types of Locking in a threaded(multi or Uni) environment in Java

Hi friends,

I am back after a long hiatus. I became so wrapped up in several things that I forgot to share my experience here for a long time. Anyways, let's move forward with today's post.

Recently I delved into Java threading. In my experience , I did not come across a single web application that makes use of the java threading utilities(which is a shame really, since they are so versatile and useful; the other reason may be that they are bit tough to understand and implement). So , while going through different threading techniques, I stumbled upon a concept of threading called as locking. The more I read, the more confused I became. At last I was able to get myself out of such a tangled mess with some help. So here I will post about locking in a way that it's easy to understand .

What is Locking ?

Locking is a way in which a thread accesses a resource and tells other threads that they cannot access the same resource until he is done using it. So , that means when we use the synchronized keyword on a method or a code block , only one thread at a time can access it. Other threads will wait until the thread accessing it is finished with it's operation. That's called locking; means the resource is locked and no one else can access it unless it's unlocked for future use.

Types of Locking 

There are actually two types of locking:

1> Intrinsic Locking
2> Explicit Locking

Intrinsic locking are of different types like : Object level locking, class level locking and re entrant locking.

Object Level Locking :

Object level locking is using the synchronized key word on a non static method or a non static code block.So in such a type of locking, multiple threads will enter the class using different instances or objects of the class, but only one thread will have a lock on the method or the code block for a particular instance . This makes instance level data thread safe .

public class Death
{
    public synchronized void deathEaters(){} //non static method
}

or

public class Harbinger
{
    public void War(){
        synchronized (this) //non static code block
        {
            
        }
    }
}

Class Level Locking :

Class level locking comes into play when synchronized key word is used on a static method or a static code block. That means at a given instance , if there are 100 threads, then only one thread can enter the method or code block. Other threads will be waiting . This comes into play because of  the nature of a static method. A static method is always available at class level and it is shared by all instances. Hence the need to have this type of locking here .

public class Death
{
    public synchronized static void deathEaters(){} // static method
}

or

public class Harbinger
{
    public static void War(){
        synchronized (Harbinger.class) //static code block
        {
            
        }
    }
}


Re entrant locking :

This is an interesting concept. Synchronized methods are re entrant in nature .If a thread has lock on the monitor object using one synchronized method  and if another synchronized method requires to have the lock on the same monitor object then the thread can enter that method . That's why it is called re entrant ( the ability to re enter ) . Consider the following :

public class Famine{

public synchronized death(){
    plague();
  }

  public synchronized plague(){
    
  }
}

If a thread enters death(), it has the lock on Famine object, so when it tries to execute plague() method, the thread is allowed to execute plague() method since it’s already holding the lock on the Famine object.

Explicit Locking :

Explicit locking is a way of introducing thread safety  without using synchronized keyword. Instead we can use the Lock API present in java.util.concurrent package to introduce locking.

public class Resource {
public void doResourcing(){
    }
public void dologging(){
    }
}

public class ExplicitLockingUsingSynchronized implements Runnable{
    private Resource resource;
public ExplicitLockingUsingSynchronized(Resource r){
        this.resource = r;
    }
     
    @Override
    public void run() {
        synchronized (resource) {
            resource.doResourcing();
        }
        resource.dologging();
    }
}

Now let's try this using the Lock API and we will remove the synchronized keyword.

public class ExplicitLockingImplementation implements Runnable{

    private Resource resource;
    private Lock lock;
     
    public ExplicitLockingImplementation(Resource r){
        this.resource = r;
        this.lock = new ReentrantLock();
    }
     
    @Override
    public void run() {
        try {
            if(lock.tryLock(10, TimeUnit.SECONDS)){
resource.doResourcing();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
            lock.unlock(); //release lock
         }
        resource.doLogging();
    }

Now do you see the difference : There a lot of  API related methods to help us with locking in the Lock API(for eg, usage of time out as I have shown here). It makes our job much, much easier . We can use a lot of conditions  and options using the lock API.

That's all on thread locking. I hope this will be very informative for people who are trying to understand the concept of locking in threads .