Wednesday, 30 January 2013

Locks & Conditions in Java 5 or 6


We have the some ways to communicate in between threads.
All of usknow that  "wait" and "notify", which is a traditional method of communicating.

With the introduction of Locks and Condition , we have better performance and control .

It was already proved  that Locks and Conditions are more throughput than Synchronized blocks.

Here I will try to explain the simple producer - consumer problem without  Locks and Condition.




package org.ohms.threads.locks;

import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 
 * Producer Consumer Problem...Solved with Locks
 * 
 * @author
 *
 */
public class PCproblemWithLocks {

 private static int storedBox=-1;;

 public static void main(String[] args) throws InterruptedException {
  
  int totalProduction=1000;
  Lock lock=new ReentrantLock();
  Condition condition= lock.newCondition();
  
  
  Buffer buffer= new Buffer();
  Thread producer= new Thread(new Producer(totalProduction, buffer,lock,condition));
  Thread consumer= new Thread(new Consumer(totalProduction, buffer,lock,condition));
  
  System.out.println("=====================================");
  
  producer.start();
  consumer.start();
  
  producer.join();
  consumer.join();
  
  System.out.println("Completed .....");
 }
 
 
 
 /**
  * used to store the values or a common 
  * object where two threads used.
  * 
  * @author
  *
  */
 static class Buffer {

  void put(int newValue) 
  {
   storedBox = newValue;
  }

  int get() 
  {
   return storedBox;
  }
  
   void clear() {
    storedBox=-1;
  }
  
 }

 /**
  * Used to store the Value
  * in the StoredBox(int variable defined above) 
  * 
  * @author
  *
  */
 static class Producer implements Runnable 
 {
  
  private int counter;
  private Buffer buffer;
  private Lock lock;
  private Condition condition;
  
  public Producer(int count,Buffer buffer,Lock lock,Condition condition) 
  {
   this.counter=count;
   this.buffer=buffer;
   this.lock=lock;
   this.condition=condition;
   System.out.println("Producer Started placing the Values");
  }

  @Override
  public void run() 
  {
   try {
   this.lock.lock();
   System.out.println(" Producer Lock Acquired ");
    for (int i = 0; i < this.counter; i++) 
    {

     if(this.buffer.get()!=-1)
     {
      //System.out.println("Waiting to put>>>>>>");
      condition.await();
      System.out.println(" Producer Lock Acquired ");
     }
     
     int randomValue=i;//new Random().nextInt(100);
     this.buffer.put(randomValue);
     System.out.println("Produced -->"+randomValue);
     condition.signalAll();
     System.out.println(" Producer Lock Released ");
     
    }
   } catch (InterruptedException e) {
    e.printStackTrace();
   }finally{
    this.lock.unlock();
   }
   
  }

 }

 /**
  * used to retrieve/read the stored value
  * in the StoredValue Box
  * 
  * @author Kumar
  *
  */
 static class Consumer implements Runnable {

  private int counter;
  private Buffer buffer;
  private Lock lock;
  private Condition condition;
  
  public Consumer(int count,Buffer buffer,Lock lock,Condition condition) {
   this.counter=count;
   this.buffer=buffer;
   this.lock=lock;
   this.condition=condition;
   System.out.println("Consumer started Reading the Values ");
  }

  @Override
  public void run() 
  {
   this.lock.lock();
    System.out.println(" Consumer Lock Acquired ");
   try {
   for (int i = 0; i < this.counter; i++) 
   {
    if(this.buffer.get()==-1)
    {
     //System.out.println("Waiting to get <<<<<<<<<<");
     condition.await();
     System.out.println(" Consumer Lock Acquired ");
    }
    
    System.out.println("Consumed -->"+this.buffer.get());
    this.buffer.clear();
    condition.signalAll();
    System.out.println(" Consumer Lock Released ");
   }

   } catch (InterruptedException e) {
    e.printStackTrace();
   }finally{
    this.lock.unlock();
   }
   
  }

 }

}



 run the above program to know the usage of the Locks and condition in java .

Saturday, 30 June 2012

How to add SVN-Subclipse plugin to Eclipse

Normally we have two plugins available in the market for eclipse IDE.
 1. Subclipse-Developed by SVN
 2. Subversive-Developed by Eclipse

Better you can go for Tortoise SVN latest release 1.7 which is more improved version .

I prefer Subclipse which will be more user friendly one than other.

 How it add SVN -Subclipse plugin to Eclipse:

 Changelog: http://subclipse.tigris.org/subclipse_1.8.x/changes.html
 Eclipse update site URL: http://subclipse.tigris.org/update_1.8.x
Zipped downloads: http://subclipse.tigris.org/servlets/ProjectDocumentList?folderID=2240

 Ref: http://subclipse.tigris.org/servlets/ProjectProcess?pageID=p4wYuA


If you want to link Eclipse SVN with Local Tortoise SVN installation then you can go for
SVN Interface Client  javaHL (JNI) (1.7.4)


Restart Eclipse after installing everything.

how to use if,equals in ANT Script




If you want to use Ant tags like <if>,<equals> then you should do the following:
  1. Add ancontrib.jar in ANT_HOME/Lib/
  2. <taskdef resource="net/sf/antcontrib/antlib.xml" classpathref="project.classpath" /> to init Target.
  3. For high features-use -
<taskdef resource="net/sf/antcontrib/antcontrib.properties"/>

How to call Customized xml file as pom file in maven


Actually we will use "pom.xml" as the file name for maven default framework.
But we can also change the name or we can call our own xml file as pom file in maven.

in order to call own xml file in maven:

mvn -f own.xml clean install


Thursday, 20 October 2011

Malformed byte sequence: Invalid byte 2 of 3-byte UTF-8 sequence

Malformed byte sequence: Invalid byte 2 of 3-byte UTF-8 sequence

Solution:
Use the UTF-8 encoding.

Possible Errors:
1.Might be you are using default-encoding while forming a string...

How to add lessthan or greaterThan characters in XSLT



using CDATA we can transform any character--
like this below examples:


<![CDATA[<]]>
<![CDATA[>]]>
<![CDATA[</]]>
<![CDATA[write anything here]]>



Fetch MAC address of the Machine


import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class MacAddress
{
   
   
    private String getMacAddress()
    {
       
        StringBuffer macAddress=new StringBuffer();
       
          try {
             
                InetAddress address = InetAddress.getLocalHost();
               //InetAddress address = InetAddress.getByName("192.75.48.67");

                /*
                 * Get NetworkInterface for the current host and then read the
                 * hardware address.
                 */
                NetworkInterface ni = NetworkInterface.getByInetAddress(address);
                if (ni != null) {
                    byte[] mac = ni.getHardwareAddress();
                    if (mac != null) {
                        /*
                         * Extract each array of mac address and convert it to hexa with the
                         * following format 08-00-27-DC-4A-9E.
                         */
                        for (int i = 0; i < mac.length; i++) {
                             macAddress.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
                        }
                       
                       
                     
                       
                       
                    } else {
                        System.out.println("Address doesn't exist or is not accessible.");
                    }
                } else {
                    System.out.println("Network Interface for the specified address is not found.");
                }
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (SocketException e) {
                e.printStackTrace();
            }
       

          return macAddress.toString();
    }
   

    public static void main(String[] args)
    {
       
        MacAddress address=new MacAddress();
        System.out.println(address.getMacAddress());
       
       
       
       
    }
}

Fo my system output is like this:
Output:
54-7D-2C-59-65-0F