Friday, October 18, 2013

LruCache in Java

Java collections has LinkedHashMap which is a combination of a HashMap and a linked list which allows for predictable iteration order. There are two options for iteration - Based on insertion order, or based on Access order.

Now to create a Least Recently Used cache, the implementation need to use the access order for iteration and override the hook method removeEldestEntry() which should check the required size of the map to remove entries. I've posted the code in the example below.

Also present in the example is how you should *not* use the map in an multithreaded fashion. The class is not thread-safe and you end up with non deterministic behavior and the size invariant and probably other things go wrong.

Sunday, May 19, 2013

Functional Programming Principles in Scala

I just completed the Functional Programming Principles in Scala course at https://www.coursera.org/course/progfun with my solutions at https://github.com/rrevo/progfun . It was a good experience learning both about Functional programming and Scala.
Overall the new features compared to an OO language like Java were-
  1. Higher-order functions
  2. Case classes and pattern matching
  3. Immutable collections
  4. Flexible evaluation strategies: strict/lazy/by name

It was refreshing to try and solve problems without mutation. However this also has a higher performance cost. Most of my current work is in Java and so I can translate some of these ideas to my work. Preferring immutability is a good idea for concurrency anyways and this was also brought up by Effective Java and Concurrency in Practice.

Scala as a language was also pretty interesting. Higher-order functions and the other features made code much more succinct than java. I did find myself trying to minify code into a single line at times. But at the same time this density meant that reading code at a later time was definitely much harder. Since types are also inferred, I did end up spending quite a bit of time trying to reason about the types of variables.

Java 8 will have some form of higher-order functions. That should close the gap between the languages slightly. However scala also has many other features and libraries that also have immense value. Choosing between either still depends on many other factors.

Thursday, January 03, 2013

Spring vs Guice default scopes

Spring and Guice are popular Inversion Of Control (IoC) frameworks. One of the most important aspects of IoC is how the framework creates new instances for value. This is the Scope. Some of the scopes are-

  1. Singleton (Spring default) - A single instance is created by the IoC container for the entire application lifetime.
  2. Prototype (Guice default) - A new instance is created whenever a value is needed.
In addition there are other scopes valid in a web context and custom scopes can also be defined. For additional details on scopes see Spring docs.

For stateless objects the programmer can choose either Singleton or Prototype. Guice docs recommend that prototype scope be used for Stateless objects even though only a single instance should suffice really. The rationale is to optimize for speed instead since singleton scopes require synchronization for implementation and today's JVMs are good at garbage collection.

Sunday, December 09, 2012

How does JDBC Connection Pooling work?

This post is an excerpt from the jtracer blog.

Overview

The Apache commons DBCP component provides Connection pooling for JDBC connections. In this blog I am going to use JTracer to reveal how DBCP works internally.

JDBC Primer

To connect to a database using JDBC a java.sql.Connection is needed. For creating a Connection, a JDBC driver needs to be loaded. Connection parameters like url and credentials should also be set. Once a Connection is obtained you can create a Statement to execute queries. After the Statement and Connection are used, they should be closed to clean up the resources. The DataSource API as part of the javax.sql package provides an alternate way to create connections.

Creation of Connections is an expensive process. It is better to use a connection pool that will re-use Connections for running queries rather than creating only new Connections. The DBCP project from Apache provides a BasicDataSource which also implements Connection pooling.

Continue

Continue reading at the jtracer blog.

Sunday, November 04, 2012

Overview of OSGi

What is OSGi?

OSGi is a module system and service platform for the Java platform.

For the module system, it extends the code level visibility controls that Java provides via the private, protected, public and package-private access. An application is usually packaged as multiple jars in java. Some of these are external libraries. With OSGi it is possible to specify version for a jar and dependency information between jars.

OSGi enables Service Oriented Architecture in a Virtual Machine. It provides APIs for providing a way to register services, discover and bind to them.


Specifications


The OSGi Alliance is an industry backed non-profit organization that manages the OSGi specifications. There are a many implementations like Apache Felix, Eclipse Equinox and Knopflerfish. Building on top of the core OSGi framework are runtimes that provide additional services like Apache Karaf.

Architecture


OSGi Platform

The OSGi platform is composed of the Framework and Standard services. The framework is the runtime that implements and provides OSGi functionality. The standard services define reusable APIs for common tasks.

Core framework

The core framework itself can be broken down into 3 layers - Module, Lifecycle and Service. Each layer is dependent on the layer below. The Module layer has to be used by an application but the Lifecycle and Service layers are optional.

1. Module Layer
In OSGi the unit of modularity is called a Bundle. A Bundle is basically a jar file containing additional metadata in headers with an additional file - META-INF/MANIFEST.MF.

Headers Bundle-SymbolicName and Bundle-Version are used to uniquely identify a Bundle and its version. Using the header Export-Package the Bundle can specify the packages that are visible to other packages. Import-Package and Require-Bundle are used to specify the dependencies of a Bundle.

2. Lifecycle Layer

There are 4 phases of a Bundle lifecycle
  1. Installation - The bundle jar has to be installed first from a URL. The framework automatically resolves its dependencies based on the Import-Package and Require-Bundle headers. Resolution happens transitively for all the dependent bundle as well.
  2. Execution - When the Bundles classes are first accessed or the bundle is explicitly started, it moves to a starting state
  3. Update - Bundles may be updated to a different version using the API
  4. Removal - Finally bundles may be uninstalled.
Some of the important APIs that allow this functionality are-
org.osgi.framework.BundleActivator
org.osgi.framework.BundleContext
org.osgi.frameword.Bundle

3. Service Layer

The OSGi framework allows registration of services, discovery and binding to them. Bundles may be installed and uninstalled allowing for dynamic services and possibly multiple implementations.

The org.osgi.framework.BundleContext class provides APIs for this service layer.

Services

An OSGi platform provides core services some of which are-
  • Package Admin (org.osgi.service.packageadmin) provides the ability to control and reflect over bundle and package level resolution
  • Start Level (org.osgi.service.startlevel) controls the relative order of bundle startup by assigning start levels to bundles
  • Service Hooks (org.osgi.framework.hooks.service) allows bundles to monitor and limit service registry events and access
Some of the optional services are-
  • Log (org.osgi.service.log) for logging by bundles
  • HTTP (org.osgi.service.http) for a HTTP server with Servlet support
  • Configuration Admin (org.osgi.service.cm) Manages bundle configuration data storage and injection
  • Preferences (org.osgi.service.prefs) for management of Preferences
  • Event Admin (org.osgi.service.event) for publish-and-subscribe and topic-based event notification

Summary

OSGi does provides some valuable extensions to the core java language. Just being able to specify packages to external clients allows to design APIs without leaking unnecessary information. Classpath resolution is also well managed.
The service layer further adds to the idea of well defined APIs.

Being based on plain java classes the framework does not feel heavy like EJBs. However figuring out how to use a particular runtime is not an easy task.

Integrating with existing code and converting them to bundles is also non-trivial. If jars are not well designed APIs then there is always a problem that there are some references that will never be cleaned causing a leak. Existing code also needs to be refractored to use the OSGi services of logging and configuration.

In all OSGi has value but there is also a cost to using the framework.

Tuesday, April 24, 2012

The Concurrency Revolution II

In Dec 2004 Mohnish had posted The Concurrency Revolution based on Herb Sutter's article on the multi-core paradigm shift in processors.

Well, it's time to read the follow up - Welcome to the Jungle .


Wednesday, March 28, 2012

Ubuntu Tour

I'm running a slightly old version of ubuntu .. trying to hold moving to the new UI. I wanted to have a peek at the current state.

Opened the Ubuntu Tour and expected to see a few screenshots. But ..

The tour is actually a working Ubuntu desktop built as an HTML page! Amazing. The dash works, the start bar works with date, volume etc and other basic controls. Some applications are just images which you can drag around. Thunderbird is more complex with demo emails. Firefox is the best because you can open other webpages.. recursive browsing.

When drafting this blog, noticed that the layout reconfigures when the width of the page changes.

HTML layouts have come a long way.

Know what libraries are used for this?