Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Compilation Failure is the best Failure!

What I am going to write may sound really obvious but surprisingly I see this problem at soo many places that it deserves a post.

Here's a Rule 1: "If you are doing an instanceof and you are in control of that class, you can instead delegate to the class"

Meaning, if you were making a decision of what code to execute by checking an instanceof and the class being checked is the one that you control, as in the one that you can modify, add methods change code, then you should delegate the decision of what should be executed to that class instead.

Lets look at an example,


public static void speak(Animal animal) 
    if (animal instanceof Dog) {
         System.out.println("bhow.. bhow...");
    } else if (animal instanceof Cat) {
         System.out.println("meow.. meow...");

    } else if (animal instanceof Tiger) {
         System.out.println("Grrrr...");
    }
}

could really be changed to,

Animal animal = getAnimal();
animal.speak();

Where classes Dog, Cat and Tiger now will implement the speak() method.

It sounds really obvious doesn't it? If it really does, just do a search of instanceof keyword in your code and ask the same question. The "speak" operation comes very naturally to the Animal but sometimes you will find that since we don't think something is natural to that Entity or class, we don't add it there.

There is an anti-pattern called "Anemic Domain Model" which will specially suffer this problem. This pattern encourages to keep the Behavior separate from the Data. Which is what is happening in above example. One very simple way to find it is to see how many classes are named "Entity" and "EntityService"? If the EntityService operates on a single instance of the Entity like single animal, then  you have a problem. Don't confuse this with the one's that operate on multiple instances like a "EntityManager" or an "EntityDAO"

So what is really wrong with writing an if else-if  and checking instanceof to make decisions? Lets consider that in above example, we added another Animal Cow. Now what can happen is that in our first version of "speak" one can forget to go and add code for a Cow. This is perfectly fine, code compiles! We have implemented the Animal interface but there are no complains. This would only lead to either runtime failure or no failure at all! which ultimately leads to bugs. Think about a larger project where the references are at a lot of places. If the "speak" method is at the level of Animal interface, you have no choice but to implement this method (God help people who will still keep it empty)

Which brings me to my Rule 2: "Compilation Failure is the best failure!"

Myth about InputStream.read(byte [], int, int) method

I know it may sound stupid but only yesterday I discovered that
InputStream.read(byte [] data, int offset, int length) 
method can end up reading lesser number of bytes than length.

What that means is if you are doing something like,
InputStream in = getInputStream(); // getting it from somewhere..
byte data = new byte[10];
int read = in.read(data, 0, data.length);
System.out.println("Bytes read: " + read);
The you cannot gurantee that in.read() call will read 10 bytes even when the stream is connected / not broken (applicable particularly in sockets). My understanding was that if it ever returns lesser bytes than lenght, then the channel us broken and we should assume that connection is dropped from counter-party.

There is good explanation in javadocs about this method. The default implementation of this method at the level of InputStream class does this,
  1. It tries to read the first byte from the stream. If the read fails due to any other reason other than end of stream, then IOException is thrown. If end of stream is detected, -1 is returned.
  2. After the first read, if any of the subsequent read throws and IOException, It is swallowed and end of stream is assumed and the number of bytes read until this point are returned. If any of the subsequent reads detects end of stream, again whaterver bytes are read are returned. 
The javadoc also suggests the extensions of InputStream to provide a better implementation of this method. In SocketInputStream (not public in java api) which is what I was dealing with, read(byte [] data, int offset, int length) call delegates to a native method.

So out of my curiosity, I wrote a sample where I had a ServerSocket as a produces producing 2 bytes and waiting for 1 second. And a consumer using Socket which would attempt to read 4 bytes at a time without waiting.  The problem was easily reproduced and I could see my every read call in consumer only reading 2 bytes at a time.

BufferedInputStream provides a more convinient implementation of the read method. It repeatedly invkoes the multibyte read method on the underlying stream until
  1. Length number of bytes are read
  2. End of stream is reached
  3. Subsequent call to read will block. This is identified by calling available method on the stream.
But note the point 3, it still does not gurantee that it will always return length number of bytes unless end of stream is reached.

In my case our SocketInputStream was wrapped in the BufferedInputStream, which relatively shielded us from this problem but it aggrevated the problem as we saw this problem very rarely. Only after some code review is what we identified this issue.

Now a few questions in your mind maybe why call the multibyte read? why not just keep calling single byte read and track how many bytes we read? One of the grey hair in my company answered this question saying, 
Whe we use to do it in C, the multibyte read made sure that there were fewer stack pushes and pops as we would end up doing fewer read calls. 
I havent personally measured the performance gain by using multibyte read but Ithink it never hurts using it if you understand how it works.

So when does the multibyte read call wait then? Since it is capable of returing lesser bytes than requested, it can always just return with lesser data. My guess is that it will only block when there are 0 bytes avaialble to read. In a way multibyte read call will never return 0, as it will make an attempt to read at least one byte.

Quick way to untar and bunzip files in java

Have you ever felt a need to deal with bzip2 compressed tarballs in Java? Recently I compressed a lot of test resources in our source tree using bzip2 compression. The resources were static and were meant to change very rarely. bzip2 was the best choice in terms of amount of compression. What it also meant was my SVN download of the source tree would take much lower time. I planned to extract the resources and make them available at runtime while running tests.

If you already know, there is no way to handle bzip compression in Java core API. But at the back of my mind I knew that you can create bzipped tarballs using Ant. So I looked at the Ant tasks and figured that there was untar task which can be instructed to also process it through bzip2 uncompression.

Here is the code snippet that can untar and bunzip the file using Java code.
Untar untar = new Untar();
untar.setSrc(new File("./src/test/resources/files.tar.bz2"));
untar.setDest(new File("./target"));
UntarCompressionMethod compression = new UntarCompressionMethod();
compression.setValue("bzip2");
untar.setCompression(compression);
untar.setOverwrite(true);
untar.execute();

Also make sure that you put ant jar on the classpath.

Maven users can simply add following dependency,

<dependency>
   <groupId>org.apache.ant</groupId>
   <artifactId>ant</artifactId>
   <version>1.7.0</version>
   <scope>test</scope>
</dependency>

Disabling test under JUnit 4.4

Recently I had to disable a unit test in our test system. We use Maven as our build tool and JUnit 4.4 for unit testing. I had a few options,

  1. Exclude that particular class from tests under surefire plugins configuration in my pom.xml
  2. Remove @Test annotation from test method in the test class. Which fails as it finds a Test class but does not find any test methods
  3. Rename the class from say MyTest to something that does not end with "Test" say "Tezt"
I remembered that in TestNG you can just disable a test by saying @Test (enable = false) and I was desperately trying to find how to do this in JUnit 4.4. But to my dissappointment Test annotation only allows a couple of attributes, timeout and expected which did not do what I want.

After looking at the JUnit javadocs, I stumbled upon an annotation @Ignore it is indeed an annotation to be used if you want to skip the test.

So if you want to disable your test case in JUnit 4.4 just annotate your test methond with @Ignore @Test annotations.

What it also did was that Maven started reposting one test as being "Skipped" which is nicer as it keeps reminding you that you need to look after the test that you have disabled.

Animal Sniffer Maven Plugin

While looking at the Maven plugins at Codehaus, I just stumbled upon a maven plugin named Animal Sniffer. This plugin could be a great tool for people working on frameworks where API's are published to the user. There is always a problem of API loosing the compatibility across versions (for eg. making some method final looses backward compatibility). These kind of problems are very very difficult to trap.

I wanted to evaluate this plugin for instrumenting our internal API against which following versions can check compatibility. Firstly I am not sure if Animal Sniffer can be used in this way but I believe it could be.

I tried to play with the plugin a little where I figured out that vresion 1.5-SNAPSHOT cannot be downloaded from the Codehaus snapshot repository and older versions 1.4, 1.3 encounter an NPE when I run animal-sniffer:build goal.

Does anyone have experience with Animal Sniffer?

Apache Pivot, Platform for building Rich Internet Appplications

Apache Pivot is a framework for building Rich Internet Applications. Pivot seems to have taken inspiration from Flex and Silverlight.

Here is a snippet of overview from Pivot website,

"Pivot applications are written using a combination of Java and XML and can be run either as an applet or as a standalone (optionally offline) desktop application. Pivot includes features that make building modern GUI applications much easier, including declarative UI, data binding, effects and transitions, and web services integration." 

I would personally choose Pivot over Flex or Silverlight as it is easier to integrate builds into Continuous Integration and Maven. Not sure where Pivot will head to but it surely seems a promising technology.

Common we are in 2009! Use an IDE!!

I have seen a number of people using a naming convention of prefixing letter 'I' to names of any interfaces in Java like IHuman, IMonster. This was a very famous and essential practice about a couple of decades ago (I believe. Not that I am soo old!) I remember reading about prefixes like "lpstr" indicating that it is a "Long Pointer to the String". But all this was followed in C and C++. It was important at that time since the languages were not type safe and there were no mature IDE's. It would be easier to recognize that this pointer is to this this type of variable etc. which would prevent a lot of silly mistakes too. Seems like a few people with inclination towards Microsoft standards in .Net still like it and recommend it.

Personally I think we are in year 2009, I use IDE (Eclipse) for development and I have never needed to really see 'I' prefixed to an interface. It adds very less value. Only thing you can accidently end up doing is say do new Interface(); but your IDE will complain the very next moment anyway. I can always see what methods I can call by simply typing '.' In case I have any doubts. I generally use F4 to see hierarchy which will clearly show me that it is an Interface by coloring it purlple or I would directly F3 to get into code to see whats there.

People who still follow this beautiful practice, I am sorry but I absolutely hate it! for others, keep your Alt + Shift + R ready ;)

Time measurement accuracy in Java

An interesting article about time measurement under Java

http://www.simongbrown.com/blog/2007/08/20/millisecond_accuracy_in_java.html

Beware if you are doing any performance measurements on Windows.

Ant / Junit and Class Loaders

Have you ever come across situations where you need to load external resources in your Junit tests? I generally prefer loading external resource files from the classpath. So I add the resources on the classpath and in the test case I look up the resource using the ClassLoader.getResource(). If you are running the Junit tests using ant, you can run into all sorts of problems if you are trying to load resources from the classpath.

Ant runs each Junit test in its own class loader. This makes sure that any libraries on the ant's classpath wont interfere with the test's environment.

If you are using a class loader to load the resources, always use the immediate class loader to load the resource. Generally you can get the handle to class loader through
ClassLoader.getSystemClassLoader(). But if you try to load a resource using this class loader in the test case, JVM will try to load the resource using the system class loader. System class loader in this case is class loader for Ant. But unfortunately since Ant created a special class loader for the test, the system class loader does not contain the same classpath that you have configured in ant's build.xml for running tests (Ideally you would have added the directories containing the resources that you need to dynamically look up in test cases here). You would end up with a resource not being found.

To overcome this, always use immediate class loader, how to dot it?

use
MyTest.class.getClassLoader()

This ensures that we are getting the class loader that loaded test class. Which infact is the immediate class loader.

This also applies for any framework / API you write. Using immediate class loader makes sure that your framework would be testable in the multi classloader environements.



My realization with synchronization

Recently I had to do major code refactoring on a component to make it thread safe and also to improve its performance. The component is a persistence layer that is capable of persisting and querying data. The component was already thread safe but the synchronization levels were on rather higher level. Older synchronization levels would block the query if the component is already executing some other query. So despite being multi threaded, queries executed from multiple threads will only execute one after the other. What we wanted now was to be able to execute queries simultaneously. Regardless of how many queries are executed in parallel. Two queries executed in parallel should block each other at rather micro level (like record level).

This component involves extensive use Java Collections. And at most of the places (while querying) you need to copy from these Collections. A particular Collection can contain more than a million object sometimes. So copying naturally takes up a lot of time in this case. The bad part is you have to synchronize on the Collection for the time you are copying it. So you are stopping any inserts and updates into the database (add, remove, on Collection).  When you need to synchronize access to the Object you always have to synchronize on all accesses to the Object. Similarly you have to synchronize all the actions on the Collections. To make the synchronization simpler, one can always use synchronized versions of Collections. You can obtain synchronized version of the underlying Collection instance by using methods Collections.synchronizedXXXX(). These synchronized versions of Collections can get rid of hassle of explicitly synchronizing on every access to the Collection. But there is a thing to remember with the synchronized Collections. Wherever you obtain any sort of Iterator, you need to externally synchronize the Collection. If you iterate on Map.keySet of synchronized map or you iterate on a synchronized Collection, you must externally synchronize the Collection (More explanation of why, coming later)

So in our case when I am copying from the collection I am actually iterating on the Collection and adding items to the other Collection. This access is synchronized. Which avoids any other access to the underlying Collection. Which means only one thread can iterate on a Collection at a time (There can be multiple iterators on a Collection at a certain time. But then we assume that no one modifies the Collection). To avoid all this blocking iteration, I came up with a rather stupid idea of using a synchronized List instead. The idea behind synchronized List was to avoid iteration (Remember you can do index base access to the List) So,

Collection src = Collections.synchronizedCollection(new ArrayList());
Collection dest = new ArrayList();
synchronized (src) {
        Iterator itr = src.iterator();
        while (itr.hasNext()) {
                 dest.add(itr.next());
        }
}


will be replaced with

List src = Collections.synchronizedList(new ArrayList());
List dest = new ArrayList();
for (int i = 0; i <= src.size(); i++) {
         dest.add(src.get(i));
}



With this approach, the synchronization is even finer now. We dont lock the Collection for all the time we spend iterating it. But we just lock it for the period we are doing src.get(i) operation. This means individual List.get() operations block each other instead of whole iteration process blocking the other one. For a while I considered this as a fabulous idea. But if you have noticed, we are breaking synchronization here. We can get into all sorts of problems using this approach.

For example:

Thread 1 : starts iterating List calculates List size as 10
Thread 2 : Removes an item from the List
Thread 1 : Reaches step List.get(i) where i=9. This will result into ArrayIndexOutOfBoundsException.

Since Thread 2 has removed one object from list by the time Thread 1 reaches 9th iteration of its for loop, we have broken the synchronous access to the List.

This lead me to an obvious conclusion that, Iteration is one logical operation on the Collection and it should block to all add, remove, get operations on corresponding Collection.

Well, thats not all! This rule can be generalized for all the objects. If you are making certain object as completely synchronized internally then the same rule applies to all such objects. Any logical operation to such object should block other logical operation (Maybe not always but most of the times). I encountered the same problem with a custom object. Which is suppose to a database index. I tried to synchronize on the entry level in index. The entries are actually stored on a Map. IndexEntry is mapped with its key. This did not help me because by the time i get an IndexEntry (Map.get(key)) out and as I operate on it. Some other thread can completely remove the entry from the Map (Map.remove(key)). Then all the operations by original thread on this IndexEntry are invalid. Same principle of the logical operation applies here. Each logical operation like read, add, update on index should be synchronous.

The other catch with synchronization is, Anything going out of scope of internally synchronized object needs to be externally synchronized. As we saw in iterators of synchronized collections. Even if the object is internally synchronized, if we return part of it as reference (internal structure, object), this part breaks the synchronization limits of the object and then needs explicit external synchronization from the user of this part. Most of the times we can avoid this scenario by making defensive copies of the internal structures before returning. But sometimes this can hit your performance.

Quite a long one! What do you guys say?


Go "Find Bugs" in your software.

Life was going smoothly for me last couple of weeks. Hardly anything to
do. So I started reading articles and blogs and I ended up on a blog on
The Serverside which mentioned about the tool called "Find Bugs" I found
the name very interesting and downloaded that tool. The very first thing
I did was that I ran it on the code base of software I was working on. I
found it funny that Find Bugs reported around 700 bugs. Obviously I had
at least some faith in my code which made me believe that it was just crap!

Next thing I did was I started looking at each issue individually and
read through the explanation on why that thing was reported as a Bug.
Suddenly it started making a lot of sense to me. Believe me, 80% of them
were bugs! It efficiently detected some blunders like empty catch blocks
with catch(Exeption e) Assignments to static in non static methods of
class, Dead local store, Class casting problems, Possible Null pointer
dereference etc. And at last I found some real work to do! A lot of
work! It taught me a lot about good coding.

Find Bugs is a must have tool in your swiss army knife for code review.
It takes off a lot of hassles of manual code reviews. It comes with a
Eclipse plugin too which works well but the swing front-end provided by
Find Bugs is really good. It lets you address problems by category.
Where as in Eclipse you have to go to individual source file to find out
bugs in your code. Eclipse also has summary view to see the problems but
it looks really cluttered. Its a must use tool for all Java programmers.

Static Inner classes?

Ever tried serializing the inner class object with non serializable
outer class? We cannot do this! By default compiler adds a reference
to the outer class in the inner class. Remember! we need to access
some attributes of outer class at times. This explicit referencing helps
at that time. When you try to serialize the inner class object you will
get an error.

Now what do we do if we want an inner class object to be serialized?
There is a way to do it. This is where you can use static inner class!.
A static inner class doesn't get a reference to the outer class when
compiled. Its treated as any other standalone class all together. When
an inner class is compiled its actually compiled into a class file with
name OuterClass$InnerClass.class where as the static inner class gets
its own seperate InnerClass.class file. This also meas that you cannot
access OuterClass members from static inner class since we no
longer have any reference to the outer class.

Singleton pattern in JAVA?
Implementing Singleton in java is easy! Isn't it?
Today i came across things which you can screw
up using a singleton pattern. Now I find it very
complex than being so easy. There are some special
cases where our "so called Singleton" is not actually
a singleton.

If one uses lazy initialization of singleton instance,
then you are very likely to create more than instances
of the singleton class. in this case, the method giving
you the instance of the singleton needs to be thread safe,
or we might end up in a situation where two threads try
to get singleton and parallely create to different objects.
But It has performance overheads in some cases.

Other problem is of having singleton objects in the
distributed environment. Objects may span across
JVMs Which creates lot of problems since the
Singleton objects are unique for a JVM. In case
where we use cluster of application servers we might
face this problem.

There are lots of other factors affecting singletons
in java for detailed text read this