a peek into my MIND

April 2, 2014

2.Literals

Filed under: Java7Spec — Bharat Kondeti @ 12:07 am

<< PREVIOUS

A literal is a representation of a value of primitive type, string type or a literal type. A primitive literal can be a Integer literal / Float literal / Boolean literal / Character literal

– Integer literal can be decimal, hexadecimal, octal and binary
– Integer literal is of type long if it is suffixed with an ASCII letter L or l
– Underscores can be used as separators between integers
– Hexadecimal numerical starts with 0x or 0X followed by ASCII hexadecimal digits (0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,A,B,C,D,E,F)
– Octa numerical starts with 0 followed by ASCII digits 0 through 7
– Binary numerical starts with 0b or 0B followed by ASCII digits 0 or 1

// Decimal with underscore
 int decimal = 10_000_000;

// Hexa decimal
 int hexadecimal = 0X989_680;

// Octa decimal
 int octadecimal = 046113200;

// Binary
 int binary = 0B100110001001011010000000;

– Float literal can be decimal and hexadecimal
– Float literal is of type float if it is suffixed with an ASCII letter F or f
– By default, a Float literal is of type double and optionally it can be suffixed with an ASCII letter D or d

– Boolean literal can be true or false

– Character literal is represented as a character or a escape sequence enclosed in a ASCII single quotes
– Character literal can only represent UTF-16 code’s whose values are in between ‘\u0000’ to ‘\uffff’

– A String literal is a reference to an instance of String class
– A string literal always refers to the same instance of the String class
– String literals defined with in the same class / defined with in different classes of the same package / defined with in different classes of different packages all reference to the same String object instance

public class Sample {
    public static void main(String[] args) {
        String ss1 = "samplestring";
        String ss2 = "samplestring";

        System.out.println( ss1==ss2); //true
        System.out.println( ss1=="samplestring"); //true
        System.out.println( Sample2.ss=="samplestring"); //true
    }
}
class Sample2 {
    public static String ss = "samplestring";
}

– String literals computed by constant expressions are computed at compile time and thus refer to same String instance

String ss = "samplestring";
System.out.println(ss=="sample" + "string"); //true

– String literals computed at runtime by concatenation are newly created and thus reference to different String instance

String ss = "samplestring";
String sample = "sample";
String str = "string";

System.out.println(ss == sample + "string"); //false
System.out.println(ss == sample + str); //false

– intern() method on the computed string will refer to the same String object reference to a literal, if that literal instance is already created

String ss = "samplestring";
String sample = "sample";
String str = "string";

System.out.println(ss == (sample + "string").intern()); //true
System.out.println(ss == (sample + str).intern()); //true

– A null type has a value of null reference that is represented by Null literal

Advertisements

March 3, 2014

1. Keywords

Filed under: Java7Spec — Bharat Kondeti @ 6:01 am

Every language has some reserved words that cannot be used as identifiers called Keywords. Java has 57 such keywords. To get complete list go here – Java Keywords.

Few interesting things:

const and goto are reserved keywords even though they are not used by the language.

– theory around volatile is bit complex. First we need to know that threads can cache data in processor cache memory for performance reasons rather than reading from / writing to main memory every time. In a single-core / multi-core processor, if multiple threads are working on the same variable with each thread using a different cache, they might not see the changes by other threads and will result in race conditions. To avoid this, if a variable is declared as volatile then threads will NOT cache that variable and is always read from / updated to the main memory.

There is one more concept called crossing the memory barrier. This means that when a memory barrier is crossed, JVM syncs all cached copies of variables to main memory and invalidates any cache that is marked as dirty in main memory. This is important because when a volatile variable is accessed, all the other variables that are cached are synced to main memory first. From Java 5 onwards, accessing a volatile variable will result in crossing a memory barrier.

Fixing the Java Memory Model – Part 1

Fixing the Java Memory Model – Part 2

– there is a keyword called strictfp as one of the reserved words. For performance reasons JVM can offload floating point calculations to the platform its running on. Since different platforms use different precisions for floating points, we would get different results when calculating floating points on these platforms. When this keyword is applied to a class, all the calculations inside the class will use strict floating point math by java runtime, resulting in same value on all the platforms. This keyword can be applied to a class, interface or a non abstract method.

>> NEXT

0. Java 7 Specification And A Goal

Filed under: Java7Spec — Bharat Kondeti @ 6:01 am

Since it is never too late to have goals, I decided to have one, which is to read Java 7 Specification and blog about things that I did not know or thought were interesting. Also my hope is writing about these would help me to remember and get better understanding of some concepts.

Plan is to finish reading the specification in next 6 months… Hope I succeed….

September 11, 2012

Maven download source code for dependencies

Filed under: Java — Bharat Kondeti @ 10:00 pm

If you are using eclipse, then you can set maven preferences to download source and java doc

If you don’t want eclipse to automatically download source files then you can use maven to do that

mvn dependency:sources
mvn dependency:resolve -Dclassifier=javadoc

This will only work if there are sources and java doc’s available.

July 11, 2011

Finally Java 7 is out

Filed under: Java — Tags: — Bharat Kondeti @ 11:25 pm

Finally after almost 5 years, new version of Java i.e. Java7 is out for developer preview. Unfortunately many of the promised features were left out in this release, features like Lambda, Jigsaw and some part of Coin initiative are moved to Java 8 release which is expected sometime year end of 2012.

Of course with every new release comes new features, better performance, new syntax etc. Some of the noteworthy features

1) One of the biggest feature is invokeDynamic. This makes interactions between Java and other dynamic languages like JRuby, Jython, Groovy and other 200 languages that are on JVM seamless. Now JVM can optimize the bytecode produced by these languages. We can choose to write code in any language that best solves the problem and compile it against JVM to get all the JVM capabilities like optimization, garbage collection etc

2) Second big feature is language enhancements. Biggest complaint about java is that its verbose / or has lot of ceremony in writing code. With project “coin” in Java7 we will see some language enhancements. For ex

Improved type inference for generic instance creation

//In Java 6
Map<String, List<String>> mapoflists = new HashMap<String, List<String>>();

//In Java 7
Map<String, List<String>> mapoflists = new HashMap<>();

Similarly Multi Catch blocks

try {
//Do Something;
catch(Exp1 | Exp2 |Exp3) {
//Do something
}

more enhancements like strings in switch statements, Binary Integral literals and underscore literals, try with resource statements etc

3) We are in an age where servers with multiple cores are very common. Having language features that enables us to use all these processing power is very helpful. Java7 has enhancements for Concurrent and Collections API that enable us to write applications to use multiple processors.

4) Enhanced NIO

For more features and information follow these links

Oracle Java 7 page

Javalobby Introducing Java 7

August 16, 2010

DbUnit and setting up changing data.

Filed under: Java, Testing — Tags: , , , — Bharat Kondeti @ 10:52 pm

DbUnit is used to set up test data for integration tests that rely on a database. One way of importing and exporting database data in DbUnit is by XML data-sets. Assuming we have a table like this…

CUSTOMER
—————————————————————————–
| ID | FirstName | LastName | LicenceExpiryDate |
—————————————————————————–

We are testing a method called isLicenceExpired(id). To unit test this method we can setup some dummy data using DbUnits.

<?xml version='1.0' encoding='UTF-8'?>
<dataset>
  <CUSTOMER ID="1" FIRSTNAME="FirstName1" LASTNAME="LastName1" LICENCEEXPIRTDATE="2010-08-25" 
  <CUSTOMER ID="2" FIRSTNAME="FirstName2" LASTNAME="LastName2" LICENCEEXPIRTDATE="2010-09-15" 
  <CUSTOMER ID="3" FIRSTNAME="FirstName3" LASTNAME="LastName3" LICENCEEXPIRTDATE="2011-01-01" 
</dataset>

Problem with above setup is test-cases would eventually fail because of ‘LicenceExpiryDate’. We need to setup this date such that it’s relative to current date. This is where ReplacementDataSet comes into picture. This class decorates FlatXmlDataSet class to provide replacement functionality. Now we can define your data set as
(more…)

February 8, 2010

Exiting nested loops in java using named statements

Filed under: Java — Bharat Kondeti @ 10:17 pm

There may be cases when one has to break the outer for loop when a condition get’s satisfied in the inner for loop.

In the following example code, I am finding the country where the state belongs to..

Country rc = null;
boolean stop = false;
for (Country country : countries) {
	if(stop) break;
	for (State state : country.getStates()) {
		if(state.getName().equalsIgnoreCase(stateName)) {
			rc = country; stop = true; break;
		}
	}
}

In the following example I am naming my external for loop and passing that name to the break statement.

Country rc = null;
COUNTRY:
for (Country country : countries) {
	for (State state : country.getStates()) {
		if(state.getName().equalsIgnoreCase(stateName)) {
			rc = country; break COUNTRY;
		}
	}
}

February 4, 2010

Unit testing iBATIS SqlMapClient with EasyMock

Filed under: Java, Testing — Bharat Kondeti @ 3:44 pm

Integrating iBATIS to an application using spring framework is pretty straight forward. Testing a DAO code with live database will make it an integration test.

In general I write two kinds of tests for any DAO code

  • Unit Test – Using EasyMock to mock a DataSource, SqlMapSession and SqlMapClient.
  • Integration test – Using DBUnit to create and delete the db data.

Following is an example DAO code. We are using iBATIS with spring. Code can be much more complex with multiple calls to database and can have some logic inside it.

import java.util.List;

import org.springframework.orm.ibatis.SqlMapClientTemplate;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

public class SomeDAODBImpl extends SqlMapClientDaoSupport {
	
  public List<Customer> lookupCustomers(String zip) {
    List<Customer> customerList = null;
    try {
      SqlMapClientTemplate template = getSqlMapClientTemplate();
      customerList = template.queryForList("Some-Ibatis-Statement-Name", zip);
    } catch (Exception ex) {
       //TODO: Do something with the caught exception
    }
    return customerList;
  }
}

To unit test this code one have to create a mock datasource, session and client. Following is an example unit test code.

(more…)

January 20, 2010

Unit testing multi threaded code with EasyMock

Filed under: Java, Testing — Tags: , , , — Bharat Kondeti @ 4:02 pm

Using java.util.concurrent api, creating asynchronous tasks and executing them in parallel is quite easy.

Following is an example where I create 2 task’s Callable1 and Callable2 and execute them in parallel with Fixed ThreadPoolExecutor. In real world there will be some complex code logic for each of these tasks, and there might also be some logic where these two tasks are executed (callTasksInParallel).

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class MultiThreadExample {
	private static final int threadTimeOut = 10;
	private static final int maxThreadPool = 20;

	private ExecutorService pool = null;

	public MultiThreadExample() {
		pool = Executors.newFixedThreadPool(maxThreadPool);
	}
        
        public void setPool(ExecutorService pool) {
		this.pool = pool;
	}

	public void callTasksInParallel() {
		Future<String> callable1Future = pool.submit(new Callable1());
		Future<String> callable2Future = pool.submit(new Callable2());

		try {
			String response1 = callable1Future.get(threadTimeOut, TimeUnit.SECONDS);
			String response2 = callable2Future.get(threadTimeOut, TimeUnit.SECONDS);

			System.out.println(response1);
			System.out.println(response2);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		} catch (TimeoutException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		MultiThreadExample multiThreadExample = new MultiThreadExample();
		multiThreadExample.callTasksInParallel();
	}
}

class Callable1 implements Callable<String> {
	public String call() throws Exception {
		return "I am returned from Callable1";
	}
}

class Callable2 implements Callable<String> {
	public String call() throws Exception {
		return "I am returned from Callable2";
	}
}

Unit testing MultiThreadExample by itself will require mocking of ExecuterService and having Future mocks. Following is an example Junit test code that tests callTasksInParallel as a unit without a dependency for Callable1 and Callable2 classes.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;

public class MultiThreadExampleTest {
	private ExecutorService executorServiceMock;
	private MultiThreadExample multiThreadExample;

	@Before
	public void setUp() throws Exception {
		executorServiceMock = EasyMock.createMock(ExecutorService.class);
		multiThreadExample = new MultiThreadExample();
		EasyMock.makeThreadSafe(executorServiceMock, true);
	}

	@SuppressWarnings("unchecked")
	@Test
	public void testCallTasksInParallel() throws Exception {
		multiThreadExample.setPool(executorServiceMock);

                //Future mock for Callable1 and set the expectation
		Future<String> callable1Mock = (Future<String>) EasyMock.createMock(Future.class);
		EasyMock.expect(callable1Mock.get(EasyMock.anyLong(), EasyMock.isA(TimeUnit.class))).andReturn("Mock response from callable1");
		EasyMock.replay(callable1Mock);

                //Future mock for Callable2 and set the expectation
		Future<String> callable2Mock = (Future<String>) EasyMock.createMock(Future.class);
		EasyMock.expect(callable2Mock.get(EasyMock.anyLong(), EasyMock.isA(TimeUnit.class))).andReturn("Mock response from callable2");
		EasyMock.replay(callable2Mock);

                //Submit the created futures to the ExecuterService mock and replay them
		EasyMock.expect(executorServiceMock.submit(EasyMock.isA(Callable1.class))).andReturn(callable1Mock);
		EasyMock.expect(executorServiceMock.submit(EasyMock.isA(Callable2.class))).andReturn(callable2Mock);
		EasyMock.replay(executorServiceMock);

		multiThreadExample.callTasksInParallel();
               
		EasyMock.verify(callable1Mock);
		EasyMock.verify(callable2Mock);
		EasyMock.verify(executorServiceMock);
	}
}

Above approach can be used to Unit test all the exception scenarios also.

December 7, 2009

Unit testing Log4j log statements.

Filed under: Java, Testing — Tags: , , — Bharat Kondeti @ 6:15 pm

Logging is an important aspect in writing any software application. Logs properly utilized provide valuable information related to code flow. Mining logs is a way to gather data related to performance of the application and to debug the application.

As part of our current application we wrote tools in Perl and Groovy to mine the logs to collect statistics related to the application. In these tools, we primarily look for string patterns and if some one unintentionally changes the log statements inside the code it breaks our tools also. It’s always beneficial to surround SOME of the log statements with Junit test.

Extending AppenderSkeleton to create a custom append-er.

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;

public class TestingAppender extends AppenderSkeleton {

  //We are collecting all the log messages in to a list
  private static List messages = new ArrayList();

  // This method is called when ever any logging happens
  // We are simply taking the log message and adding to our list
  @Override
  protected void append(LoggingEvent event) {
    messages.add(event.getRenderedMessage());
  }

  //This method is called when the appender is closed.
  //Gives an opportunity to clean up resources
  public void close() {
    messages.clear();
  }

  public boolean requiresLayout() {
    return false;
  }

  public static String[] getMessages() {
    return (String[]) messages.toArray(new String[messages.size()]);
  }

  public static void clear() {
    messages.clear();
  }
}

Then we need to write couple of methods to setup the custom append-er and remove it. As part of setUp and tearDown methods of JUnit tests appropriate methods can be called.


private void setupLog4j(TestingAppender appender) {
  //Get the root logger for the
  Logger root = Logger.getRootLogger();

  //If there are no appenders, means Log4j is not initialized properly
  if (!root.getAllAppenders().hasMoreElements()) {
    System.out.println("*******Log4j is not initilized**********");
  } else {

   //Set to appropriate log level and add custom appender
    root.setLevel(Level.ERROR);
    root.addAppender(appender);
  }
}

private void resetLog4j(TestingAppender appender) {
  TestingAppender.clear();
  Logger root = Logger.getRootLogger();
  root.setLevel(Level.FATAL);
  root.removeAppender(appender);
}

As part of tests we can call TestingAppender.getMessages() to get the list of messages and assert for the appropriate log message. This way we can have unit tests for log statements also.

Older Posts »

Blog at WordPress.com.