Showing posts with label download-source-code. Show all posts
Showing posts with label download-source-code. Show all posts

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.


Latches

http://ydtech.blogspot.com/2010/06/countdownlatch-by-example.html

A latch is a boolean condition that is set at most once, ever. Once a single release is issued, all acquires will pass.

Latch is switch or gate
In concurrent programming, a latch is a type of "switch" or "gate". The latch is set up with a particular count value. The count is then counted down, and at strategic moments, a thread or threads waits for the countdown to reach zero before continuing to perform some process. Note that this is a one-off process: once the latch reaches zero, there is no way to reset the count.

So threads can then either count down on the latch or wait for it to reach 0. When the latch reaches 0, all waiting threads are released.

The CountDownLatch class allows one to prevent a set of threads from running until you are ready for them to. For example, you might want to create the threads and then do some initialization tasks before starting them all simultaneously.

CountDownLatch’s constructor takes an integer as a parameter which decides its behavior. Calling await() holds execution till countdownLatch’s count(constructor parameter) become zero and countdown() reduces the count on every call. So calling await() blocks the thread until the count reaches zero.  

Example

package com.vaani.countdown;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchDemo {

public static void main(String[] args) throws Exception {
int nThreads = 3;
final CountDownLatch startLatch = new CountDownLatch(nThreads);
final CountDownLatch endLatch = new CountDownLatch(nThreads);

ExecutorService svc = Executors.newFixedThreadPool(nThreads);
for (int i = 0; i < nThreads; i++) {
svc.execute(new Runnable() {
public void run() {
try {
log("At run()");
startLatch.countDown();
startLatch.await();

log("Do work");
Thread.sleep((int) (Math.random() * 1000));

log("Wait for end");
endLatch.countDown();
endLatch.await();

log("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
});
Thread.sleep(100);
}
}

private static void log(String msg) {
System.out.println(System.currentTimeMillis() + ": "
+ Thread.currentThread().getId() + " " + msg);
}
}

In this code, you’ll see two latches get initialized. Each thread that starts up counts down on the latch and awaits the latch counting down to 0 (when all threads have been initialized). Similarly, each thread waits for all threads to complete at the same time.

Sample output of this program is:

1308458964186: 8 At run()
1308458964286: 9 At run()
1308458964386: 10 At run()
1308458964386: 8 Do work
1308458964386: 10 Do work
1308458964387: 9 Do work
1308458964952: 8 Wait for end
1308458965037: 9 Wait for end
1308458965277: 10 Wait for end
1308458965277: 9 Done
1308458965277: 8 Done
1308458965277: 10 Done


You can see that each thread hits run() at different times, but proceeds past the barrier at the same time. They each then do some random amount of work and wait for the latch, then proceed past it together.

In the example above, each thread waits forever for the latch to trigger. You can also choose to wait for a specified time period before giving up. And you can check the latch to see how many threads have arrived and are now waiting. Each CountDownLatch instance can only be used once and is then dead.

Download the source


You can download the source code of the above program from here.

Get the desktop snapshot with Java

To take the snapshot of your desktop try this:

package com.vaani.image;

import java.awt.Dimension;
import java.awt.Rectangle;import java.awt.Robot;import java.awt.Toolkit;import java.awt.image.BufferedImage;import javax.imageio.ImageIO;import java.io.File;

public class ScreenShooter {
public static void main (String[] args)
throws Exception {
ScreenShooter screenshooter = new ScreenShooter ();
screenshooter.captureScreen ("C://temp/desktopSnapshot.png");
}

public void captureScreen (String fileName) throws Exception {

Dimension screenSize = Toolkit.getDefaultToolkit ().getScreenSize ();
Rectangle screenRectangle = new Rectangle (screenSize); Robot robot = new Robot (); BufferedImage image = robot.createScreenCapture (screenRectangle);
ImageIO.write (image, "png", new File (fileName));

}

}


Download the source code from here.

Friday, 17 June 2011

CyclicBarrier

As written in java docs Cyclic barrier is -
A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.

So if a given thread should do its calculation and then wait until all the other threads are finished before starting to calculate the next step, you might have to use a barrier synchronization technique. This term implies that a thread is stopped at the barrier until all threads reach it. Once all have reached it, the barrier is lowered and they all start a new round of step calculations and all again wait at the barrier after they finish their work.

It is a synchronization mechanism that can synchronize threads progressing through some algorithm. In other words, it is a barrier that all threads must wait at, until all threads reach it, before any of the threads can continue.

Understanding the CyclicBarrier

Java concurrency utilities offers java.util.concurrent.CyclicBarrier class to provide us with barrier. (It's called cyclic because it can be reused after each time the waiting threads are released by it.)

Firstly, the barrier is constructed with the following:

  • the number of threads that will be participating in the parallel operation;
  • optionally, an amalgamation routine to run at the end of each stage/iteration.

Then, at each stage (or on each iteration) of the operation:

  • each thread carries out its portion of the work;
  • after doing its portion of the work, each thread calls the barrier's await() method;
  • the await() method returns only when:
    • all threads have called await();
    • the amalgamation method has run (the barrier calls this on the last thread to call await() before releasing the awaiting threads).
  • if any of the threads is interrupted or times out while waiting for the barrier, then the barrier is "broken" and all other waiting threads receive a BrokenBarrierException.

In other words, this last point means there is a mechanism for an error/timeout in one of the worker threads to "ripple out" to all threads and for the operation to halt, or for the operation to be interrupted externally by interrupting just one of the threads. 

Examples

A common use for this is in multi-threaded testing where it is typical to start a bunch of threads, meet, do some stuff, meet, validate some assertions, repeatedly. Lets see the example :

package com.vaani.cyclicbarrier;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CyclicBarrierDemo {

public static void main(String[] args) throws Exception {
int nThreads = 3;
final CyclicBarrier barrier = new CyclicBarrier(nThreads);

ExecutorService esvc = Executors.newFixedThreadPool(nThreads);
for (int i = 0; i < nThreads; i++) {
esvc.execute(new Runnable() {
public void run() {
try {
log("At run()");
barrier.await();

log("Do work");
Thread.sleep((int) (Math.random() * 1000));

log("Wait for end");
barrier.await();

log("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
});
Thread.sleep(100);
}
}

private static void log(String msg) {
System.out.println(System.currentTimeMillis() + ": "
+ Thread.currentThread().getId() + " " + msg);
}
}


Another nice trick with CyclicBarrier is that a Runnable action can be associated with the barrier to be run by the last thread reaching the barrier. You can very simply build a start/end timer for testing with this functionality:

package com.vaani.cyclicbarrier;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TimerBarrierDemo {

public static void main(String[] args) throws Exception {
int threads = 3;
final CyclicBarrier barrier = new CyclicBarrier(threads, new BarrierTimer());

ExecutorService svc = Executors.newFixedThreadPool(threads);
for (int i = 0; i < threads; i++) {
svc.execute(new Runnable() {
public void run() {
try {
barrier.await();
long sleepTime = (int) (Math.random() * 1000);
System.out.println(Thread.currentThread().getId()
+ " working for " + sleepTime);
Thread.sleep(sleepTime);
barrier.await();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}

private static class BarrierTimer implements Runnable {
private long start;

public void run() {
if (start == 0) {
start = System.currentTimeMillis();
} else {
long end = System.currentTimeMillis();
long elapsed = (end - start);
System.out.println("Completed in " + elapsed + " ms");
}
}
}
}


Here we rely on knowing that the barrier will be reached exactly twice – once at start and once at end. The first time it’s reached, we record a timestamp and the second time it’s reached we print out the timing. When we construct our barrier, we give it an instance of this timer class. Each thread then waits to start on the barrier, works for a random amount of time, and waits for the end barrier.

A run looks like this:

10 working for 136
9 working for 391
8 working for 720
Completed in 721 ms


Generally, you should expect the recorded elapsed time to be the maximum of the working time of any of the threads.

CyclicBarrier has a few additional tricks as well – threads can wait for a time period instead of forever, check whether a barrier has been broken (by interruption or forcibly with a reset() method), and determine the number of parties and the number currently waiting.


Download the Source


Source code 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.