Moving to chandershivdasani.blogspot.com

I’m retiring my wordpress blog and moving to blogspot. My new home is at: chandershivdasani.blogspot.com

Abstract Classes vs Interfaces

The distinction between Abstract Classes and Interfaces has been mentioned zillion times, every time the key difference mentioned being the same old multiple inheritance. In Item 18 of Effective Java, the author goes beyond this common difference and explains at what places we should prefer Interfaces over Abstract Classes. In this post, I’m going to summarize those differences.

Existing classes can be retrofitted to implement the new interface

This is, what I feel, the biggest advantage of using interfaces. When Collections API were introduced, many existing classes were retrofitted to use Comparable interface. This wouldnt have been possible through Abstract Classes.

Interfaces allows the construction of nonhierarchical types

Not every relation can be represented as an hierarchy. Say, for example, A Singer who is also a Song Writer. Such a relation cannot be defined as an hierarchy, at least not in an intuitive manner. Using interfaces, we can define two interfaces and have our Person class implement both of them. In essence, these interfaces would like follows:

  interface SongWriter {

      Lyrics writeSong();

  }

  interface Singer {

      Audio sing();

  }

Interfaces are ideal for defining mixins

A mixin is a type that a class can implement in addition to its primary type, to declare that it provides some optional behavior. For example, Serializable is a marker interface that indicates that a class can be serialized. Another such example is Comparable, that allows a class to declare that its instances are ordered with respect to other objects.

Adapter vs Facade vs Decorator pattern

For all those like me who often get confused between these three patterns, the following definitions with examples will help demystify that.

Facade: Make an interface simpler. Internally uses instances of different type.

e.g: javax.faces.context.ExternalContext internally uses ServletContext, HttpSession, HttpServletRequest.

Decorator: Doesnt alter the interface, but adds responsibility. They take instance of the same abstrace/interface type and add responsibility to it.

e.g: java.io.BufferedInputStream(InputStream)(Returns a InputStream)

Adapter: Converts one interface to another. They take an instance of different abstract/interface type and return an implementation own/another instance type which decorates the given instance.

e.g: java.io.InputStreamReader(InputStream) (Returns a Reader)

Amortized time in simple words

Today, I stumbled onto this post at StackOverflow, that explains Amortized time in plain, simple words.

From the post:

If you do an operation say a million times, you don’t really care about the worst-case or the best-case of that operation – what you care about is how much time is taken in total when you repeat the operation a million times.

So it doesn’t matter if the operation is very slow once in a while, as long as “once in a while” is rare enough for the slowness to be diluted away. Essentially amortised time means “average time taken per operation, if you do many operations”. Amortised time doesn’t have to be constant; you can have linear and logarithmic amortised time or whatever else.

Let’s take mats’ example of a dynamic array, to which you repeatedly add new items. Normally adding an item takes constant time (that is, O(1)). But each time the array is full, you allocate twice as much space, copy your data into the new region, and free the old space. Assuming allocates and frees run in constant time, this enlargement process takes O(n) time where n is the current size of the array.

So each time you enlarge, you take about twice as much time as the last enlarge. But you’ve also waited twice as long before doing it! The cost of each enlargement can thus be “spread out” among the insertions. This means that in the long term, the total time taken for adding m items to the array isO(m), and so the amortised time (i.e. time per insertion) is O(1).

Fair toss from a Biased coin

Problem:

Given a biased coin that turns up heads 60% of the times, can we simulate an unbiased coin toss?

Solution:

The solution to this problem is attributed to Von Neuman, which makes use of symmetry.

  • Toss the coin twice.
  • If it comes either HH or TT, ignore and toss again.
  • If it comes up HT, output a H and if comes up TH, output a T

Why does this work?

We need to come up with a way to toss the coin that has equal probability for its outcome.

P(HH) = 0.6*0.6

P(TT) = 0.4*0.4 

Since, P(HH) != P(TT), we ignore the outcome and repeat the toss again.

P(HT) = 0.6*0.4 == P(TH) = 0.6*0.4

Now that the outcomes have same probability, biased is removed!

Non blocking stack

Implemented a simple non blocking stack using java.concurrent.atomic package. Unlike the java.util.Stack, this stack iterates in a LIFO order.

Source code can be found at: https://github.com/chandershivdasani/NonBlockingDS

Life cycle of a Servlet

In this post, I’m going to briefly explain the steps a Servlet container takes when it receives a Servlet request from a client.

When a web container like Tomcat identifies a request as being for an HttpServlet, it creates HttpServletResponse and HttpServletRequest objects.

The next step it does is to look for the appropriate servlet and load it in to the JVM. After the class is loaded, it is initialized by calling its no-arg constructor. After the constructor is completed, servlet’s init() method, which it inherited from a GenericServlet, is called. This is called only ONCE in the Servlet’s life time and must complete before servlet can start “serving” requests.

After initialization, Servlet’s service() method is called. In the service() method, a request is identified as an Http GET request or an Http POST request. Based on this, Servlet’s doGet() or doPost() method is called and the HttpServletResponse and HttpServletRequest objects are passed to it.

Each request for a particular Servlet gets run as a separate thread. Once the request is served Servlet’s destroy() method is called, giving it a chance to clean up before its killed.

This post serves as a gentle introduction as well as a quick brush up  on the life cycle of the servlet. There are many things i didnt cover for the sake of brevity. For a more complete and comprehensive introduction on Servlets, refer Oracle’s documentation.

Lessons from Alice in Wonderland

Alice: Would you tell me, please, which way I ought to go from here?
The Cat: That depends a good deal on where you want to get to
Alice: I don’t much care where…
The Cat: Then it doesn’t much matter which way you go.
Alice: …so long as I get somewhere.
The Cat: Oh, you’re sure to do that, if only you walk long enough.

Java I/O Quick Reference Guide

As daunting as it may sound, creating a good I/O system is one of the most important and difficult challenges in front of a programmer. This is pretty evident when one looks at numerous classes inside java.io package.

When designing such systems, it is important to understand the different types of sources and sinks that you want to communicate with. A little knowledge of this, coupled with a quick reference guide of the major classes inside java.io package, can go a long way in eliminating most of the design issues. For a detailed tutorial on former, refer sun’s io tutorial.  This blog post is the latter.

Byte Streams

Byte streams are used to handle raw binary data. They perform input and output of 8-bit bytes.

Base Classes:             InputStream and OutputStream

Common child classes:  FileInputStream, FileOutputStream, ObjectInputStream, StringBufferInputStream, FilterInputStream

Character Streams

Even though Byte Streams provide a way to write to files, it represents a low level kind of I/O which should be avoided. Since, most of the text files are character data, the best way to access them is using character stream.

Character values are stored in java using Unicode conventions. Character streams automatically translates internal representation to and from the local character set.

Base Classes:                    Reader, Writer

Common sub classes:     FileReader, FileWriter, BufferedReader, InputStreamReader, BufferedWriter, OutputStreamWriter, PrintWriter

Byte Stream to Character Stream Bridges

Most of the times, you would wrap byte streams with character streams, there by letting byte streams to perform the low level I/O. Two wrapper classes InputStreamReader and OutputStreamReader can do this for you. The main need for this arises when reading and writing to sockets.

Line oriented I/O

Reading a file character by character can be cumbersome.                                                                                                                                                    Classes BufferedReader and PrintWriter  provides functions like readLine() and println(),  to read and write lines.

Buffered Streams

In an unbuffered I/O, each read and write request is directly handled by the underlying OS. This can be very expensive if a program performs frequent but smaller reads/writes, since each operation will trigger disk access, network latency and other operations.

To overcome this, java provides a way to buffer I/O streams. These can be done using BufferedReader and BufferedWriter.

Data Streams

Data Streams can used to perform binary I/O on primitive data types: boolean, char, byte, short, int, long, float, double and String.

Base interfaces:    DataInput, DataOutput

Common implementations: DataInputStream, DataOutputStream

Object Streams

They are used to perform serialization. Serialization is a process of converting object state into a format that can be stored and then later reconstructed.

Classes needs to implement a marker interface Serializable to be able to get serialized.

Commonly used classes: ObjectInputStream and ObjectOutputStream

This ends the quick reference. I hope you got a fairly decent idea about the commonly used I/O classes. Any feedback/suggestions are welcomed. As a future enhancement , i plan to add code snippets of each type.

In my next post, i plan to do a similar write up about NIO (New I/O).

Keep Watching this space for more!

–CS

Coffee flavored Yogurt

Recipe from my friend Dhruv Matani:

  • Take about 1/2 tsp. instant coffee powder (Nescafe, etc…) and make a fine powder with your fingers. Put the powder in a bowl.
  • Take about 2.5 tsp. sugar and add to the same bowl.
  • Take about 1 cup (240 ml) of cold yogurt and mix thoroughly with the coffee powder and sugar in the bowl using a spoon.
  • Once it has formed a light brown homogenous paste, eat to your heart’s content!
Follow

Get every new post delivered to your Inbox.

Join 141 other followers