How to create dead lock? Here is the fine example.
Lets talk about money transfer from one account to another account. Money has to be debited from one account and it has to be credited into another account.
public class Transfer extends Thread
{
private Credit credit = null;
private Debit debit = null;
private boolean odd = false;
public Transfer(Credit credit, Debit debit,boolean odd)
{
this.credit=credit;
this.debit=debit;
this.odd=odd;
}
public void run()
{
if(odd)
{
transferMethod1();
}
else
{
transferMethod2();
}
}
//first lock credit and then do debit
public void transferMethod1()
{
credit.credit();
//thread.sleep() can be added just to ensure that dead lock is happening
debit.debit();
}
//first lock debit and then do credit
public void transferMethod2()
{
debit.debit();
//thread.sleep() can be added just to ensure that dead lock is happening
credit.credit();
}
public static void main(String a[])
{
Credit c = new Credit();
Debit d = new Debit();
Transfer t1 = new Transfer(c,d,true);
Transfer t2 = new Transfer(c,d,false);
}
}
class Credit
{
public synchronized credit()
{
//credit implementation
}
}
class Debit
{
public synchronized debit()
{
//debit implementation
}
When thread t1 calls transferMethod1(), credit object is locked and its waiting for debit object. At the same time, when thread t2 calls transferMethod2(), debit object is locked and its waiting for credit object. t1 can proceed when t2 releases debit object and t2 can proceed when t1 releases credit object. Hence program hangs. One way to avoid this deadlock is, combine those two resources. i.e synchronize both these credit and debit operations. i.e in other words synchronize methods in Transfer object. Make transferMethod1() and transferMethod2() methods synchronized.
Friday, June 24, 2011
Sunday, June 5, 2011
Regex to find Email
Wrote a regular expression to find e-mail which has below conditions.
1. User name must start with a character.
2. It can contain _-. characters but not two consequetive hypens (--). It can contain numbers.
3. Domain name must start with a character or a number it can have any number of subdomains i.e .co.in etc
(\b[a-zA-Z][\w\.^[--]]*)@([a-zA-Z][\w^[--]]*)(\.[\w^[--]]+)+
My idea is to group email as username,domainname. First lets take username. This can be identified by (\b[a-zA-Z][\w^[--]]*).
\b means it should start with a word boundary. It should start with a character, so the character class [a-zA-Z] confirms the same. Then it could contain any number of characters but not two hypens which can be achieved by a word character \w (a-zA-Z0-9) and a character class ^[--].
Email can have any number of sub domains i.e .co.in. so I split it as (.\w) i.e a . followed by a word character. And the rest is self explanatory.
1. User name must start with a character.
2. It can contain _-. characters but not two consequetive hypens (--). It can contain numbers.
3. Domain name must start with a character or a number it can have any number of subdomains i.e .co.in etc
(\b[a-zA-Z][\w\.^[--]]*)@([a-zA-Z][\w^[--]]*)(\.[\w^[--]]+)+
My idea is to group email as username,domainname. First lets take username. This can be identified by (\b[a-zA-Z][\w^[--]]*).
\b means it should start with a word boundary. It should start with a character, so the character class [a-zA-Z] confirms the same. Then it could contain any number of characters but not two hypens which can be achieved by a word character \w (a-zA-Z0-9) and a character class ^[--].
Email can have any number of sub domains i.e .co.in. so I split it as (.\w) i.e a . followed by a word character. And the rest is self explanatory.
Thursday, May 19, 2011
Some real world java examples
Just thought about some real world examples.
1. Polymorphism:
In simple terms polymorphism means one interface - multiple implementations. Users can choose the
implementation based on their own interests. For example Vehicle could be the interface and travel
is the method. There could be n number of implementations for Vehicle interface. i.e Van, Car, Bus etc.
Uses can choose their own Vehicle implementation based on their need i.e capacity, cost etc. Polymorphism can
be used for grouping.
2. Inheritance:
In object oriented programming, users can map real world entities into java objects. Through inheritance
parent object's properties are passed to children object properties. This reduces the amount of code
to be written and also increases the maintainability of the code. For example employee is the class that could
have details as name, id, start date of employment, address etc. Also Lead is also an employee but he has
more details as module he owns, review permission etc. Manager is also an employee who has additional responsibilites
like performance review etc., along with the default employee details.
3. Encapsulation:
Encapsulation means providing right access details for the right entities. For example in a hotel,customers are not allowed
inside cooking room. Servers are not allowed inside owner's cabin.
4. Queue:
Queue means first in first out. Railway booking counters.
4. Stack:
Stack means last in first out. Assume a movie theatre has 1000 seats which has only one gate in which people are allowed based on the seat number. Once the
show is over person who sat in 1000th seat, can come out as a first person.
5. Deque:
Deque means addition/removal is supported on both ends. Same theatre example could be applied here where it has two gates. One front gate and one back gate, visitors are allowed in both the gates.
1. Polymorphism:
In simple terms polymorphism means one interface - multiple implementations. Users can choose the
implementation based on their own interests. For example Vehicle could be the interface and travel
is the method. There could be n number of implementations for Vehicle interface. i.e Van, Car, Bus etc.
Uses can choose their own Vehicle implementation based on their need i.e capacity, cost etc. Polymorphism can
be used for grouping.
2. Inheritance:
In object oriented programming, users can map real world entities into java objects. Through inheritance
parent object's properties are passed to children object properties. This reduces the amount of code
to be written and also increases the maintainability of the code. For example employee is the class that could
have details as name, id, start date of employment, address etc. Also Lead is also an employee but he has
more details as module he owns, review permission etc. Manager is also an employee who has additional responsibilites
like performance review etc., along with the default employee details.
3. Encapsulation:
Encapsulation means providing right access details for the right entities. For example in a hotel,customers are not allowed
inside cooking room. Servers are not allowed inside owner's cabin.
4. Queue:
Queue means first in first out. Railway booking counters.
4. Stack:
Stack means last in first out. Assume a movie theatre has 1000 seats which has only one gate in which people are allowed based on the seat number. Once the
show is over person who sat in 1000th seat, can come out as a first person.
5. Deque:
Deque means addition/removal is supported on both ends. Same theatre example could be applied here where it has two gates. One front gate and one back gate, visitors are allowed in both the gates.
Monday, May 16, 2011
ClassCastException while trying to cast to the same object
Recently I wanted to know how application servers are reloading jsp file. So thought of finding it myself. Tried writing a ClassLoader that extends java.lang.ClassLoader which always loads class files from the disc and not from the memory.
public class PrintObj
{
public void print()
{
System.out.println(" one ");
}
}
public class MyClassLoader extends ClassLoader
{
public Class findClass()
{
//load it from the disc and return the Class object
}
}
public class ClassLoaderTest
{
public static void main(String a[])
{
ClassLoader sysLoader = DynamicClassLoader.class.getClassLoader();
//it loads it from the memory
PrintObj l1 = (PrintObj)sysLoader.loadClass("PrintObj").newInstance();
l1.print();
MyClassLoader loader = new MyClassLoader();
PrintObj l2 = (PrintObj)loader.loadClass("PrintObj").newInstance();
l2.print();
}
}
When I am trying to execute the below code, it throws
Exception in thread "main" java.lang.ClassCastException: PrintObj cannot be cast to PrintObj. Bolded line shows ClassCastException. Interested to know that it collides with the existing PrintObj loaded by the system class loader. Then had to create an interface call Print and then made PrintObj implements that Print interface.
public interface Print
{
public void print();
}
public class PrintObj implements Print
{
System.out.println(" one ");
}
After doing the above change below code runs with out any problem.
ClassLoader sysLoader = DynamicClassLoader.class.getClassLoader();
//it loads it from the memory
Print l1 = (PrintObj)sysLoader.loadClass("PrintObj").newInstance();
l1.print();
MyClassLoader loader = new MyClassLoader();
Print l2 = (PrintObj)loader.loadClass("PrintObj").newInstance();
l2.print();
Now other issue when I tried to load the class second time it throws ,
MyClassLoader loader = new MyClassLoader();
Print l2 = (PrintObj)loader.loadClass("PrintObj").newInstance();
l2.print();
Print l3 = loader.loadClass("PrintObj").newInstance();
Exception in thread "main" java.lang.LinkageError: loader (instance of MyClassLoader): attempted duplicate class definition for name: "PrintObj". Then finally realized that a new ClassLoader() instance has to be created to reload a class every time from the disc.
public class PrintObj
{
public void print()
{
System.out.println(" one ");
}
}
public class MyClassLoader extends ClassLoader
{
public Class findClass()
{
//load it from the disc and return the Class object
}
}
public class ClassLoaderTest
{
public static void main(String a[])
{
ClassLoader sysLoader = DynamicClassLoader.class.getClassLoader();
//it loads it from the memory
PrintObj l1 = (PrintObj)sysLoader.loadClass("PrintObj").newInstance();
l1.print();
MyClassLoader loader = new MyClassLoader();
PrintObj l2 = (PrintObj)loader.loadClass("PrintObj").newInstance();
l2.print();
}
}
When I am trying to execute the below code, it throws
Exception in thread "main" java.lang.ClassCastException: PrintObj cannot be cast to PrintObj. Bolded line shows ClassCastException. Interested to know that it collides with the existing PrintObj loaded by the system class loader. Then had to create an interface call Print and then made PrintObj implements that Print interface.
public interface Print
{
public void print();
}
public class PrintObj implements Print
{
System.out.println(" one ");
}
After doing the above change below code runs with out any problem.
ClassLoader sysLoader = DynamicClassLoader.class.getClassLoader();
//it loads it from the memory
Print l1 = (PrintObj)sysLoader.loadClass("PrintObj").newInstance();
l1.print();
MyClassLoader loader = new MyClassLoader();
Print l2 = (PrintObj)loader.loadClass("PrintObj").newInstance();
l2.print();
Now other issue when I tried to load the class second time it throws ,
MyClassLoader loader = new MyClassLoader();
Print l2 = (PrintObj)loader.loadClass("PrintObj").newInstance();
l2.print();
Print l3 = loader.loadClass("PrintObj").newInstance();
Exception in thread "main" java.lang.LinkageError: loader (instance of MyClassLoader): attempted duplicate class definition for name: "PrintObj". Then finally realized that a new ClassLoader() instance has to be created to reload a class every time from the disc.
Monday, April 25, 2011
Writing an Ant Task
Many are having a need to write their own ant task, just like I had. I wanted to search some strings in a set of files and write the result into some destination files. Just listing the steps to achieve the same.
1. I work with Eclipse. Created a Java project and created the below build.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<project name="Search" basedir="." default="jar">
<target name="clean" description="Delete all generated files">
<delete dir="classes"/>
<delete file="search.jar"/>
</target>
<target name="compile" description="Compiles the Task">
<javac srcdir="src" destdir="classes"/>
</target>
<target name="jar" description="JARs the Task" depends="compile" >
<jar destfile="search.jar" basedir="classes"/>
</target>
</project>
2. Wrote a Java code which extends Task class. I wanted to have sourceFile, destFile and searchString as parameters and hence having three instance variables as sourceFileString, destFileString and searchString. On execute() method functionality has been implemented.
import org.apache.tools.ant.Task;
import java.io.*;
public class SearchTask extends Task {
private String sourceFileString = null;
private String destFileString = null;
private String searchString = null;
public void setSourceFile(String sourceFile)
{
this.sourceFileString = sourceFile;
System.out.println(" Source file set to "+sourceFile);
}
public void setDestFile(String destFile)
{
this.destFileString = destFile;
System.out.println(" dest file set to "+destFile);
}
public void setSearchString(String searchString)
{
this.searchString = searchString;
System.out.println(" search string set to "+searchString);
}
public void execute()
{
System.out.println(" Execute called ");
File sourceFile = new File(sourceFileString);
if(sourceFile.isDirectory())
{
File[] array = sourceFile.listFiles();
for(int i=0;i<array.length;i++)
{
File file = array[i];
search(file);
}
}
else
{
search(sourceFile);
}
}
private void search(File sourceFile)
{
System.out.println(" searching starts ");
BufferedReader reader = null;
BufferedWriter writer = null;
try
{
reader = new BufferedReader(new FileReader(sourceFile));
writer = new BufferedWriter(new FileWriter(destFileString));
String line = null;
while( (line = reader.readLine()) != null)
{
System.out.println(" line =="+line+" searchString "+searchString);
if(line.indexOf(searchString) > -1)
{
writer.write(line);
writer.newLine();
}
}
}
catch(Exception ee)
{
ee.printStackTrace();
}
finally
{
try
{
writer.close();
reader.close();
}
catch(Exception ee)
{
ee.printStackTrace();
}
}
}
}
3. Executed jar task and created search.jar. Then added the below task.
<target name="search" depends="jar" description="searching the file">
<taskdef name="search" classname="SearchTask" classpath="search.jar"/>
<search sourceFile="e:\\searchFile.txt" destFile="e:\\searchresult.txt" searchString="cool" >
</search>
</target>
1. I work with Eclipse. Created a Java project and created the below build.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<project name="Search" basedir="." default="jar">
<target name="clean" description="Delete all generated files">
<delete dir="classes"/>
<delete file="search.jar"/>
</target>
<target name="compile" description="Compiles the Task">
<javac srcdir="src" destdir="classes"/>
</target>
<target name="jar" description="JARs the Task" depends="compile" >
<jar destfile="search.jar" basedir="classes"/>
</target>
</project>
2. Wrote a Java code which extends Task class. I wanted to have sourceFile, destFile and searchString as parameters and hence having three instance variables as sourceFileString, destFileString and searchString. On execute() method functionality has been implemented.
import org.apache.tools.ant.Task;
import java.io.*;
public class SearchTask extends Task {
private String sourceFileString = null;
private String destFileString = null;
private String searchString = null;
public void setSourceFile(String sourceFile)
{
this.sourceFileString = sourceFile;
System.out.println(" Source file set to "+sourceFile);
}
public void setDestFile(String destFile)
{
this.destFileString = destFile;
System.out.println(" dest file set to "+destFile);
}
public void setSearchString(String searchString)
{
this.searchString = searchString;
System.out.println(" search string set to "+searchString);
}
public void execute()
{
System.out.println(" Execute called ");
File sourceFile = new File(sourceFileString);
if(sourceFile.isDirectory())
{
File[] array = sourceFile.listFiles();
for(int i=0;i<array.length;i++)
{
File file = array[i];
search(file);
}
}
else
{
search(sourceFile);
}
}
private void search(File sourceFile)
{
System.out.println(" searching starts ");
BufferedReader reader = null;
BufferedWriter writer = null;
try
{
reader = new BufferedReader(new FileReader(sourceFile));
writer = new BufferedWriter(new FileWriter(destFileString));
String line = null;
while( (line = reader.readLine()) != null)
{
System.out.println(" line =="+line+" searchString "+searchString);
if(line.indexOf(searchString) > -1)
{
writer.write(line);
writer.newLine();
}
}
}
catch(Exception ee)
{
ee.printStackTrace();
}
finally
{
try
{
writer.close();
reader.close();
}
catch(Exception ee)
{
ee.printStackTrace();
}
}
}
}
3. Executed jar task and created search.jar. Then added the below task.
<target name="search" depends="jar" description="searching the file">
<taskdef name="search" classname="SearchTask" classpath="search.jar"/>
<search sourceFile="e:\\searchFile.txt" destFile="e:\\searchresult.txt" searchString="cool" >
</search>
</target>
Friday, April 22, 2011
My Passport renewal Experience
Had my passport expired and wanted to renew it. Thought of writing it here so that it will help some people who are yet to renew their passport.
http://passport.gov.in/ is the website where we shall get all related details.
1. We can download the application form from the above site and get appointment to visit the passport office.
2. To renew we need two solid address proof. Old passport can be considered as one address proof when there is no address change. Otherwise bank passbook can be used. Ration card is not accepted as address proof. List of documents can be found in the below link.
http://passport.gov.in/cpv/checklist.htm
3. When I entered Madurai passport office, there is a long queue for certification verification. They rejected my application just because I wrote one reference address in pen. I went to ex-servicemen and filled-in a new application which had some other date of appointment. Very frustrated and left that office.
4. Second time I went there and since I had ration card as address proof they rejected my application.
5. My native is in Aruppukottai which falls in Virudhunagar district. So I went to Virudhunagar collectorate and gave 200 to get D.D and filled-in application form. This time my application entered into the system.
6. I got police verification in two weeks and they asked me to come to the police station. I went to Aruppukottai police station and waited for 3 hours to see superindent of police. He asked me two or three questions and its over.
7. I got a letter from madurai passport office saying that I need to submit the damage sworn affidavit. In fact my old passport is not at all damaged and I went there and submitted. Passport office asked me some basic questions.
8. Finally in three weeks I got the passport.
Here comes the interesting part, following are the differences in 10 years.
1. Process is very fast. In one week you can get a tatkal passport and in three weeks you can get normal passport if you have all the documents.
2. Some passport officers are very kind in nature and they are really helping the needy people.
3. Having ex-serviceman booth in passport office is really a good idea.
4. Still some passport officers are not people friendly. This is not changed even in the last 10 years.
http://passport.gov.in/ is the website where we shall get all related details.
1. We can download the application form from the above site and get appointment to visit the passport office.
2. To renew we need two solid address proof. Old passport can be considered as one address proof when there is no address change. Otherwise bank passbook can be used. Ration card is not accepted as address proof. List of documents can be found in the below link.
http://passport.gov.in/cpv/checklist.htm
3. When I entered Madurai passport office, there is a long queue for certification verification. They rejected my application just because I wrote one reference address in pen. I went to ex-servicemen and filled-in a new application which had some other date of appointment. Very frustrated and left that office.
4. Second time I went there and since I had ration card as address proof they rejected my application.
5. My native is in Aruppukottai which falls in Virudhunagar district. So I went to Virudhunagar collectorate and gave 200 to get D.D and filled-in application form. This time my application entered into the system.
6. I got police verification in two weeks and they asked me to come to the police station. I went to Aruppukottai police station and waited for 3 hours to see superindent of police. He asked me two or three questions and its over.
7. I got a letter from madurai passport office saying that I need to submit the damage sworn affidavit. In fact my old passport is not at all damaged and I went there and submitted. Passport office asked me some basic questions.
8. Finally in three weeks I got the passport.
Here comes the interesting part, following are the differences in 10 years.
1. Process is very fast. In one week you can get a tatkal passport and in three weeks you can get normal passport if you have all the documents.
2. Some passport officers are very kind in nature and they are really helping the needy people.
3. Having ex-serviceman booth in passport office is really a good idea.
4. Still some passport officers are not people friendly. This is not changed even in the last 10 years.
Thursday, April 21, 2011
My UDP based JMS Solution
Just wondered and searched udp based JMS solutions for high performance need. Could not find any and hence decided to write one through java. Till now able to create Queues and made them communicate each other. My design has,
1. A communication provider maintains a list of Queues and Topics. Mainly list of Queue Initiators and on subscription it will have Queue Clients too. It will have a list of Topic subscribers too.
2. A Queue initiator that communicates with ConnectionProvider to register the queue name and its ip/port details.
3. A Queue client that subscribes with ConnectionProvider and get the details of Queue initiator.
4. Queue initiator and Queue client can communicate each other with high performance. On closure, commuincation provider can be updated.
5. Communication Provider , Queue initiator , Queue clients are distributed. They can run in three different jvm.
6. Currently all objects are extending Thread object. But it can be enhanced by having one thread per jvm that receives all packets and then notifies clients.
Have made a working version that supports create, delete, subscribe and unsubscribe. On a i3 CPU 64 bit, 3 GB, 2.27 GHz, 2.26 GHz machine, it is able to send/receive 6700 udp packets per second. Recently have made it to support topic also.
1. A communication provider maintains a list of Queues and Topics. Mainly list of Queue Initiators and on subscription it will have Queue Clients too. It will have a list of Topic subscribers too.
2. A Queue initiator that communicates with ConnectionProvider to register the queue name and its ip/port details.
3. A Queue client that subscribes with ConnectionProvider and get the details of Queue initiator.
4. Queue initiator and Queue client can communicate each other with high performance. On closure, commuincation provider can be updated.
5. Communication Provider , Queue initiator , Queue clients are distributed. They can run in three different jvm.
6. Currently all objects are extending Thread object. But it can be enhanced by having one thread per jvm that receives all packets and then notifies clients.
Have made a working version that supports create, delete, subscribe and unsubscribe. On a i3 CPU 64 bit, 3 GB, 2.27 GHz, 2.26 GHz machine, it is able to send/receive 6700 udp packets per second. Recently have made it to support topic also.
Subscribe to:
Posts (Atom)