The small pleasures of programming

It’s not just pulling off a complex engineering feat that makes programmers love their jobs. There are small pleasures to be had even in your day to day tasks, if you look for them.

Seasoned programmers know the thrill of recognising the possibility to introduce an abstraction over duplication. A task as simple as renaming a variable can be the difference between obscurantism and lucidity. It’s the boy scout principle in action. Making your code a bit more pleasant to revisit. The joy one derives in these simple improvements is akin to Amélie’s les petits plaisirs.

[Read more]

Representing natural numbers in lambda calculus

One of the joys of reading SICP is that apart from the main subject matter, we come across many tangential topics that are interesting in their own right. One such topic is mentioned in Exercise 2.6: Church numerals. Named after the mathematician Alonzo Church, Church numerals are a way of representing natural numbers in lambda calculus. But what is λ-calculus?

From a programming perspective, λ-calculus can be thought of as the smallest universal programming language. It lacks some of the common features that one would expect in a programming language like, primitives, booleans, numbers etc. In this language, variable substitution and functions are used as the building blocks to express everything else. Even numbers! In this post we will get a glimpse of how this is achieved.

[Read more]

Using thread dumps to analyse deadlocks

In a multi-threaded Java application, a deadlock occurs when two threads wait forever attempting to acquire locks that are held by each other. Here’s a simple example to simulate a deadlock:

public class Deadlock {
    private Object lock1;
    private Object lock2;

    public Deadlock(Object lock1, Object lock2) {
        this.lock1 = lock1;
        this.lock2 = lock2;
    }

    public void methodA() {
        System.out.println("trying to acquire lock1 from - " + Thread.currentThread().getName());
        synchronized (lock1) {
            someLongRunningTask();
            methodB();
        }
    }

    public void methodB() {
        System.out.println("trying to acquire lock2 from - " + Thread.currentThread().getName());
        synchronized (lock2) {
            someLongRunningTask();
            methodA();
        }
    }

    private void someLongRunningTask() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[]args) {
        Object lock1 = new Object();
        Object lock2 = new Object();

        new Thread(() -> new Deadlock(lock1, lock2).methodA()).start();
        new Thread(() -> new Deadlock(lock1, lock2).methodB()).start();
    }
}
First thread calls methodA and acquires lock1. Second thread calls methodB and acquires lock2. Then the first thread calls methodB while at the same time the second thread calls methodA. Both are trying to acquire a lock that is already held by another thread, so neither can proceed further.

[Read more]

Setting up a JavaScript project in 2017

Creating a front-end JavaScript project can be a daunting task due to the sheer volume of choices available while deciding the tech stack. First, you need to decide the JavaScript framework or library for your project. Do you plan to use the latest ES2015 language features in your code? If yes, then you need a transpiler because your browser probably doesn’t support them yet. Then you require a bundling tool to get your code loaded in the browser. You may want to minify the code for faster load time. To automate all these steps, you need a build script. You may want to deploy your project on a local web server during development. Some setup is required for that. Finally, you need to include some testing framework in your project to write unit tests.

[Read more]

Hystrix – a simple use case

Hystrix is a fault tolerance library that is very useful for managing failures in a distributed environment like microservices. Suppose we have a service A dependent on service B, which is in turn dependent on service C.

A -> B -> C

Let’s say a call is made from A to B. To serve this request, B needs to call C but there’s a communication failure between them. If the call from B to C is wrapped in Hystrix mechanism, we prevent the failure being propagated to A. Because B couldn’t fetch the actual information from C, Hystrix gives us the option of declaring a fallback value to be used in this case, if feasible.

[Read more]

Running time intensive operations in parallel with RxJava Observables

Recently I delved into the RxJava library. In this post I will demonstrate how RxJava Observables can be used to execute two long running tasks in parallel, so as to reduce their overall execution time.

While we can create threads for this purpose, an additional benefit of using Observables is that it provides a convenient way of collecting the results of the parallel tasks. With threads, this can get pretty complicated. Let’s consider a situation where we have a consumer class that depends on the result of two or more expensive independent tasks.

public class Producer1 {
  public List<Integer> produce() {
    List<Integer> list = new ArrayList<Integer>();
    
    for(int i=0; i<5; i++) {
      System.out.println("Producer1 - " + i);
      try {
        Thread.sleep(1000);
      } catch(Exception e) {}
      list.add(i);
    }
    return list;
  }
}
public class Producer2 {
  public List<Integer> produce() {
    List<Integer> list = new ArrayList<Integer>();
    
    for(int i=0; i<5; i++) {
      System.out.println("Producer2 - " + i);
      try {
        Thread.sleep(1000);
      } catch(Exception e) {}
      list.add(i);
    }
    return list;
  }
}

[Read more]

In case of any query, revert back to me

If you have ever worked in an office in India, you would have encountered the phrase “revert back” at the end of official emails. When people ask you to “revert back”, they are actually asking you to “reply back”. It is an Indian colloquialism and in fact people think that using this phrase makes them sound more formal!

Of course languages are used differently in different parts of the world. But I have always wondered in which scenario would asking someone to “revert back” be a doable request? Now I have an answer.

[Read more]

Logging with Spring AOP

Aspect oriented programming (AOP) is a way of separating the business login in your code from cross cutting concerns. What is a cross cutting concern?

Analogy time. A typical house has different rooms that have designated functions. We keep our stuff in the rooms where they make sense. The living room is an unlikely location for a dishwasher and a bathtub belongs in the bathroom. But the electric circuit runs throughout the house because it is not tied to the functionality of any specific room. Thus, the electric circuit is a cross-cutting concern.

[Read more]

Memory profiling – simple examples

Recently I have been trying to learn different memory profiling tools to monitor Java applications. I have looked into the command line tools that are shipped as part of JDK like jstat, jps, jvisualvm etc. Licensed tools like Yourkit provide wholesome information about a running JVM including memory usage, CPU time, thread count etc. Running a java application with -verbose:gc option prints memory usage of each generation after every garbage collection event.

[Read more]

JPA Entity Relationships

In a relational database, the relationships between two tables are defined by foreign keys. Typically, one table has a column that contains the primary key of another table’s row. In JPA, we deal with entity objects that are Java representations of database tables. So we need a different way for establishing relationship between two entities. JPA entity relationships define how these entities refer to each other.

For the purpose of this article, I will work with JPA 2.0 and a table structure as following.

CREATE TABLE team(team_id NUMBER, name VARCHAR2(20));
INSERT INTO team(team_id, name) VALUES(1, 'india');
INSERT INTO team(team_id, name) VALUES(2, 'australia');
INSERT INTO team(team_id, name) VALUES(3, 'england');


CREATE TABLE player(player_id NUMBER, name VARCHAR2(50), team_id NUMBER, age NUMBER, role VARCHAR2(20));
INSERT INTO player(player_id, name, team_id, age, role) VALUES(1, 'sachin', 1, 42, 'batsman');
INSERT INTO player(player_id, name, team_id, age, role) VALUES(2, 'dhoni', 1, 34, 'wicketkeeper');
INSERT INTO player(player_id, name, team_id, age, role) VALUES(3, 'clarke', 2, 38, 'batsman');
INSERT INTO player(player_id, name, team_id, age, role) VALUES(4, 'rogers', 2, 40, 'batsman');
INSERT INTO player(player_id, name, team_id, age, role) VALUES(5, 'cook', 3, 31, 'batsman');
INSERT INTO player(player_id, name, team_id, age, role) VALUES(6, 'root', 3, 26, 'batsman');

CREATE TABLE player_stat(player_stat_id NUMBER, player_id NUMBER, runs NUMBER, wickets NUMBER);
INSERT INTO player_stat(player_stat_id, player_id, runs, wickets) VALUES(10, 1, 10000, 300);
INSERT INTO player_stat(player_stat_id, player_id, runs, wickets) VALUES(20, 2, 5000, 10);
INSERT INTO player_stat(player_stat_id, player_id, runs, wickets) VALUES(30, 3, 7000, 100);
INSERT INTO player_stat(player_stat_id, player_id, runs, wickets) VALUES(40, 4, 2000, 0);
INSERT INTO player_stat(player_stat_id, player_id, runs, wickets) VALUES(50, 5, 9000, 0);
A team can have multiple players. A player can have a statistic.

[Read more]