Saturday, July 17, 2010

How to use ThreadLocal

Target audience: Beginners and Intermediates

ThreadLocal is a class provides way to hold thread local variables and provide access to get and set values. in other words, it allows you to have copy of variables per thread and these variables will be garbage collected when the associated thread dies. ThreadLocal instances are advised to be private static fields in classes.For example, check the Audit class bellow
class Audit {
private static ThreadLocal auditDetails = new ThreadLocal();

public static String get() {
return (String) auditDetails.get();

public static void set(String details) {

Here, auditDetails is a thread local variable. The set(String) method of Audit class sets a value in thread local variable auditDetails. As auditDetails is a static, it will be shared with multiple threads but the value which is set will belong to only the current thread.The JVM finds the current thread and associate the value. And when get(String) method of Audit is called, the auditDetails returns the value associated with current thread. The following example will help you to understand it more.

package basics;

public class ThreadLocalExamples {

public void methodA() {

//Generates a random value
int value = (int)(Math.random()*100);

//Prints the current thread and the generated random value
System.out.println("Setting " +value+ " to " +Thread.currentThread().getName());

//Set the random value as audit details

//Keeping the threads on sleep mode for some time
try {
} catch (InterruptedException e) {

public void methodB() {

//Just prints the audit details value set for the current thread

public static void main(String[] args) {

final ThreadLocalExamples examples = new ThreadLocalExamples();

//Creates thread one and call methodA() on examples
Thread threadOne = new Thread() {
public void run() {

//Creates thread two and call methodA() on the same instance examples
Thread threadTwo = new Thread() {
public void run() {

//Starting the threads
if you look at the code, there are two methods methodA() and methodB().The methodA() generates a random number and set it as audit details and calls the methodB().The static method set(string) in Audit class is called to set audit details to the thread local .The methodB() gets the audit details and prints it. The static method get() in Audit class is called to get audit details from thread local. The main method creates creates one instance of ThreadLocalExamples and two instances of threads. Both thread instances call the methodA() of same instance of ThreadLocalExamples in their run() method.
Note: The same instance of ThreadLocalExamples is accessed by two threads at the same time.
If you run the program, you will get something like the following output
Setting 13 to ThreadOne
Setting 67 to ThreadTwo

if you analyze the output results, Thread one sets ‘13 ‘ to thread local, then Thread two sets ‘67 ‘ to thread local.Even though both threads access the same thread local instance to set the value. the values are set to the current thread’s local values. That’s why when it prints the value, the value associated to the current thread is retrieved and printed.

So one again i say it, ThreadLocal is a class provides way to hold thread local variables and provide access to get and set values. in other words, it allows you to have copy of variables per thread and these variables will be garbage collected what the thread dies.

Thursday, July 15, 2010

Be aware of Autoboxing

Target audience: Beginners and Intermediates
Autoboxing is a feature added in Java 5. Boxing and unboxing give convenient ways to use Wrapper classes. The following example shows how it was used to create a Wrapper class and unwrapp it in versions previous to Java 5 and How it is used with Java 5 autoboxing

//Without autoboxing
Integer one = new Integer(1);
int intOne = one.intValue();
System.out.println("Value of one = " + intOne);

//With autoboxing
Integer intTwo = 2;
System.out.println("Value of two= " + intTwo);

I think we all know about this. But i would like to suggest to be careful when autoboxing is used. Just have a look at the bellow example.

package features;

public class AutoboxingExamples {

public static void main(String[] args) {

Integer i1 = 200;
Integer i2 = 200;
if (i1 == i2) {
} else {

Integer i3 = 10;
Integer i4 = 10;
if (i3 == i4) {
} else {

The output of this program is:



Ohh... what’s happening here??.The i1 and i2 looks fine as normal. we could also predict that two references will be different because we know JVM creates two separate instances and i1 == i2 will be return false. But what happend to i3 and i4? should not it be also ‘different’? “i3 and i4” look even same as “i1 and i2” except the value 100 and 10 respectively.

Oki, let me explain what’s happening.
When the JVM interprets the code, it interprets the Integer i3 = 10; to Integer.valueOf(10);
//Code we wrote
Integer i3 = 10;

//code JVM interprited
Integer i3 = Integer.valueOf(10);

What is happening with Integer.valueOf() is, it uses in memory cache and if the value given(eg: 10) to create the Interger object is small( between -128 and 127) then it gets the object from the cache.The cache is created while loading the IntegerCache class with it’s static block. look at the code of Integer.valueOf() method.
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
return new Integer(i);

So if int value falls between -128 and 127, the JVM gives us the same objects, that’s why we got true for i3==i4 condition.Java uses in memory cache for small integers to improve the performance.

Not only the Integer wrapper class but the following wrappers also behave the same way
Character from \u0000 to \u007f (7f is 127 in decimal)
Short and Integer from -128 to 127

Better be careful when we have conditions with autoboxing.

Wednesday, July 14, 2010

Using Apache Ant as template engine while building an Application

Target audience: Beginners
There will be situations where we may have more than one properties files having same values for keys. For Example, there can be different properties files but have the same value for server URL or JNDI Provider URL. These values will vary depends on the environment we deploy the Application. For Example, Server URL will be in UAT (User Acceptance Testing) environment and it will be in production. We have to change all the places in all properties file whenever we deploy the application. It is Ok, if it’s only in one or two places. But what if there are several places to be changed and lot of values like this Server URL. It’ll be a headache.

What can be done?
What we can do is, we can use keys for all the configuration values and replace all the keys with the actual values when the application is built.

Let me explain, we can use a key for Server URL and this key will be used in all properties file. Where ever the Server URL is used, this key will be used instead. Ok, Assume that now we are going to use a key myapp.config.serverurl in all the places where Server URL is used. And we are going to replace this key with the actual value when we build the application. The idea is to replace all the actual values while building. We can keep the actual values in a configuration file with key value pair.

It sounds better, and how can we do this?
We can do this with Apache Ant. As you all know, Ant is a Java-based build tool widely used for building java projects. We can make use of replace task and do out work.Suppose, My application has properties file called, then I’ll make a file and myapp.config files. The file will have all configuration values replace with keys and the myapp.config will have entries for those keys and values. At the build time the Ant build system that I am going to create will generate the final file which will be used for deployment

I keep all files, myapp.config and build.xml in one folder and file also will be generated in the same folder


The myapp.config

Ant build file

includes="*.properties" />

Once you run the ant task, the file will be generated. The generated file will look like the following

How to check loaded classes and from which JAR file they were loaded

Target audience: Beginners

Sometimes we run into issue like loading a class from unexpected location or from JAR file in a different place. We might have placed the JAR in one location but there could be same JAR loaded from different location by class loader based on the class loading preferences but we could found difficulties to resolve the issue. In this kind of scenarios, we might need to find the actual JAR file from which the class files was loaded.

How can we find the loaded classes and its JAR files from which they were loaded?
Java has an JVM option -verbose:class. if we run the JVM with this option, then it will list out all classes thar are loaded by JVM and those classes’s JAR file with location. This will be really helpful resolving loading classes from unexpected JAR files.
C:\Projects\MyWork>java -verbose:class org.test.TestMyClass

If you wish you can try out an opensource tool called Joops too.

Tuesday, July 13, 2010

CSS Style of Command Prompt or Console

In one of my blog post, I wanted to show some text as how it would look like in command prompt or console. Then i created a CSS style which will make the in-line text to be looked like texts in command prompt or console. Hope it will help you too.


Output will be:


How to use encrypted password in JBoss datasource

Target audience: Beginners
Version: JBoss 4.x

We configure the datasources in *-ds.xml files and place those files under \server\xxx\deploy location. The JBoss will scan any *-ds.xml under this location and create datasources.

I’m going to explain only how to use encrypted password in datasource configuration and i hope you all know how to configure the datasource. In this section, i going to configure a XA datasource with encrypted password.

JBoss provides a way to do configure datasource using encrypted password. The way is to use a “security-domain” property in the -ds.xml. This property should be mapped to a policy in login-config.xml under \server\xxx\conf location.

Look at the following sample -ds.xml files . I have commented out the section that are used when a clear text password is used.






A “security-domain” property is defined(or mapped) with a value “OracleDSEncryptedLogon”. This “OracleDSEncryptedLogon” is called login policy and it should be defined in login-config.xml .
Ok, How do we define the login policy?. The bellow section shows how to defined a login policy in login-config.xml under \server\xxx\conf location.



As you see, A “OracleDSEncryptedLogon” is defined with a user name and a password. The password is a encrypted password and it should be an encrypted password. The is used as code. This is a JBoss’s built in tool to encrypt and decrypt text.
Note: As i use XA datatsource, i have configured “managedConnectionFactoryName” module option with the jndi name “XAOracleDS” given in -ds.xml file and with the service “XATxCM”.

Ok, Now we know how to configure the encrypted password. But i think we have to encrypt the password . It can be done with the same jboss tool Follow the steps
Step 1.Open a command prompt
Step 2. Go to your JBoss home (C:/Tools/jboss-4.2.3.GA/)
Step 3. Set /bin to the path if it has not been set yet.
Step 4. Excecute bellow command to run the encryption tool to generate the encrypted password.

java -cp lib/jboss-common.jar:lib/jboss-jmx.jar:server/default/lib/jbosssx.jar:server/default/lib/jboss-jca.jar password
you will see the
Encoded password: 5dfc52b51bd35553df8592078de921bc
Once you configured everything then just restart the server.
Hope this note will be helpful for you.