Showing posts with label example-code. Show all posts
Showing posts with label example-code. Show all posts

Monday, 20 June 2011

save image from clipboard to file

This is how we can save image from clipboard:

import java.io.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.datatransfer.*;
import javax.imageio.*;

public class clipimg
{
public static
void main(String[] args)
throws Exception
{
System.err.println("usage: java clipimg [filename]");
String outputfile="/temp/1.png";
if(args.length > 0)outputfile=args[0];
copyTo(outputfile);
}

static
int copyTo(String filename) throws Exception {
Transferable content = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
if(content==null){
System.err.println("error: nothing found in clipboard");
return 1;
}
if(!content.isDataFlavorSupported(DataFlavor.imageFlavor)){
System.err.println("error: no image found in clipbaord");
return 2;
}
BufferedImage img = (BufferedImage)content.getTransferData(DataFlavor.imageFlavor);
String ext = ext(filename);
if(ext==null){
ext="png";
filename+="."+ext;
}
File outfile=new File(filename);
ImageIO.write(img,ext,outfile);
System.err.println("image copied to: " + outfile.getAbsolutePath());
return 0;
}

static String ext(String filename){
int pos=filename.lastIndexOf('.')+1;
if(pos==0 || pos >= filename.length() )return null;
return filename.substring(pos);
}
}

Sunday, 19 June 2011

Java has a nanosecond timer!

Java has a nanosecond timer!

It works well too.

Quick test script:

We do empty loops of varying numbers of iterations, and use the nanotimer to test how long that takes:

for( int its = 0; its < 100; its++ ) {
long start = System.nanoTime();
for( int i = 0; i < its; i++ ) {
}
long delta = System.nanoTime() - start;
System.out.println("its " + its + ": " + delta );
}

Saturday, 18 June 2011

Java Locks : Re-entrant locks

Java concurrency library provides more control over synchronization than synchronized. Either we need to control types of access (read and write) separately, or it is cumbersome to use because either there is no obvious mutex or we need to maintain multiple mutexes. So doing it by synchronized will eat lot of time and will be buggy as well.
Thankfully, lock utility classes were added in Java 1.5 and make these problems easier to solve.

Java Reentrant Locks


Java has a few lock implementations in the java.util.concurrent.locks package.
The general classes of locks are nicely laid out as interfaces:
  • Lock - the simplest case of a lock which can be acquired and released
  • ReadWriteLock - a lock implementation that has both read and write lock types – multiple read locks can be held at a time unless the exclusive write lock is held
Java provides two implementations of these locks that we care about – both of which are reentrant (this just means a thread can reacquire the same lock multiple times without any issue).
  • ReentrantLock - as you’d expect, a reentrant Lock implementation
  • ReentrantReadWriteLock - a reentrant ReadWriteLock implementation

Extended capabilities with Reentrant locks

The ReentrantLock in the util.concurrent.locks package gives the developers some flexibility here. With ReentrantLock following are some of the options

  1. tryLock() : With ReentrantLock, the thread can immediately return if it did not get the lock (if the lock is with some other thread).
  2. tryLock(long timeout, TimeUnit unit):With ReentrantLock, the thread can wait for some duration to get hold of the lock. If it does not get the lock within some time, it will return.
  3. lockInterruptibly() : With ReentrantLock, the thread waiting for the lock can be interrupted and cause it to come out with InterruptedException.
Now, let’s see some examples. So the general way to use re-entrant lock is like this :
final ReentrantLock _lock = new ReentrantLock();

private void method() throws InterruptedException
{
//Trying to enter the critical section
_lock.lock(); // will wait until this thread gets the lock
try
{
// critical section
}
finally
{
//releasing the lock so that other threads can get notifies
_lock.unlock();
}
}

Using optional “fairness” parameter with ReentrantLock
ReentrantLock accepts an optional “fairness” parameter in it’s constructor. Normally what happens is, whenever a thread releases the lock anyone of the waiting threads will get the chance to acquire that lock. But there is no predefined order or priority in the selection of the thread (at least from a programmers perspective).

But if we are specifying the fairness parameter as “true” while creating a new ReentrantLock object, it gives us the guaranty that the longest waiting thread will get the lock next. Sounds pretty nice right?

Use of “Condition” in ReentrantLock
Condition can be considered as a separation of monitor methods (wait(), notify() & notifyAll()). For each ReentrantLock we can define a set of conditions and based on that we can make the threads waiting & things like that.

import java.util.concurrent.locks.Condition;
final Condition _aCondition = _lock.newCondition();
private void method1() throws InterruptedException
{
_lock.lock();
try
{
while (condition 1)
{
// Waiting for the condition to be satisfied
// Note: At this time, the thread will give up the lock
// until the condition is satisfied. (Signaled by other threads)
_aCondition.await();
}
// method body
}
finally
{
_lock.unlock();
}

}

private void method2() throws InterruptedException
{
_lock.lock();
try
{
doSomething();
if (condition 2)
{
// Signaling other threads that the condition is satisfied
// Wakes up any one of the waiting threads
_aCondition.signal();

// Wakes up all threads waiting for this condition
_aCondition.signalAll();
}

// method body
}
finally
{
_lock.unlock();
}
}


Example


We will take the same example of counter again. We have already seen how to implement counter using synchronized keyword here. Here we will see how to implement using Reentrant locks:
Counter.java

package com.vaani.lock;

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

public class Counter {
private int count;
private Lock lock = new ReentrantLock();

public int getNextValue() {
try {
lock.lock();
count++;
}
finally {
lock.unlock();
return count;
}

}


}

Worker.java
Now worker threads starts on the counter object and start incrementing the value:

package com.vaani.lock;

public class Worker implements Runnable {
private Counter counter;
private boolean increment;
private int count;

public Worker(Counter counter, boolean increment, int count) {
this.counter = counter;
this.increment = increment;
this.count = count;
}

public void run() {
for (int i = 0; i < this.count; i++) {
System.out.println(this.counter.getNextValue());


}
}
}

Now let's put worker's on work – as in demo:

package com.vaani.lock.demo;
import com.vaani.lock.*;
public class ReentrantLockDemo {
public static void main(String[] args) throws Exception {
Counter counter = new Counter();
Thread t1 = new Thread(new Worker(counter, true, 10000));
t1.start();
Thread t2 = new Thread(new Worker(counter, false, 10000));
t2.start();

t1.join();
t2.join();
System.out.println("Final count: " + counter.getNextValue());
}
}


Download the source



Source code above can be downloaded from here.


Monday, 13 June 2011

The Callable Interface

One of the beautiful things about Java from its very first release was the ease with which we could write multi-threaded programs and introduce asynchronous processing into our designs. The Thread class and Runnable interface combined with Java’s memory management model meant for straightforward thread programming.

The run() method in Runnable cannot return a result (i.e. it returns void) and cannot throw a checked exception. If you try to throw an exception in a run() method, the javac compiler insists that you use a throws clause in the method signature. However, the superclass run() method doesn't throw an exception, so javac will not accept this. The lack of thrown checked exceptions was a little more serious.

Even if you were careful and you stored these for later verification, you couldn’t force all uses of the class to check the exception. You could go through all your getters and throw the Exception if it existed on each one. Besides being cumbersome, even that wasn’t foolproof. You couldn’t enforce calls to any of these. Thread programmers would correctly call join() to wait for it complete and may then have gone on their merry way.

The new java.util.concurrent.Callable interface is much like Runnable but overcomes two drawbacks with Runnable.
The interface looks like this :
public interface Callable<V> {
V call() throws Exception;
}


Implementing Runnable to get returned value
If you need a result from a Runnable task, you have to provide some external means of getting that result. A common technique is to set an instance variable in the Runnable object and provide a method to retrieve that value. For example,

public MyRunnable implements Runnable
{
private int fResult = 0;
public void run () {
...
fResult = 1;
} // run

// A getter method to provide the result of the thread.
public int getResult () { return fResult; }

} // class MyRunnable


Even if you were careful and you stored these for later verification, you couldn’t force all uses of the class to check the exception. You could go through all your getters and throw the Exception if it existed on each one. Besides being cumbersome, even that wasn’t foolproof. You couldn’t enforce calls to any of these. Thread programmers would correctly call join() to wait for it complete and may then have gone on their merry way.
Implementing the Callable
The Callable interface solves these problems. Instead of a run() method the Callable interface defines a single call() method that takes no parameters but is allowed to throw an exception. A simple example is

import java.util.concurrent.*;
public class MyCallable implements Callable
{
public Integer call () throws java.io.IOException {
return 1;
}
} // MyCallable

This call() method returns an Integer. (Note that we have conveniently used the autoboxing support in J2SE 5.0 to have the literal int 1 value automatically boxed into an Integer return value.)

Note
The call() method is the entry point into a Callable object, and it's return type is the type parameter set in the Callable object. To implement Callable with no return value, use Callable<void>. Also, note that the call() method throws a checked exception, as compared to the run() method in Runnable which does not throw any exception. The Executors class contains utility methods to convert from other common forms to Callable classes. However, Callable cannot be used in place of a Runnable. Callable objects have to be invoked by ExecutorService. The Executor framework provides the Future interface to allow handling the cancellation and returns of a Callable object.

Getting the return value from a Callable depends upon the new generics feature:

FutureTask task = new FutureTask (new MyCallable ());
ExecutorService es = Executors.newSingleThreadExecutor ();
es.submit (task);
try {
int result = task.get ();
System.out.println ("Result from task.get () = " + result);
}
catch (Exception e) {
System.err.println (e);
}
es.shutdown ();

Here, we use the FutureTask class that supports an Integer return value. Then the task is submitted using the ExecutorService submit() method, and the result is obtained from the FutureTask get() method, again using auto-unboxing to convert the Integer to an int. See the API documentation for more information on ExecutorService, and FutureTask.

 

Callable Example


CallableImpl.java


package com.vaani.callable;

import java.util.concurrent.Callable;

public class CallableImpl implements Callable<Integer> {

private int name;
public CallableImpl(int i){
name = i;
}

public Integer call() {
for(int i = 0; i < 10; i++) {
System.out.println("Thread : " + getName() + " I is : " + i);
}
return new Integer(getName());

}

public int getName() {
return name;
}

public void setMyName(int myName) {
this.name = myName;
}

}

CallableDemo.java



public class CallableDemo {

public static void main(String[] args) {
Callable<Integer> callable = new CallableImpl(2);

ExecutorService executor = new ScheduledThreadPoolExecutor(5);
Future<Integer> future = executor.submit(callable);

try {
System.out.println("Future value: " + future.get());
} catch (Exception e) {
e.printStackTrace();
}
}
}

Also we have future which is similar to Callable except Future represents the result of an asynchronous computation. But it is discussed here.







Download the source


Source code can be downloaded from here.

Monday, 6 June 2011

EasyMock for Unit Tests

What is mock object?
A mock object is a dummy interface or class in which you define the dummy output of a certain method call. These objects can be provided to the class which should be tested to avoid any dependency to external data. The classical example is a mock object for a data provider. In production a real database is used but for testing a mock object simulates the database and ensures that the test conditions are always the same.

What is easy mock?
This basic requirement of creating mock object can be accomplished by using Easy mock. Easy mock is a library that helps to dynamically create mock objects. This way we can avoid much of the tedious work involved in manually coding mock objects. However, EasyMock itself is not the silver bullet, we still have to define expectations in test cases. Using EasyMock also means that you have make certain design changes (if your design follows the usual design principles you may not have to change much. Here's a sample Unit Test using EasyMock. You can download easymock from here.
Class Under Test
DateFormatter.java
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormatter {
public static final String DATE_FORMAT = "MM/dd/yyyy";

private DateFormatterHelper helper = null;

public DateFormatter() {
}

public String convertToStandardFormat(String dateString, String format)
throws ParseException {
if (dateString == null || dateString.equals(""))
return "";
dateString = dateString == null ? "" : dateString;
DateFormat df = helper.getDateFormat(format);
Date date = df.parse(dateString);
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
return sdf.format(date);
}

public DateFormatterHelper getHelper() {
return helper;
}

public void setHelper(DateFormatterHelper helper) {
this.helper = helper;
}
}

Testing the class

Helper Class and Interface: If you are to mock any class using EasyMock, it is required that you have an interface for the class. If you are following the old design principle "program to an interface, not an implementation", you are good here.

package sample;

import java.text.DateFormat;

public interface DateFormatterHelper {
public DateFormat getDateFormat(String format);
}

DateFormatterHelperImpl.java
public class DateFormatterHelperImpl 
implements DateFormatterHelper {

public DateFormatterHelperImpl() {
}

public DateFormat getDateFormat(String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setCalendar(Calendar.getInstance());
sdf.setLenient(false);
return sdf;
}


public static void main(String args[]) {
DateFormatterHelper helper = new DateFormatterHelperImpl();
try {
System.out.println(helper.
getDateFormat("MM/dd/yyyy").parse("11/27/2008"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

DateFormatterTests.java
import static org.junit.Assert.fail;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import sample.DateFormatter;
import sample.DateFormatterHelper;

public class DateFormatterTests {

private DateFormatter formatter = null;

DateFormatterHelper helper = null;

@Before
public void setUp() throws Exception {
helper = EasyMock.createMock(DateFormatterHelper.class);
formatter = new DateFormatter();
formatter.setHelper(helper);
}

@Test
public void testConvertToStandardFormat() {

String formatted = null;
try {
EasyMock.expect(helper.getDateFormat("MM-dd-yyyy"))
.
andReturn(new SimpleDateFormat("MM-dd-yyyy"));
EasyMock.replay(helper);
formatted = formatter.
convertToStandardFormat("11-27-2008", "MM-dd-yyyy");
} catch (ParseException e) {
e.printStackTrace();
fail("Exception");
}
Assert.assertEquals(formatted, "11/27/2008");

}
}

Note that in the EasyMock.expect method line, we use the "andReturn" method. This is to define the expected behavior when the method under test is invoked by the testcase. As can be expected, the replay method simply replays the pre-defined behavior when the actual call is made on the mock object.

Download the source
You can download the source code from here.

JUnit - Tutorial

Unit testing with JUnit 
A unit test is a piece of code written by a developer that tests a specific functionality in the code which is tested. Unit tests can ensure that functionality is working and can be used to validate that this functionality still works after code changes.

Setup JUnit in eclipse
Here we will see how to setup the test classes in eclipse:
  1. Create a new project, name it whatever you want, say JUnitDemo.
  2. It would be good to create the unit tests in a separate folder as a good practise. Create therefore a new source folder "test" via right mouse click on your project, select properties and choose the "Java Build Path". Select the tab source code. Press "Add folder" then then press "Create new folder". Create the folder "test".
    before junit
  3. Create the class to be tested - Add it to the normal source folder.
    public class Calc { public long add(int a, int b) { return a+b; } }
  4. Tester class - Right click on test folder, and either make a new JUnit test case or a simple class and add @Test annotation on the methods of this class.
    import org.junit.Test; import static org.junit.Assert.assertEquals; public class CalcTest { @Test public void testAdd() { assertEquals(5, new Calc().add(2, 3)); } }
  5. Now run the test class like this:
    JUnit Run as
  6. Now in the end you will see the following result as green if test was successful and red otherwise.
Creating the testee and tester class

  1. The tests: Unlike in JUnit 3.x you don't have to extend TestCase to implement tests. A simple Java class can be used as a TestCase. The test methods have to be simply annotated with org.junit.Test annotation as shown below
    @Test
    public void emptyTest() {
    stack = new Stack<String>();
    assertTrue(stack.isEmpty());
    }
  2. Using Assert Methods: In JUnit 4 test classes do not inherit from TestCase, as a result, the Assert methods are not available to the test classes. In order to use the Assert methods, you have to use either the prefixed syntax (Assert.assertEquals()) or, use a static import for the Assert class.
    import static org.junit.Assert.*;
    Now the assert methods may be used directly as done with the previous versions of JUnit.
  3. Changes in Assert Methods: The new assertEquals methods use Autoboxing, and hence all the assertEquals(primitive, primitive) methods will be tested as assertEquals(Object, Object). This may lead to some interesting results. For example autoboxing will convert all numbers to the Integer class, so an Integer(10) may not be equal to Long(10). This has to be considered when writing tests for arithmetic methods. For example, the following Calc class and it's corresponding test CalcTest will give you an error.
    Calc.java
    public class Calc {
    public long add(int a, int b) {
    return a+b;
    }
    }

    CalcTest.java
    import org.junit.Test;
    import static org.junit.Assert.assertEquals;

    public class CalcTest {
    @Test
    public void testAdd() {
    assertEquals(5, new Calc().add(2, 3));
    }
    }

    You will end up with the following error.
    java.lang.AssertionError: expected:<5> but was:<5>

    This is due to autoboxing. By default all the integers are cast to Integer, but we were expecting long here. Hence the error. In order to overcome this problem, it is better if you type cast the first parameter in the assertEquals to the appropriate return type for the tested method as follows:
    assertEquals((long)5, new Calc().add(2, 3));

    There are also a couple of methods for comparing Arrays:
    public static void assertEquals(String message, Object[] expecteds, Object[] actuals);
    public static void assertEquals(Object[] expecteds, Object[] actuals);
  4. Setup and TearDown: You need not have to create setup and teardown methods for setup and teardown. The @Before, @After and @BeforeClass, @AfterClass annotations are used for implementing setup and teardown operations. The @Before and @BeforeClass methods are run before running the tests. The @After and @AfterClass methods are run after the tests are run. The only difference being that the @Before and @After can be used for multiple methods in a class, but the @BeforeClass and @AfterClass can be used only once per class.
  5. Parameterized Tests: JUnit 4 comes with another special runner: Parameterized, which allows you to run the same test with different data. For example, in the the following peice of code will imply that the tests will run four times, with the parameter "number" changed each time to the value in the array.
    @RunWith(value = Parameterized.class)
    public class StackTest {
    Stack<Integer> stack;
    private int number;

    public StackTest(int number) {
    this.number = number;
    }

    @Parameters
    public static Collection data() {
    Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4 } };
    return Arrays.asList(data);
    }
    ...
    }

    The requirement for parameterized tests is to
    • Have the annotation @RunWith for the Test Class
    • Have a public static method that returns a Collection for data. Each element of the collection must be an Array of the various paramters used for the test.
    • You will also need a public constructor that uses the parameters
  6. Test Suites: In JUnit 3.8 you had to add a suite() method to your classes, to run all tests as a suite. With JUnit 4 you use annotations instead. To run the CalculatorTest and SquareTest you write an empty class with @RunWith and @Suite annotations.
    import org.junit.runner.RunWith;
    import org.junit.runners.Suite;
    @RunWith(Suite.class)
    @Suite.SuiteClasses({StackTest.class})
    public class AllTests {
    }

    The "Suite" class takes SuiteClasses as argument which is a list of all the classes that can be run in the suite. The following is a listing of the example StackTest used in the post:

Static imports with Eclipse

JUnit uses a lot of static methods and old Eclipse cannot automatically import static imports, but new one can. You can make the JUnit test methods available via the content assists.
Open the Preferences via Window -> Preferences and select Java > Editor > Content Assist > Favorites. Add then via "New Member" the methods you need. For example this makes the assertTrue, assertFalse and assertEquals method available.

JUnit static imports


You can now use Content Assist (Ctrl+Space) to add the method and the import.
I suggest to add at least the following new members.
  • org.junit.Assert.assertTrue
  • org.junit.Assert.assertFalse
  • org.junit.Assert.assertEquals
  • org.junit.Assert.fail

Annotations

The following give an overview of the available annotations in JUnit 4.x


Annotations
AnnotationDescription
@Test public void method()Annotation @Test identifies that this method is a test method.
@Before public void method()Will perform the method() before each test. This method can prepare the test environment, e.g. read input data, initialize the class)
@After public void method()Test method must start with test
@BeforeClass public void method()Will perform the method before the start of all tests. This can be used to perform time intensive activities for example be used to connect to a database
@AfterClass public void method()Will perform the method after all tests have finished. This can be used to perform clean-up activities for example be used to disconnect to a database
@IgnoreWill ignore the test method, e.g. useful if the underlying code has been changed and the test has not yet been adapted or if the runtime of this test is just to long to be included.
@Test(expected=IllegalArgumentException.class)Tests if the method throws the named exception
@Test(timeout=100)Fails if the method takes longer then 100 milliseconds

Assert statements

The following gives an overview of the available test methods:


Test methods
StatementDescription
fail(String)Let the method fail, might be usable to check that a certain part of the code is not reached.
assertTrue(true);True
assertsEquals([String message], expected, actual)Test if the values are the same. Note: for arrays the reference is checked not the content of the arrays
assertsEquals([String message], expected, actual, tolerance)Usage for float and double; the tolerance are the number of decimals which must be the same
assertNull([message], object)Checks if the object is null
assertNotNull([message], object)Check if the object is not null
assertSame([String], expected, actual)Check if both variables refer to the same object
assertNotSame([String], expected, actual)Check that both variables refer not to the same object
assertTrue([message], boolean condition)Check if the boolean condition is true.

Download the source
The source code can be downloaded from here.

Tuesday, 31 May 2011

Thread Local in java

Thread Local can be considered as a scope of access, like a request scope or session scope. It’s a thread scope. It has following:

  • Values stored in Thread Local are global to the thread, meaning that they can be accessed from anywhere inside that thread. If a thread calls methods from several classes, then all the methods can see the Thread Local variable set by other methods (because they are executing in same thread). The value need not be passed explicitly. It’s like how you use global variables.
  • Values stored in Thread Local are local to the thread, meaning that each thread will have it’s own Thread Local variable. One thread can not access/modify other thread’s Thread Local variables.

Comparing Thread locals in other languages and Java

A thread-local variable effectively provides a separate copy of its value for each thread that uses it. Each thread can see only the value associated with that thread, and is unaware that other threads may be using or modifying their own copies. Some compilers (such as the Microsoft Visual C++ compiler or the IBM XL FORTRAN compiler) have incorporated support for thread-local variables into the language using a storage-class modifier (like static or volatile). Java compilers offer no special language support for thread-local variables; instead, they are implemented with the ThreadLocal class, which has special support in the core Thread class.

Because thread-local variables are implemented through a class, rather than as part of the Java language itself, the syntax for using thread-local variables is a bit more clumsy than for language dialects where thread-local variables are built in. To create a thread-local variable, you instantiate an object of class ThreadLocal. The ThreadLocal class behaves much like the various Reference classes in java.lang.ref; it acts as an indirect handle for storing or retrieving a value.

When to use ThreadLocal?

Consider a case when some application is connecting to database. Now you may provide some DAO with connection object as field:

class MyDao{
Connection con;
public void doSomeBusinessLogic()
{
con = datasource.getConnection();
con.doUpdate();
}
}

Now in multi-threaded environment, there is possible that when 1 connection is active, one may be updating and other may be updating simultaneously. So it may be possible that threads may update database but incompletely. So what is the solution for this?

Solution 1 : Make a Connection object locally in a synchronized method.

public synchronized void doBusinessLogic()
{
Connection con = datasource.getConnection();
//some logic
//do update
con.close();
}

This approach solves above problem, but brings in 1 more problem:


  1. We have to create connection object each time method is called, which is very expensive.
  2. Also as threads increase, high processor usage will result. So this may result in problem.

Solution 2 : Make a connection pool and get connections from there.


public synchronized void doBusinessLogic(){
Connection con = pool.getConnection();
//some logic
//do update
}


This approach is fine. But still there is problem of contention. If you are using multi-threaded environment, with multicores, it will be waste of resources to use Connection pooling approach.


Solution 3 : Use thread local


Now we can use ThreadLocal to avoid contention.
Suppose we have thread T1 and T2. ThreadLocal for T1 has a map in which it will have T1 and corresponding connection object. Similarilty ThreadLocal for T2 has T2 and corresponding connection object. Now when doing the same business logic, we can say:


public void doBusinessLogic(){
Connection con = myThreadLocal.connection;
con.doUpdate();
}


So we don't have to create the connection object again and again. Also if hardware is good there is no contention on the database. Suppose later we need some other local variable say transaction, even that will be saved in the map like this.
Some people say that we can pass connection as parameter in the business method, but that will make code look horrible and cumbersome. But that is a solution.


Advantage of ThreadLocal:



  1. No contention. If memory is not an issue, thread local is the best approach.
  2. It avoids using local objects like connection to be used as parameter, making code look simpler but still efficient.

Example code


Consider you have a Servlet which calls some business methods. You have a requirement to generate a unique transaction id for each and every request this servlet process and you need to pass this transaction id to the business methods, for logging purpose. One solution would be passing this transaction id as a parameter to all the business methods as discussed above. But this is not a good solution as the code is redundant and unnecessary.

To solve that, you can use Thread Local. You can generate a transaction id (either in servlet or better in a filter) and set it in the Thread Local. After this, what ever the business method, that this servlet calls, can access the transaction id from the thread local.

This servlet might be servicing more that one request at a time. Since each request is processed in separate thread, the transaction id will be unique to each thread (local) and will be accessible from all over the thread’s execution (global).

Java provides an ThreadLocal object using which you can set/get thread scoped variables. Below is a code example demonstrating what I’d explained above.

First make the DAO or transaction dealing class:

package com.vaani.dao;

public class SomeDAO {
private String transactionId = null;
//some methods to deal with transaction
public void setTransactionId(String transId)
{
transactionId = transId;
}
public String getTransactionId() {
return transactionId;
}

}

Now create Thread Local class to hold this Dao above.

package com.vaani.threadlocal;

import com.vaani.dao.SomeDAO;

public class MyThreadLocal {

public static final ThreadLocal userThreadLocal
                              = new ThreadLocal();

public static void set(SomeDAO dao) {
userThreadLocal.set(dao);
}

public static void unset() {
userThreadLocal.remove();
}

public static SomeDAO get() {
return (SomeDAO)userThreadLocal.get();
}
}
In the above code, you are creating a ThreadLocal object as a static field which can be used by rest of the code to set/get thread local variables.

Let’s create our main class file which will generate and set the transaction ID in thread local and then call the business method.

package com.vaani.demo;

import com.vaani.businesscode.BusinessService;
import com.vaani.dao.SomeDAO;
import com.vaani.threadlocal.MyThreadLocal;

public class ThreadLocalDemo extends Thread {

public static void main(String args[]) {

Thread threadOne = new ThreadLocalDemo();
threadOne.start();

Thread threadTwo = new ThreadLocalDemo();
threadTwo.start();
}

@Override
public void run() {
// sample code to simulate transaction id
SomeDAO dao = new SomeDAO();
dao.setTransactionId(getName());

// set the context object in thread local
// to access it somewhere else

MyThreadLocal.set(dao);

/* note that we are not explicitly
passing the transaction id */

new BusinessService().businessMethod();
MyThreadLocal.unset();

}
}


Finally, here’s the code for the BusinessService.java which will read from thread local and use the value.

package com.vaani.businesscode;

import com.vaani.dao.SomeDAO;
import com.vaani.threadlocal.MyThreadLocal;

public class BusinessService {

public void businessMethod() {
// get the context from thread local
SomeDAO dao = MyThreadLocal.get();
System.out.println(dao.getTransactionId());
}
}

Output

When you run the ThreadLocalDemo file, you’ll get the below output:

Thread-1
Thread-0

As you might see, even though we are not explicitly passing the transaction id, the value can be accessed from the business method and printed on the console. Adding to it, the transaction ID differs for each thread (0 and 1).

Source Code


You can download Source code from here.

Saturday, 28 May 2011

Property class example in java

Here is an example of reading in a properties file, removing the password and printing out the reminder.
import java.util.*;
import java.io.*;

public class PropertyDemo {

public static void main(String[] args)
throws Exception {

BufferedInputStream bStream = new BufferedInputStream
(new FileInputStream("prefs.ini"));
Properties props = new Properties();
props.load(bStream);
props.remove("password");
props.list(System.out);
bStream.close();
}
}

LinkedHashMap example in java

This example shows LinkedHashMap in java:

public class JavaLinkedHashMapExample {
public static void main(String[] args) {
//create object of LinkedHashMap
LinkedHashMap lHashMap = new LinkedHashMap();
//put the values
lHashMap.put("One", new Integer(1));
lHashMap.put("Two", new Integer(2));
//get the value
Object obj = lHashMap.get("One");
System.out.println(obj);
//iterate over linked hash map values
Collection c = lHashMap.values();

//obtain an Iterator for Collection
Iterator itr = c.iterator();



//iterate through LinkedHashMap values iterator
while(itr.hasNext())
System.out.println(itr.next());
}
}