Skip to main content

Posts

Showing posts with the label Java

Double Checked Locking And Java Singletons

I read this article by Bill Pugh on why the double checked locking idiom does not guarantee thread safety in Java Singletons. That article taught me a lot of new things, and to be honest, I had to re-read that article at least a couple of times to partially understand it :-) I recently created a presentation to make at DevCamp on this topic. What follows are my slides and an explanation of each slide. I hope you enjoy this presentation and find it useful. Double checkedlockingjavasingletons View more presentations from parag . slide 1: In this presentation I will discuss the double checked locking idiom, and explain why it does not work to provide thread safety to Java Singletons. I will also talk about how using volatile fields will fix the problem in JDK 1.5 onwards. slide 2 (Singleton): Many of you might already have used the Singleton design pattern . In case you have not, here is a brief description of what Singletons are. The Singleton pattern is used when we want to ensure...

What is type erasure in Java?

I had read about type erasure in Java a long time back. However, today when a friend asked me a question related to type erasure, I found myself not quite certain of the answer. I read up on it again and here is what I learned. Angelika Langer has an excellent FAQ , where she explains generics, and type erasure. According to the FAQ: A process that maps a parameterized type (or method) to its unique byte code representation by eliding type parameters and arguments. OK, let's understand what that means. Below is a simple class which uses the generified version of Java Lists. package  net.adaptivelearningonline.examples.generics; import  java.util.ArrayList; import  java.util.Iterator; import  java.util.List; public class  GenericsErasure  {    public static  void  main ( String args []) {      List<String> list =  new  ArrayList<String> () ;  ...

Bit manipulation in Java

I have always had a hard time remembering rules of bit manipulation in Java. So, when someone asked this question on Stackoverflow.com , I knew he had to do masking, but I forgot why. I decided to look up bit wise operations on Wikipedia to refresh my memory. However, this time I am also blogging the answer so I don't forget (yet another use of blogging :-) ). There are two types of bit shift operations: arithmetic shift, and logical shift. An arithmetic right shift preserves the sign bit, while logical shifts always insert a zero. Representing -1 as a signed byte we get: 11111111 -1 >> 1 gives us: 11111111 -1 >>> 1 gives us: 01111111 so by this logic (-1 >>> 8) should give us 00000000 which is 0 Well not so: byte b = -1; System.out.println("-1 >>> 8 = " + (b >>> 8)); The output I get is: -1 >> 8 = 16777215 Hmmm. what just happened? Java converted the signed byte into a signed int, and then did an arithmetic right shift of...

Getting interested in polyglot programming

From the last few days I have started learning Groovy by listening to the Groovy series podcasts . While listening to the podcast on numbers ( attached_code ), I couldn't help smiling when I saw this (line 42 in the attached code): assert 1/2 == 0.5 Yes 1/2 is actually 0.5 in Groovy. Isn't that awesome :-) We all know what we get when we write this code in Java: System.out.println("1/2 = " + 1/2); A few other things I found interesting about Groovy numbers are: def bigDecimalObj = 5.12345 assert bigDecimalObj.class.name == 'java.math.BigDecimal' Groovy treats all floating point numbers as BigDecimal (there are exceptions, but I will not get into that here). We all know how difficult it is to implement high precision calculations in Java. We cannot use double, because we may lose precision in calculations involving double. The alternative of using BigDecimal results in unreadable code. However, Groovy can be compiled to bytecode and can coexist with Java. So n...

Creating Boolean Objects

Have you ever written this line of code? Boolean b = new Boolean(false); According to FindBugs (and rightly so) should not instantiate Boolean objects in Java as we did above. Instead we must use the creational method provided to us. Boolean b = Boolean.valueOf(false); This is better for performance. Since we can have only two Boolen values, either true or false, the JVM can cache both these objects, and we can reuse them across our application by using the above creational method, instead creating new Boolean objects every time we need them. Discuss this post in the learning forum .

Make build scripts in GANT

I have always used ANT to create build scripts, and by and large it has served me well. ANT is simple, and it has a wide variety of tasks, which take care of almost all build requirements. Sometime back when I came across a new build tool called GANT , I was curious as to what it would offer that ANT did not. GANT is really Groovy + ANT. For those of you who are not familiar with Groovy, it is a dynamic language which compiles to bytecode and interoperates very well with Java. So GANT uses Groovy as the language to create build scripts. However all ANT tasks have been made available through Groovy's ANTBuilder. So GANT can use ANT under the hoods, but it is not limited to ANT. If we need to write custom stuff for a build script, we can either create our own custom ANT task, or alternatively we can write a Groovy function or class. This along with being able to easily add consitional logic in build scripts is a very useful feature. Also since we use Groovy for creating the build s...

Unicode newline character in Java string

The other day I was trying to represent a String in unicode characters. String s = new String ( "\u0041 \u000A" ) ; What I wanted was this "A \n", and instead, what I got was a COMPILE ERROR String literal is not properly closed by a double-quote What the hell! I have represented characters as unicode earlier in my Java code. So what was wrong here. It seems the compiler did not like the unicode newline character I had added. Here's why... The compiler translates unicode characters at the beginning of the compile cycle. Which means the above source first gets converted to String s = new String ( "\u0041 " ) ; before compilation starts. Now it is quite obvious why compilation would fail. Check out section 3.2 on Lexical Translations to understand what exactly happens in the translation phase of lexical analysis. You might also enjoy reading this issue of the Java Specialists newsletter. If you trying to represent newline or carraige return character...

XML attribute value normalization

A couple of days back I was debugging a failed test case which was testing an XML generated by a Servlet. We were using JDom for generating the XML, and XMLUnit for testing. Testing involved comparing the generated XML with an XML on disk. The test case was failing on a '\n' character in one of the attributes of the generated XML. The XML generated by the Servlet was something like this: <root att="test \n value"> but JDom seemed to be putting some strange characters in place of '\n' Now I had absolutely no idea about this, but the XML specification has something called "XML attribute normalization". Among other things, while adhering to this specification, JDom replaces all '\n' with Look here for more details. The moment I replaced the '\n' in the expected data, the test worked like a charm.

Singletons

In the previous post I had said that it may not be a good idea to have static attributes in your class. The Singleton design pattern also uses a static attribute to hold the Singleton instance. Even though there are valid uses of Singletons, lately this pattern has come under considerable attack . Here is another page on the Portland Pattern Repository Wiki , that outlines a practical problem someone faced while using Singletons. Google has an open source tool to detect Singletons. They call it the Google Singleton Detector . They have identified 4 types of Singletons, namely: Singletons, Hingletons, Mingletons, and Fingletons. You can find definitions for all the funny _ingletons on their wiki , but for those of you too lazy to visit the wiki, I will quote them here: Singleton: A class for which there should only be one instance in the entire system at any given time. This program detects singletons which enforce their own singularity, which means they keep one static instance of the...

Using static attributes in Java

As you will probably know, the 'static' keyword in Java is used to denote fields, methods, and inner classes that do not belong to any instance of a class. They belong to the class itself and can be accessed when the class is loaded. In this post we will focus on static fields and very briefly discuss pitfalls of their usage. Static fields are used for a variety of reasons: To define constants In the Singleton design pattern As global stores for application wide settings For mapping default objects (like formats) with Strings Several other reasons depending on the requirements A few days back I was reviewing some code, and I realized that mutable static fields were being used in way too many places. This can make the code very brittle. When an object has a mutable static field, for all practical purposes this becomes a global variable, and thus has all the pitfalls of global variables. Some object might change the value, and another object that was depending on the old value wi...

Docking Frames

Docking Frames is an excellent Java docking framework. There are a few other docking frameworks out there also, like FlexDock , MyDoggy , and VLDockin g, but from all of them I found DockingFrames to be the best for my requirements. DockingFrames just works. I found very little inconsistency and bugs in it. Also it uses static variables very judiciously which was important for our use, since we might want to use docking in multiple places in the application, such that each of those do not know of each other. I also found the lead contributor to be very responsive. He was extremely prompt in answering questions and always gave good suggestions. DockingFrames uses the concept of themes for docking. A theme specifies things like icons, buttons, tabs, etc that appear in the panels that contain the docked components. In the beginning I used the BasicTheme and the FlatTheme. However, BasicTheme uses angular tabs (for selecting components that are docked in tabs), which I liked more than t...

Do you like static imports?

Static imports have been around since Java 1.5, but they are a feature that I have rarely used, or even seen much in code. I guess that's because static imports is not a must have thing, but something that is nice to have . Using static imports takes some pain away from typing code. For example, instead of writing System.out.println("some message"); we could statically import System.out and write it as follows: static import  System.out; public class  HelloWorld  {    public static  void  main ( String args []) {      out.println ( "Hello World" ) ;    } } Well using static imports definetely takes the pain away from typing System.out every time. However sometimes using static imports can also reduce the readability of code, because we would have to look at the imports to know if a variable in code was declared within that class itself or imported statically. Hav...

Spot the mistake

Can you spot the mistake in this code? // BROKEN - throws NoSuchElementException! for (Iterator i = suits.iterator(); i.hasNext(); ) for (Iterator j = ranks.iterator(); j.hasNext(); ) sortedDeck.add(new Card(i.next(), j.next())); If not, check this article on the Java for...each loop. Note: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net

The risk of invoking public methods in Java

In the past few posts we have discussed how it can be dangerous to extend a class that we do not control, if it has not been designed for subclassing. We understood this concept with a specific example from Josh Bloch's book: Effective Java. In the example we subclassed the HashSet class in the JDK. Without repeating the material, I will simply reiterate what I said in my previous post: The real problem was the class AbstractCollection which was not designed properly for inheritance. It is a non-final class with a public method addAll(Collection c) which invokes another non-final public method add(Object o) . Here is a possible implementation of the HashSet class that does not break the DRY principle and is also safe for extending...

Never invoke a public method from another public method

In the previous post we saw how subclassing from a class not designed for inheritance, can be dangerous. Using composition instead of inheritance would have solved the problem. But what was the crux of the problem? Could such a trap have been avoided? Could AbstractCollection have been implemented so that such a situation would not have arisen in the first place? The real problem was the class AbstractCollection which was not designed properly for inheritance. It is a non-final class with a public method addAll(Collection c) which invokes another non-final public method add(Object o) . How should AbstractCollection have implemented add(Object o) and addAll(Collection c) to prevent such a problem? I do not know if this problem has been fixed in OpenJDK. They may have not been able to do so to maintain backwards compatibility. You can check out the sources from their website . In the next post we will discuss an idiom for preventing such a situation.  Discuss this post in the...

A student's perspective on Java

From some time I have been very keen to publish a post that describes a student's perspective on Java. Over the years Java has gone from a simple easy to learn language to quite a huge beast. The volume of things one has to learn and keep up in Java poses a special challenge to students who wih to learn the language. I would like to post experiences of how various students coped with the challenge of learning Java. In this post, Sanket Daru, a student in one of my Java classes at SCIT describes his experience with Java. I am particularly glad to post Sanket's thoughts, since he is one of the brightest and most enthusiastic students, that I have had the pleasure of teaching. Q. How did you go about learning Java? A. It all began in 2003 during my graduation. We had Java in our curriculum. I attended the Java faculty’s first and second lecture and knew that “maybe he is a genius, but he knows nothing about the heads or tails of teaching.” Convinced and determine...

Compiling Java source files with supplementary characters

Java source files can also contain supplementary characters as strings as well as identifiers if the character is a string or a digit. Here is a video that shows how we can compile Java source files that contain supplementary characters as Strings. Click on the image to download the video.     Note: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net

Changes in Java to support supplementary Unicode characters

Support for supplementary characters might need changes in the Java language as well as the API. A few questions come to mind. How do we support supplementary characters at the primitive level (char is only 16 bits)? How do we support supplementary characters in low level API's (such as the static methods of the Character class) ? How do we support supplementary characters in high level API's that deal with character sequences? How do we support supplementary characters in Java literals? How do we support supplementary characters in Java source files? The expert commitee that worked on JSR-204 dealt with all these questions and many more (I'm sure) . After deliberating as well as experimenting with how the changes would affect code, they came up with the following solution. The primitive char was left unchanged. It is still 16 bits and no other type has been added to the Java language to support the supplementary range of unicode characters.  Low level API's, such as ...

It's been a while since I posted

It's been a week since I posted last. I am really sorry, this is the second time in succession that I have missed my target of posting at least thrice a week. By way of an excuse, all I have is a lame "it's been a bit crazy at work" . I am messing around with a lot of client side technologies, like AJAX and the plethora of libraries that accompany it, and all this without really understanding Javascript well enough. One of the libraries I am checking out is DWR (Direct Web Remoting) . It allows Javascript code to invoke Java objects. All this is done by creating proxy objects in Javascript that make AJAX calls to the DWR Servlet, which in turn invokes the Java objects. I personally think, it's a very nice concept, and it also supports reverse AJAX. Would you like to know more about DWR? Please comment and let me know. I will then post a series on DWR after completing the current one on Unicode characters.   On a total tangent, here's a little something from ...

Supplemantary character support in Java

In the last post I wrote that supplementary characters in the Unicode standard are in the range above U+FFFF, which means they need more than 16 bits to represent them. Since the char primitive type in Java is a 16 bit character, we will have to use 2 char's for them. I just finished reading some stuff on supplementary character support in Java, and well, there are parts I understood right away and parts that are going to need further reading. I will try to share what I am learning on this blog. However, let us first clarify some terminology. Character: Is an abstract minimal unit of text. It doesn't have a fixed shape (that would be a glyph ), and it doesn't have a value. "A" is a character, and so is "€", the symbol for the common currency of Germany, France, and numerous other European countries. Character Set: Is a collection of characters. Unicode is a coded character set that assigns a unique number to every character defined in the Unicode ...