Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts
Thursday, December 08, 2011
Thursday, March 10, 2011
Access Application Context from JSP
<%
ApplicationContext context =
WebApplicationContextUtils.getWebApplicationContext(
pageContext.getServletContext());
MyBean myBean=(MyBean)context.getBean("myBeanId");
%>
Wednesday, November 24, 2010
When is a Singleton not a Singleton?
Yesterday happen to read this post, very nice one http://java.sun.com/developer/technicalArticles/Programming/singletons/
Wednesday, November 03, 2010
Use of static inner classes
We have HashMap.Entry class that is declared as a static inner class, I was searching for why it has been declared as static inner class and I found this post, which talks about when to use what type of inner classes.
In Short,
- Convenient way of grouping classes without using packages
- To create an instance of this class, we don't need outer class's object
- It will help you to extend from some other class
java.util.HashMap.Entry
- java.util.LinkedHashMap.Entry
- java.util.HashMap.EntrySet
- java.util.HashMap.HashIterator
- java.util.LinkedHashMap
Wednesday, September 22, 2010
Fast way to multiply a number by 7
/**
* @author Vijayan Srinivasan
* @since Sep 22, 2010 3:47:15 PM
*/
public class MulBy7 {
public static void main(String[] args) {
for(int i=0;i<10;i++){
System.out.print("i="+i+",");
int value=(i<<3)-i;
System.out.println("i*7="+value);
}
}
}
Output:
i=0,i*7=0
i=1,i*7=7
i=2,i*7=14
i=3,i*7=21
i=4,i*7=28
i=5,i*7=35
i=6,i*7=42
i=7,i*7=49
i=8,i*7=56
i=9,i*7=63
Thursday, February 04, 2010
Get Password without displaying it on console
JDK 1.6 provides option to get secret inputs without displaying them on console. Here is the code sample to do that.
System.console().readPassword("[%s]", "Password:");
Thursday, January 28, 2010
Specifying default schema name in JPA
Often we use different user name to connect to oracle database instead of the using the same user name with schema name. In that case queries needs to be prefixed with schema names. to do that in JPA we can add the following property in persistence.xml file
com.foo.bar.Test
Tuesday, January 19, 2010
Access Oracle Blob and Timestamp Columns
Many of the time we use Blob and Timestamps column in Oracle. When we access them using JDBC, we will get Oracle specific Java objects when result set is returned from DB. e.g oracle.sql.BLOB, oracle.sql.TIMESTAMP but we may need them in the form of java.sql.Blob and java.sql.Timestamp
To get it in right way we need add the following start-up properties
-Doracle.jdbc.J2EE13Compliant=true
To get it in right way we need add the following start-up properties
-Doracle.jdbc.J2EE13Compliant=true
Saturday, October 03, 2009
Ways by which singleton can be created
Singleton classes can be created in 3 ways
Case 1:
In this case the statically created object is made final and publicly exposed to everyone.
Case 2:
Case 3:
In this third case is preferable because it creates the object on-demand. But it can create issue when it is used in multi threaded environment.
So the code can be changed to case 4
Case 4:
Though it takes care multi threaded this will become a costly method. to make it a light-weight we can change the code to case 5
Case 5:
This method is an efficient but complex one, this is also called as double-null checking method. more info on this can be found in http://en.wikipedia.org/wiki/Double-checked_locking
Output:
org.vijayan.sample.Singleton@10b62c9
org.vijayan.sample.Singleton@10b62c9
org.vijayan.sample.Singleton@10b62c9
org.vijayan.sample.Singleton@10b62c9
Please note all 4 times it returns the same object reference.
Case 1:
package org.vijayan.sample;
public class Singleton {
/**
* Advanced Initialization
*/
public static final Singleton SINGLETON=new Singleton();
private Singleton(){
}
public static void main(String[] args) {
for(int i=0;i<4;i++){
System.out.println(Singleton.SINGLETON);
}
}
}
In this case the statically created object is made final and publicly exposed to everyone.
Case 2:
package org.vijayan.sample;
public class Singleton {
/**
* Advanced Initialization
*/
private static Singleton singleton=new Singleton();
private Singleton(){
}
public static Singleton getInstance(){
return singleton;
}
public static void main(String[] args) {
for(int i=0;i<4;i++){
System.out.println(Singleton.getInstance());
}
}
}
Case 3:
package org.vijayan.sample;
public class Singleton {
/**
* Lazy Initialization
*/
private static Singleton singleton=null;
private Singleton(){
}
public static Singleton getInstance(){
if(singleton==null){
singleton=new Singleton();
}
return singleton;
}
public static void main(String[] args) {
for(int i=0;i<4;i++){
System.out.println(Singleton.getInstance());
}
}
}
In this third case is preferable because it creates the object on-demand. But it can create issue when it is used in multi threaded environment.
So the code can be changed to case 4
Case 4:
package org.vijayan.sample;
public class Singleton {
/**
* Lazy Initialization
*/
private static Singleton singleton=null;
private Singleton(){
}
/**
*
* Will take care multi threaded environment but it expensive
*/
public static synchronized Singleton getInstance(){
if(singleton==null){
singleton=new Singleton();
}
return singleton;
}
public static void main(String[] args) {
for(int i=0;i<4;i++){
System.out.println(Singleton.getInstance());
}
}
}
Though it takes care multi threaded this will become a costly method. to make it a light-weight we can change the code to case 5
Case 5:
package org.vijayan.sample;
public class Singleton {
/**
* Lazy Initialization
*/
private static Singleton singleton=null;
private Singleton(){
}
/**
*
* Will take care multithreaded environment also less expensive
*/
public static Singleton getInstance(){
if(singleton==null){
synchronized (Singleton.class) {
if(singleton==null){
singleton=new Singleton();
}
}
}
return singleton;
}
public static void main(String[] args) {
for(int i=0;i<4;i++){
System.out.println(Singleton.getInstance());
}
}
}
This method is an efficient but complex one, this is also called as double-null checking method. more info on this can be found in http://en.wikipedia.org/wiki/Double-checked_locking
Output:
org.vijayan.sample.Singleton@10b62c9
org.vijayan.sample.Singleton@10b62c9
org.vijayan.sample.Singleton@10b62c9
org.vijayan.sample.Singleton@10b62c9
Please note all 4 times it returns the same object reference.
Synchronization usecases
Consider a class called A, it has m1() and m2() methods, 2 instance of this A class is created a1 and a2 and there are 2 threads t1, t2
Case 1: m1() and m2() are not synchronized
t1 uses a1 and calls m1()
t2 uses a2 and calls m2()
both thread t1 and t2 can run at the same time because both threads are using different objects.
Case 2: m1() and m2() are synchronized
t1 uses a1 and calls m1()
t2 uses a2 and calls m2()
both thread t1 and t2 can run at the same time because both threads are using different objects.
by default synchronization will acquire lock on the object, since here both are using different object locking will not happen.
Case 3: m1() and m2() are synchronized
t1 uses a1 and calls m1()
t2 uses a1 and calls m2()
both thread t1 and t2 cannot run at the same time because both threads are using same object.
if t1 first access m1() then t2 will have to wait for t1 to complete running m1()
Case 4: m1() is static and m2() is non static and both are synchronized
t1 uses a1 and calls m1()
t2 uses a1 and calls m2()
both thread t1 and t2 can run at the same time because though both threads are using same object when t1 first access m1() it is not accessing via a1 object rather it will use A class for accessing the static method that is A.m1() is what called. For doing the same A.Class object will be created and it will be synchronized using A.Class object and t2 will be using a1 object for locking since both objects are different they can work parallel.
Case 5: m1() is static and m2() is static and both are synchronized
t1 uses a1 and calls m1()
t2 uses a1 and calls m2()
both thread t1 and t2 cannot run at the same time because though both threads are using same object (A.Class object)
Why synchronization in java?
Consider the following programs
package org.vijayan.sample;
public class Main {
public static void main(String[] args) {
SampleFile file=new SampleFile("test.txt");
FileWriterThread mt1=new FileWriterThread(10000,"MT1", file);
FileWriterThread mt2=new FileWriterThread(20,"MT2", file);
mt1.start();
mt2.start();
}
}
package org.vijayan.sample;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class SampleFile {
private File file;
public SampleFile(String fileName){
file=new File(fileName);
file.delete();
}
public void writeMessage(int count, String message){
try {
FileWriter writer=new FileWriter(file,true);
for(int i=0;i
writer.write(message+"-"+i);
writer.write("\n");
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package org.vijayan.sample;
public class FileWriterThread extends Thread {
private SampleFile file;
private int count;
public FileWriterThread(int count, String name, SampleFile math){
super(name);
this.file=math;
this.count=count;
}
@Override
public void run() {
file.writeMessage(count, getName());
}
}
Output of the above program can result
MT1-1026
MT1-1027
MT1-1028
MT1-1029
MT1-1030
MT1-1031
MT1-1032
MT1-1MT2-0
MT2-1
MT2-2
MT2-3
MT2-4
MT2-5
MT2-6
MT2-7
MT2-8
MT2-9
MT2-10
MT2-11
MT2-12
MT2-13
MT2-14
MT2-15
MT2-16
MT2-17
MT2-18
MT2-19
033
MT1-1034
MT1-1035
MT1-1036
MT1-1037
Please note the bold lines carefully. In this case both thread is using same SampleFile Object and both thread is writing to a same file concurrently. Since there is no synchronized keyword for writeMessae() it is possible. if we make this method synchronized like below
public synchronized void writeMessage(int count, String message){
try {
FileWriter writer=new FileWriter(file,true);
for(int i=0;i
writer.write(message+"-"+i);
writer.write("\n");
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
then the output will change to like the following
MT1-9994
MT1-9995
MT1-9996
MT1-9997
MT1-9998
MT1-9999
MT2-0
MT2-1
MT2-2
MT2-3
MT2-4
MT2-5
MT2-6
MT2-7
MT2-8
MT2-9
MT2-10
MT2-11
MT2-12
MT2-13
Output 2 indicates that though both thread is started running the second thread is waiting until first thread completes its operation. though it is providing desired output we may not want to make the second thread wait until full completion of thread 1. This can be achieved by changing the program to following ways.
package org.vijayan.sample;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class SampleFile {
private FileWriter writer;
public SampleFile(String fileName){
File file=new File(fileName);
file.delete();
try {
writer=new FileWriter(file,true);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void finalize() throws Throwable {
super.finalize();
writer.close();
}
public void writeMessage(int count, String message){
try {
for(int i=0;i
synchronized (writer) {
writer.write(message+"-"+i);
writer.write("\n");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
MT1-1218
MT1-1219
MT2-0
MT2-1
MT2-2
MT2-3
MT2-4
MT2-5
MT2-6
MT2-7
MT2-8
Please note adding a synchronized block requires some extra code and it always needs to be done carefully.
Monday, September 14, 2009
equals(), hashCode() and toString() methods in Object
//hashCode in Object class
public native int hashCode();
//Java doc for hashCode()
int java.lang.Object.hashCode()
Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.
The general contract of hashCode is:
* Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
* If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
* It is not required that if two objects are unequal according to the java.lang.Object.equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)
//equals() method in Object class
public boolean equals(Object obj) {
return (this == obj);
}
package object;
public class User {
private String firstName;
private String lastName;
private Integer mark;
public User(String firstName,String lastName, Integer mark){
setFirstName(firstName);
setLastName(lastName);
setMark(mark);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getMark() {
return mark;
}
public Integer setMark(Integer mark) {
this.mark = mark;
}
}
package object;
public class ObjectTest {
public static void main(String[] args) {
User user1=new User("Vijayan", "Srinivasan", new Integer(100));
User user2=new User("Vijayan", "Srinivasan", new Integer(100));
System.out.println("[user1==user2]="+(user1==user2));
System.out.println("[user1.equals(user2)]="+user1.equals(user2));
}
}
So both case it is giving false becasue, both of the statements uses the same logic to compare 2 objects. For getting this right we have to do the following.
//Override equals() method in User class
public boolean equals(Object object) {
if(object instanceof User){
User user=(User) object;
return
equals(firstName,user.firstName) &&
equals(lastName,user.lastName) &&
equals(mark,user.mark);
}
return false;
}
// Implementation of toString() in Object class
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
Although it is sufficient that overriding equals methods alone sufficient here it is adviced to override also for better performance. //Why?
// implementation of put() method in Hashtable class
public Object put(Object key, Object value) {
// Make sure the value is not null
if (value == null) throw new NullPointerException();
// Makes sure the key is not already in the hashtable.
HashtableEntry e;
HashtableEntry tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) { //<------ Look here
Object old = e.value;
e.value = value;
return old;
}
}
Please note if we have proper hashCode() impelentation there is no need of calling the equals() method at all. Hence if the object is different we can let the Hashtable know ahead of calling equals() method. That is the reason it is always important to implement hashCode() when ever we override the equals()
Thursday, August 20, 2009
Jboss JDBC Driver Loading Issue
If we configure data source throug *-ds.xml (e.g. mysql-ds.xml) file in Jboss and the corresponding JDBC driver jar is only available in a WEB-INF/lib folder of an application, even though the same application tries to get a connection through configured data source, first time it will throw an ClassNotFoundException. As the class would not have loaded until the first call.
But if we try to get connection second time it will work with out any exception. This problem can be rectifed by keeping the copy of the JDBC driver jar in /server//lib folder (e.g. c:\jboss 4.0.2 \server\default\lib). This will ensure that the driver jar will be loaded in to ClassLoader at the time of server starting.
Monday, August 17, 2009
Incorrect arguments to mysql_stmt_execute
When we use MySQL connector mysql-connector-java-5.0.4-bin.jar with PreparedStatement contains more number of columns we may get the following Exception
java.sql.SQLException: Incorrect arguments to mysql_stmt_execute
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:946)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1573)
To fix this issue we have to use mysql-connector-java-5.1.8-bin.jar
java.sql.SQLException: Incorrect arguments to mysql_stmt_execute
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:946)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1573)
To fix this issue we have to use mysql-connector-java-5.1.8-bin.jar
Friday, June 26, 2009
Java FTP Sample Code
Writing FTP Code using ANT is very simple compare to we write the same using FTPClient class. This post will explain you how to do basic FTP operation through ANT FTP task classes.
import java.io.File;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.optional.net.FTP;
import org.apache.tools.ant.types.FileSet;
public class FtpUsingAnt {
public static void main(String[] args) {
ftpGetSample();
ftpDeleteTaskSample();
}
public static void ftpGetSample(){
FTP ftp=new FTP();
FTP.Action action=new FTP.Action();
action.setValue("get");
ftp.setAction(action);
ftp.setServer("server.com");
ftp.setUserid("user-name");
ftp.setPassword("password");
ftp.setRemotedir("/remote-folder");
FileSet fileSet=new FileSet();
File dir=new File("c:\\local-folder");
fileSet.setDir(dir);
fileSet.setIncludes("**/*.csv");
ftp.addFileset(fileSet);
callAntTask(ftp, "ftp");
}
public static void ftpDeleteTaskSample() {
FTP ftp=new FTP();
FTP.Action action=new FTP.Action();
action.setValue("del");
ftp.setAction(action);
ftp.setServer("server.com");
ftp.setUserid("user-name");
ftp.setPassword("password");
ftp.setRemotedir("/remote-folder");
FileSet fileSet=new FileSet();
File dir=new File("."); // Not Needed
fileSet.setDir(dir);
fileSet.setIncludes("**/*.csv");
ftp.addFileset(fileSet);
callAntTask(ftp, "ftp");
}
public static void callAntTask(Task task, String taskName){
DefaultLogger logger=new DefaultLogger();
logger.setMessageOutputLevel(Project.MSG_DEBUG);
logger.setOutputPrintStream(System.out);
logger.setErrorPrintStream(System.err);
Project project=new Project();
project.addBuildListener(logger);
task.setProject(project);
task.setTaskName(taskName);
task.execute();
}
}
Monday, June 22, 2009
How Class.forName() registers driver?
Most of the time for registering driver to DriverManager, we use the following code.
But Class.forName() method will not do any registration of Driver with DriverManager. If that is the case how DriverManager.registerDriver() (registration) is called?
This is snippet is taken from com.mysql.jdbc.Driver class's source code. So if you closely watch this code, when ever
Class.forName("com.mysql.jdbc.Driver");
But Class.forName() method will not do any registration of Driver with DriverManager. If that is the case how DriverManager.registerDriver() (registration) is called?
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (java.sql.SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
This is snippet is taken from com.mysql.jdbc.Driver class's source code. So if you closely watch this code, when ever
Class.forName("com.mysql.jdbc.Driver");is invoked as soon as the class is loaded in to the memory, all static blocks of that classes are also being invoked. Insite one of the static block all driver classes are registering them self to DriverManager.
Tuesday, June 09, 2009
Unzip Using Ant Code
package com.test.ant;
import java.io.File;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Expand;
public class AntUnzip {
public static void main(String[] args) {
File src = new File("1.zip"); // Source Zip File Name
File dest = new File("test"); // Destination Folder Name
Expand expand = new Expand();
expand.setSrc(src);
expand.setDest(dest);
callAntTask(expand, "Unzip");
}
public static void callAntTask(Task task, String taskName) {
DefaultLogger logger = new DefaultLogger();
logger.setMessageOutputLevel(Project.MSG_DEBUG);
logger.setOutputPrintStream(System.out);
logger.setErrorPrintStream(System.err);
Project project = new Project();
project.addBuildListener(logger);
task.setProject(project);
task.setTaskName(taskName);
task.execute();
}
}
ClassNotFoundException vs. NoClassDefFoundError
Many a times we will come across these exceptions, though they look similar there is a clear difference between these two classes.
First compile all these classes. Once compilation is complete, then run the class B and C
You will get the following output.
Now delete class A and re-run the classes B & C
package com.test;
/**
* @author Vijayan Srinivasan
* @since Sep 22, 2010 9:16:46 PM
*/
public class A {
public void print() {
System.out.println("I am A");
}
}
package com.test;
/**
* @author Vijayan Srinivasan
* @since Sep 22, 2010 9:16:46 PM
*/
public class B {
public static void main(String[] args) {
try {
Class clazz = Class.forName("com.test.A");
A a = (A) clazz.newInstance();
a.print();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
package com.test;
/**
* @author Vijayan Srinivasan
* @since Sep 22, 2010 9:16:46 PM
*/
public class C {
private A a = new A();
public static void main(String[] args) {
new C().a.print();
}
}
First compile all these classes. Once compilation is complete, then run the class B and C
You will get the following output.
C:\Test\bin>java com.test.C
I am A
C:\Test\bin>java com.test.B
I am A
Now delete class A and re-run the classes B & C
C:\Test\bin>java com.test.C
Exception in thread "main" java.lang.NoClassDefFoundError: com/test/A
at com.test.C.(C.java:12)
at com.test.C.main(C.java:15)
Caused by: java.lang.ClassNotFoundException: com.test.A
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
... 2 more
C:\Test\bin>java com.test.B
java.lang.ClassNotFoundException: com.test.A
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at com.test.B.main(B.java:15)
Subscribe to:
Posts (Atom)