Wednesday, 25 November 2015

Create Deadlock between two threads in Java

Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.

Deadlock occurs because:

Mutual exclusion - Two processes cannot simultaneously control the same resource or be in their critical section.

Hold and Wait - processes currently holding resources can request new resources.

No preemption - Once a process holds a resource, it cannot be taken away by another process or the kernel.

Circular wait - Each process is waiting to obtain a resource which is held by another process.

Deadlocks in Java:
Deadlocks can occur in Java when the synchronized keyword causes the executing thread to block while waiting to get the lock, associated with the specified object. Since the thread might already hold locks associated with other objects, two threads could each be waiting for the other to release a lock. In such case, they will end up waiting forever.


class Thread1 implements Runnable {
      public Object obj1;
      public Object obj2;
      public Thread1(Object obj1, Object obj2) {
            this.obj1 = obj1;
            this.obj2 = obj2;
      }

      public void run() {
            synchronized (obj1) {
                  System.out.println("Thread1 : obj1");
                  synchronized (obj2) {
                        System.out.println("Thread1 : obj2");
                  }
            }
      }
}

class Thread2 implements Runnable {
      public Object obj1;
      public Object obj2;
      public Thread2(Object obj1, Object obj2) {
            this.obj1 = obj1;
            this.obj2 = obj2;
      }
      public void run() {
            synchronized (obj2) {
                  System.out.println("Thread2 : obj2");
                  synchronized (obj1) {
                        System.out.println("Thread2 : obj1");
                  }
            }
      }
}

public class Deadlock {
      public static void main(String args[]) throws InterruptedException {
            Object obj1 = new Object();
            Object obj2 = new Object();

            Thread2 runn2 = new Thread2(obj1, obj2);
            Thread1 runn1 = new Thread1(obj1, obj2);

            Thread thrd2 = new Thread(runn2);
            Thread thrd1 = new Thread(runn1);

            thrd1.start();
            thrd2.start();

            while(!thrd2.isAlive() || !thrd1.isAlive()) {
                  System.out.println("No deadlock found");
            }

      }
}

Output:
Thread1 : obj1
Thread2 : obj2

Tuesday, 24 November 2015

Print Natural numbers using two Even-Odd printing Thread

Print Natural numbers using Even-Odd Thread

There are two Threads, one Thread will print the even sequence and another will print the Odd sequence.
Use these Threads to print the sequence in the natural order.

PrintOdd.java
class PrintOdd implements Runnable {
     public static boolean oddFlag = true;
     public void run() {
           for (int i = 1; i <= 9;) {
                if (oddFlag) {
                     System.out.print(i+" ");
                     oddFlag = false;
                     i = i + 2;
                }
           }
     }
}

PrintEven.java
class PrintEven implements Runnable {
     public void run() {
           for (int i = 2; i <= 10;) {
                if (!PrintOdd.oddFlag) {
                     System.out.print(i+" ");
                     PrintOdd.oddFlag = true;
                     i = i + 2;
                }
           }
     }
}

PrintNatural.java
public class PrintNatural {
     public static void main(String args[]) {
           PrintEven prEven = new PrintEven();
           PrintOdd prOdd = new PrintOdd();
           Thread evenThread = new Thread(prEven);
           Thread oddThread = new Thread(prOdd);
           evenThread.start();
           oddThread.start();
     }
}
Output:
1
2
3
4
5
6
7
8
9
10

Thursday, 19 November 2015

How to get the name of the current executing method in java?

Using reflection:


/** using reflection trace. */
Method method = new Object(){}.getClass().getEnclosingMethod();
String methodName = method.getName();


However, a new anonymous inner class will be created during compile time (e.g. MethodNameTest$1.class). So this will create a .class file for each method that deploys this trick.

Advantage of trick is that getEncosingMethod()

It returns java.lang.reflect.Method which can be used to retrieve all other information of the method including annotations and parameter names. This makes it possible to distinguish between specific methods with the same name (method overload).

Using stackTrace:

/** using stack trace. */
StackTraceElement[]stackTrace=Thread.currentThread().getStackTrace()
String nameUsingTrace = stackTrace[1].getMethodName();



import java.lang.reflect.Method;

public class MethodNameTest {
     public static void main(String[] args) {
           checkMethodName();
     }

     private static void checkMethodName() {
           /** using stack trace. */
           StackTraceElement[] stackTrace =                 
                       Thread.currentThread().getStackTrace();
           String nameUsingTrace = stackTrace[1].getMethodName();
          
           System.out.println("print method name using stack trace : "
                     + nameUsingTrace);

           /** using reflection trace. */
           Method method =
                 new Object(){}.getClass().getEnclosingMethod();

           String methodName = method.getName();

           System.out.println("print method name using reflection : "
                     + methodName);
     }
}
Output:
print method name using stack trace : checkMethodName
print method name using reflection : checkMethodName

Wednesday, 18 November 2015

ArrayList vs HashMap in Java


ArrayList
HashMap
Interface
Implementation of java.util.List Interface.
Implementation of java.util.Map interface.

Storage
It used to store the object.
It is used to store the object in key-value pair.
Where key and value are different objects.

Methods to implement
No method is required to implement.

However contains() method uses the equals() method to check the existence of the object.
For HashMap, class which is used as key must implements equals() and hashCode() method correctly.

Better hashcode() implementation will lead to better performance.

Ordering
ArrayList maintain order of object.
HashMap doesn't provide any order guarantee.

Duplicate
ArrayList allows duplicates
HashMap doesn't allow duplicates key, though it allows duplicate values.

Resizing
Size increase 50% after resizing.
Size increase 100%. Load factor plays the vital role to resize the HashMap.

Related Posts Plugin for WordPress, Blogger...