Pages

Wednesday, 15 May 2013

Producer And Consumer Example In Java Using Threads


     Below I have created on sample example of producer and consumer using java threads. I this example I have one producer thread which will create 50 fruit items and it will be consumed by 3 consumer threads. When producer finishes consumer also finishes the execution.Producer will create the fruit and will put it in the bucket which will be consumed by the consumer.

Below is the example :
How to run :
1)Create class ProducerConsumer in eclipse. This class contains all the other classes as inner classes.
2)Run the class and check the console.
3)Most important go though the code.


import java.util.ArrayList;
import java.util.List;

/**
 * Producer and consumer example. There will be one producer thread which will create 50 fruit items
 * and it will be consumed by 3 consumer threads. When producer finishes consumer also finishes the
 * execution
 * @author Vikram
 *
 */
public class ProducerConsumer {

public void initlize() {
Bucket b = new Bucket();
Producer producer = new Producer(b);
Consumer consumer_1 = new Consumer(b,"Consumer 1");
Consumer consumer_2 = new Consumer(b,"Consumer 2");
Consumer consumer_3 = new Consumer(b,"Consumer 3");

producer.start();
consumer_1.start();
consumer_2.start();
consumer_3.start();

}

public static void main(String[] args) {
new ProducerConsumer().initlize();
}

public class Producer extends Thread {

Bucket bucket;

public Producer(Bucket b) {
bucket = b;
}

@Override
public void run() {

int fruitCount = 0;
while (fruitCount < 50) {
synchronized (bucket) {
System.out.println("produced : Fruit_" + fruitCount);
bucket.addFruit("Fruit_" + fruitCount++);

bucket.notifyAll();

}
try {
this.sleep(200);//sleep for some so it will slow sysout slowly
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
synchronized (bucket) {
bucket.setProducerFinished(true);
bucket.notifyAll();//realese all locks befor finish
}
System.out.println("Producer finised" );

}
}

public class Consumer extends Thread {

Bucket bucket;
String consumerName;

public Consumer(Bucket b, String consName) {
bucket = b;
consumerName =consName;
}

@Override
public void run() {

while (bucket.isProducerFinished()==false ) {
synchronized (bucket) {

String fruit = bucket.getFruit();

//no fruit produced
if (fruit == null) {
try {
bucket.wait();
System.out.println(consumerName+"  waiting" );
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
System.out.println("Consumed fruit :" + fruit +" by "+consumerName);
}


}
}
synchronized (bucket) {
bucket.notifyAll();//realese all locks befor finish
System.out.println(consumerName +" finised" );
}

}

}

public class Bucket {

private List<String> fruitBuket  = new ArrayList<String>();
private boolean producerFinished = false;


public boolean isProducerFinished() {
return producerFinished;
}

public void setProducerFinished(boolean producerFinished) {
this.producerFinished = producerFinished;
}

public int getBucketSize() {
return fruitBuket.size();
}

public void addFruit(String fruit) {
fruitBuket.add(fruit);
}

public String getFruit() {
if (fruitBuket.size() == 0)
return null;
return fruitBuket.remove(fruitBuket.size() - 1);
}
}

}


If you find this post useful,please comment ans share. Thanks :)

Thursday, 21 March 2013

File Change Event In Java 6 using apache.commons.jci


I had requirement in my project to reload the whole context when properties file is changes.This is similar requirement like context reloading or hot deployment apache tomcat .After doing analysis I found that it is very easy to do it in java 7.But my requirement was for java 6 which we can achieve by using apache commons jci.
I have explained with the simple example monitors file change using apache commons 
Requirement:
1)  apache commans jci Jar and dependent Jars
Download Example project using below links:
1)Example with maven project :Maven dependency is added for the  commons jci.
2)Simple java project :In this project jars are added in lib folder please put them in classpath.

Below is the exaplanation about the classes used in above example projects:

1)ConfigurationReloading : This class has main method.This class will create FilesystemAlterationListener and it will associate it with File.When  file change event occurs the listeners onStop method will be triggered.Check javadoc of FilesystemAlterationListener. 
Please take closer look to this class :

package fileReloadingExampleMain;


 
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;
 
import org.apache.commons.jci.listeners.FileChangeListener;
import org.apache.commons.jci.monitor.FilesystemAlterationListener;
import org.apache.commons.jci.monitor.FilesystemAlterationMonitor;
import org.apache.commons.jci.monitor.FilesystemAlterationObserver;
 
/**
 * This example will demonstrate that how add file change listener to properties file.
 * 
 * @author Vikram P
 */
public final class ConfigurationReloading {
 
    private final FilesystemAlterationMonitor fam = new FilesystemAlterationMonitor();
 
    private void run(String[] args) {
 
    	//this is the file on which we want to add listener
        final File configFile = new File("Some.Properties");
        
        //file does not exisits then we can not add listener
        if(configFile.exists()==false){
        	System.out.println("File does not exists at path"+configFile.getAbsolutePath());
        	return;
        }
 
        System.out.println("Watching " + configFile.getAbsolutePath());
 
        
        final Collection<configurable> configurables = new ArrayList<configurable>();
 
        //this is the listener which will be associated with above configFile
        final FilesystemAlterationListener listener = new FileChangeListener() {
            public void onStop(FilesystemAlterationObserver pObserver) {
                super.onStop(pObserver);
 
                if (hasChanged()) {
                    //System.out.println("Configuration change detected " + configFile);
 
                    final Properties props = new Properties();
                    try {
 
                        props.load(new FileInputStream(configFile));
 
                        //System.out.println("Notifying about configuration change " + configFile);
 
                        for (Iterator it = configurables.iterator(); it.hasNext();) {
                            final Configurable configurable = (Configurable) it.next();
                            configurable.configure(props);
                        }
 
                    } catch (Exception e) {
                        System.err.println("Failed to load configuration " + configFile);
                    }
 
                }
            }
        };

        //add listerner to config file.you can add multiple files here.
        fam.addListener(configFile, listener);
        //start monitoring.
        fam.start();
 
        //when ever any file change event will occure it will call the configure method of ChangedFileHandler class
        //ChangedFileHandler implements Configurable 
        ChangedFileHandler changedFileHandler = new ChangedFileHandler();
        
        configurables.add(changedFileHandler );
 
        while(true) {
            try {
            	//sleep period
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
        }
    }
 
    public static void main(String[] args) {
    	//you can send multiple files through args
        new ConfigurationReloading().run(args);
    }
}

2) Interface Configurable : This interface’s implemented by ChangedFileHandler whose configure() method will be called when file is changed.        
package fileReloadingExampleMain;

import java.util.Properties;

public interface Configurable {
	public void configure(Properties props);
}
3)ChangedFileHandler :This class implements Configurable inteface.
   package fileReloadingExampleMain;

import java.util.Properties;

public class ChangedFileHandler implements Configurable {
	
	public void configure(Properties props) {
		System.out.println("File has changed...do reloading stuff....");
	}

}
   

Download  Example Project Using Below links:

1)Example with maven project
2) Simple java project
How to test?
- Some.properties file is present in the same project.When ever this file is changed it will print message to console.


“Please comment if you find this information useful.Thank you :)”

Tuesday, 16 October 2012

Free Folder or Directory Compare Tool / Utility



In software development sometimes we need to compare two folders which are having same files. The same case happened with me. So I have written simple directory compare utility.
This is an executable jar which compares two folders and list down the result in xls file. This is simply written in java and UI is in java swing so it will work in any OS.






Prerequisites to run the utility:


1) Set the PATH environment variable to Java\jdk1.6.0_24\bin\ to run executable jar.

2) Output is created in .xls format. So .xls editor is needed for reading excel file. Use Microsoft Excel for windows and OpenOffice for Linux.

3)While providing input, First directory should be the latest directory otherwise it will not show  the newly added files in result.


To Run the utility follow below steps:

1) Double click on executable jar or use command java -jar DirectoryComparator.jar to run using command line.

2) Input to utility:

1) Two directory paths for comparison.
Note*:First Directory should be the latest directory otherwise it will not show  the newly added files in result.

2) Path of result file which is a excel sheet. (no need to give extention to excel file)

3) Comma separated list of file extensions ( if this left empty it will compare all the files.)

 e.g. java,jsp,txt,jpeg.css that means it will compare these files only.

Below is screen shot of utility with input selected:

Directory Compare Utility



3)After filling all the inputs and hitting compare button.The popup will show the path of excel file and basic result of the comparison as shown in below image.
                     Folder Compare




4) Go to the excel file  and expand the columns to see the details. Excel sheet shows the following details.
a)Column  List Of Changed Files : path of files which are changed
b)Column  Added File List : Shows file which are newly added.
c)Column  Other Information Shows :
a)Number  of  files compared count.
b)Number  of  files differs count.
c)Number  of  newly added files  count.

directory compare



Advantages of this Utility:

1) Comparison is fast and generates simple excel sheet.
2) It gives list of newly added files.
3) Main advantage is  it has filtering option i.e if you want to compare java and jsp file only then give input as java,jsp in File with extension input field.

Disadvantages of this Utility:

1)If user want to find newly added files in a directory then user have to give that folder as a first input and the other folder as second. This means it will not list newly added files in second directory.


Click Below link to download executable jar:



If you have any problem running utility please let me know.
Comments would be appreciated.

Thanks

PermGen space exception



      PermGen space exception with Maven


  •  What is PermGen Space?

             PermGen Stands for  Permanent Generation. PermGen space is a part heap memory.It is used for storing metadata information like class definitions.

  •   Why this  OutOfMemoryError  exception occurs?

                       The OutOfMemoryError: PermGen Space error occurs when the permanent generation heap is full. Usually this error is caused by a memory leak.

  •    How To Fix this exception ?
               a)MAVEN   
                     If your are using maven you get this error create following  environment variable:

                           MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=128m"

                       Here 128m is double of the default space.

                       Note*: If your using  eclipse for running maven command and setting the MAVEN_OPTS is not               
                   solving problem try to run your maven commands using command line,as sometime it does not  
                   works.

                 b)Tomcat
                       Open catalina.sh Or catalina.bat based on the OS  and change the JAVA_OPTS as follows:


JAVA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m 
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"









                    

Monday, 24 September 2012

Convert java util Date From one Timezone To another Timezone In Java

How to convert java.util date from one Timezone To another Timezone?



      Here is the simple method which converts one Timezone To another and returns util date. Also most important thing is that it handles daylight saving time (DSTwhile converting date.



/**
* Convert Date from one timezone to other timezone.
* This method also takes care of daylight saving time
* @param dt
* @param from
* @param to
* @return
*/
public static Date convertFromOneTimeZoneToOhter(Date dt,String from,String to ) {

      TimeZone fromTimezone =TimeZone.getTimeZone(from);//get Timezone object
      TimeZone toTimezone=TimeZone.getTimeZone(to);
             
      long fromOffset = fromTimezone.getOffset(dt.getTime());//get offset
      long toOffset = toTimezone.getOffset(dt.getTime());
     
      //calculate offset difference and calculate the actual time
      long convertedTime = dt.getTime() - (fromOffset - toOffset);
      Date d2 = new Date(convertedTime);
     
      return d2;
}