Thursday, 25 October 2012

Semaphore

Semaphore provides simple and effective way of controlling multiple threads trying to access same resource. This concepts was invented by dutch scientist in 1965. Semaphore can be used as deadlock handling mechanism for single resource. There are two main types of semaphore,

1. Counting semaphore :
Here semaphore represents arbitrary number of resource unit. Like 10,20 etc.

2. Binary semaphore :
Binary semaphore holds only two values 0 or 1. Means available/ not-available or locked /unlocked. This binary semaphore works nearly as Mutex.

Here is one simple example of explaining semaphore concept,
Consider internet cafe where 10 seat are available to be used by customer and there is one gate keeper. Now when customer wants to occupy seat in the cafe then first he/she has to take permission from gate keeper. If gate keeper is giving permission then and only then he/she can occupy seat. Again if customer wants to leave any seat then after leaving that seat customer has to inform gate keeper that he/she just released one seat.
Here gate keeper is simply maintaining count of number of seats ready to use. If count is more than 0 then gatekeeper will allow customer to occupy seat and if count is 0 then gate keeper will not allow you to occupy the seat.
This explains the semaphore concept where seats are number of resources, customers means processes and gate keeper means semaphore. Semaphore neer maintains which resources are empty but it only maintains number of resources ready to use.

Even if we are using semaphore the dead lock may occur because of multiple resource problem. This problem can be explained using dining philosophers problem.

Tuesday, 23 October 2012

Exceptions - Java

Exception handling mechanism in java shows one major base class called Throwable. This Throwable class shows two major branches called Exception and Error.

Exception : 
Exception is abnormal condition occurred at run time. We programmers can handle these exceptions in our code using try-catch block. Example of exception is NullPointerException, FileNotFoundException etc.

Error :
Error are abnormal conditions which are not supposed to be handled by programmer. These are serious ones and we can't handle these in our program. Example of error is OutOfMemoryError, StackOerflow etc.

Again there are two types of exceptions. Checked exceptions and unchecked exception. Checked exception are those which compiler forces us to add. Like IOException. And unchecked exceptions are those which are under RunTimeException class or under Error class.

We already know how to handle exception using try-catch block. Here I am trying to explain how to handle exception between different methods. Here is simple example of that,

Code :
import java.io.IOException;

class Main
{
    public void test() throws IOException {
       
    }
   
    public void test1() throws IOException {
        test();
    }
   
    public void test2() {
        test1(); // It will create problem.
       
        try {
            test1();
        } catch(IOException e) {
           
        }
    }
    public static void main(String args[])
    {
       
    }
}

Let's examine the above code carefully. Here method test is throwing IOException so this exception will be handled by the method who is calling to test() method. Here that method is test1(); But test method is also throwing the same exception so at this point responsibility of handling that exception will be of method who is calling to test1(); So in the above code IOException throws by test() method is handled in test2() method using try-catch block.

Anonymous Inne Classes - Java

Anonymous inner classes are little confusing in java. Remember one thing about these classes that, anonymous inner classes can either implement one interface or extend one class at a time only. These classes can never extend and implement class and interface but only one at a time.
Here I am presenting few things about anonymous inner classes with examples.

Anonymous inner class extending class :
Here is a code where anonymous class is sub class of one of super class,
Code :
class Test {
     public void cool() {
          System.out.print("This is original.");
     }
}

class Main {
     public static void main(String args[]) {
          Test t = new Test() {
               public void cool() {
                    System.out.print("This is duplicate.");
               }
          };
          t.cool();
     }
}

This code will output "This is duplicate.". In this way we can use anonymous inner classes for overriding one or more methods of super class.

Anonymous inner class implementing interface :
Here is code presenting this concept,
Code :
interface Test {
     public void ohh();
}

class Main {
     public static void main(String args[]) {
          Test t = new Test() {
               public void ohh() {
                    System.out.print("Hahahaha");
               }
          };
          t.ohh();
     }

This code will print "Hahahaha". Here anonymous inner class is implementing our Test interface.

Anonymous inner class as argument :
Here is code for this one,
Code :
----------
----------
button.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEent ae) {

     }
});
---------
---------

Enjoy it.....

Monday, 22 October 2012

Inner Classes - Java

In java inner classes are interesting. Here I am trying to present few things about inner classes. There are different types of inner classes are present in java,
     1. Regular inner classes
     2. Static inner classes (Nested classes)
     3. Method-local inner classes
Let's see these types one by one,

Regular inner classes : 
Regular inner classes means non-static inner classes, which are declared in top level class only. Here is example of regular inner class,

Code :
class TestOuter {
     private int x = 10;
     public static void main(String args[])  {
           TestOuter to = new TestOuter();
           TestOuter.TestInner ti = to.new TestInner();
           ti.testInnerMethod();   
     }

     public void outerNonStatic() {
           TestInner ti = new TestInner();
           ti.testInnerMethod();
     }

     class TestInner {
           public oid testInnerMethod() {
               System.out.print("X : " + x); //Totally valid
          }
          //Static members are not allowed in regular inner class.
         // Interfaces are no allowed here.
     }
}

From this example we can define following rules,
     1. Regular inner class can access private members of outer class.
     2. Regular inner classes can not declare any static member like static variable or method.
     3. We can directly create instance of inner class from non static method of outer class.
     4. We can create instance of inner class from static method of outer class via instance of outer class, because static method can never use this reference.
     5. We can not declare any interface in regular inner class.

Static inner classes :
Static inner classes are nested classes. Static word says that inner class is static member of outer class and can be accessed as other static members without creating instance. Here is example of static inner classes,

Code:
class Main
{
    int x =10;
    public static void main(String args[])
    {
        Test t = new Test(); // It works fine.
        t.testMethod();
        // This also works fine.
        Main.Test t = new Main.Test();
        t.testMethod();
    }
   
    public void outerNonStatic() {
        Test t = new Test();
        t.testMethod();
    }
   
    static class Test {
        public void testMethod() {
            System.out.print("X : " + x); //It will not compile.
        }
        interface TestingInt {
           
        }
    }
}

From this we can define following rules,
     1. Nested class can not access non static members of outer class.
     2. We can create instance of static class without reference of outer class. Even in static method.
     3. In static inner class we can declare any interface as well. This proves that static inner class works like top level class.

Method local inner classes:
Method local inner classes are those are defined in method. Here is simple example of method local inner classes,

Code :
class Main
{
    private int x =10;   
    public void testing() {
        Test t1 = new Test(); //It will not compile.       
       
        int a = 20;
        final int b = 30;
        class Test {
            public void testing() {
                System.out.print("X : " + x);
                System.out.print("A : " + a);// It will not compile
                System.out.print("B : " + b);               
            }
        }
       
        Test t = new Test();
        t.testing();
    }
}

From this we can define following rules,
     1. Method local inner classes can't access any variable of method except final.
     2. Object can be created only after class declaration.
     3. Can access private variables of top level class.

There are still many things to study about inner classes.