Venkatesh Shukla Code ramblings

Java 8 - Functional interface with lambda

Java 8 introduces lots of new elements in the java syntax like lambda and functional interfaces.

These changes, even though just syntactic sugar over the previous syntax, change drastically the way a Java code looks. Someone, who is used to traditional Java and is well versed with it, would easily be baffled looking at those arrows -> and double quotes ::.

I would like to explore one of the new elements here. That is the functional interface.

Functional interface, also known as, Single Abstract Method (SAM) interface is a well known and already existing construct in Java. It looks something like this

public interface Runnable {
    void run();
}

So, by definition, SAM or functional interface is an interface in java having only a single method defined in it. It might extend other interfaces as long as the following conditions are met.

  1. There is only one abstract method defined. This is considering both the current interface and its parent. There can be any number of default methods.
  2. java.lang.Object methods can be present, like toString and equals. They are redundant.

Runnable interface is a well known example and belongs to java.lang package.

Till java 7, to execute something in a new thread, something like this would be used.

Thread t = new Thread(
    new Runnable() {
        @Override
        public void run() {
            System.out.println("Hello, parallel World!");
        }
    }
);
t.start();

It uses an anonymous class which implements the Runnable interface. But, as we can see, the real executable statement here is in the line 5. The other lines do not more than cluttering the code. This obviously makes the syntax heavy.

As an improvement, in Java 8, one can use the following lambda syntax to initialise a functional interface.

Thread t = new Thread(() -> System.out.println("Hello, world!"));
t.run();

Here the lambda expression () -> System.out.println() is actually the implementation of the abstract run method of Runnable interface.

As we can see, the syntax is way more lighter. And the real executable line is clearly visible without the clutter.

In a way, it can be said that java 8 has given new life to functional interfaces.

Pro Tip : Use annotation @FunctionalInterface while defining a functional interface to get compile time errors and warning.

Example

One more code sample for methods with arguments.

A sample functional interface

@FunctionalInterface
public interface Printable {
    void print(String a, String b);
}

A function expection a Printable object and the calling main method.


public class DemoFunctionalInterface {
    public static void callPrintable(Printable p) {
        p.print("Apple", "Ball");
    }
    public static void main(String[] args) {
        callPrintable((a, b) -> System.out.println("Printing " + a + " " + b));
    }
}

This main method would print Printing Apple Ball.


Reference

  1. State of the lambda
  2. java.lang.Runnable
  3. Translation of lambda expressions
  4. Functional interface : Recreation in Java 8
  5. Defender or default methods
  6. java.lang.FunctionalInterface

PM2 : Process manager for Node

While looking at the docs for managing this ghost powered blog, I came across this cool piece of technology called PM2.

It is essentially a process manager for node (as can be gathered from the title :). But it is a sophisticated one at that. It is targeted for production systems and is currently used by tech companies like Paypal and Intuit.

Besides just managing the node processes, restart on crash, start on boot, PM2 also provides app monitoring and a nice terminal based interface. One of the useful features is the no-downtime reload, which is especially helpful if you are changing the setting of your blog often. Moreover, it has the ability to remotely deploy your apps as well. Debugging needed? You have the tailed logs. Another feature to mention is the cluster mode of operation using which an application can be run by multiple process which are load balanced. This improves the performance of the application.

All in all, if you are using node for some of your applications, a simple nohup node index.js &, though simplistic and helpful, might not be the entire solution.

You would need some mechanism to maintain it (keep the process running, recover from crash, monitor memory and CPU usage, etc). And in that case, PM2 would be one of the most comprehensive options out there.

So quickly, some of the helpful command of PM2. A comprehensive list can be found here.

  • Start a node application : pm2 start index.js --name 'app-name'
    In the response, you would get a table, with the name of your application and an id attached to it. This could be used to refer to this process.

  • List the applications : pm2 list
    Also lists the modules

  • Stop the application : pm2 stop id
    It stops the application. But it would still remain in the pm2 grid.

  • Delete the application : pm2 delete id
    It stops the application and remove from the grid.

  • Reload the application : pm2 reload id
    This restarts the running applications with no downtime. The no-downtime part works only for cluster mode of operation. pm2 reload all to reload all applications.

  • Check the logs : pm2 logs id/app-name
    This is equivalent to doing tail -f. Logs are polled and printed on screen. There are also the option of rotating logs. This is done using pm2-logrotate module[^3].

  • Monitor : pm2 monit
    Monitor the memory and cpu of the running applications.

  • Kill the pm2 process : pm2 kill
    Kill all the running applications and pm2 itself.

  • Startup pm2 startup Detects the platform, generates a startup script and configures the startup system.

  • Starting in cluster mode pm2 start -i 4 index.js
    Run the application in a cluster of 4 processes.

  • Scale up the application : pm2 scale app-name 10

Ghost specific settings

For normal start, we use the options --mode=production. For starting via pm2, this option would not work. For starting in production mode, declare a variable called NODE_ENV and set its value to production. Something like this : export NODE_ENV=production After this, run pm2 start index.js --name=ghost for starting the ghost via pm2.

For some reason, the cluster mode is not working for ghost. I would have to look more on this.

Open Source

One of my foremost metric for evaluation of a library or a product is it being open source. And yes, like all cool stuff I talk about here, PM2 is open source. You can look through it’s code here. It has more than 3000 commits as of date.

Do try this out.

Cheers.


  1. Code : https://github.com/Unitech/pm2
  2. Website : http://pm2.keymetrics.io/
  3. Install using pm2 install pm2-logrotate. Logs are found here : ~/.pm2/logs.

Google Analytics with Github pages

Google analytics is a wonderful product by Google which helps us in tracking user interaction with your site.

Adding that to Github pages is an easy task, thanks to the amazing post here.

The best part about this blog post is that the local hosting is not tracked, owing to this section of _includes/head.html.

{% if jekyll.environment == 'production' %}
{% include analytics.html %}
{% endif %}

Brief mention of the other parts.

_config.yml

# Google services
google_analytics: UA—XXXXXXXX-X

This property can be referred as site.google_analytics from anywhere in the project.

Finally, the analytics.html, referred to in the first section, add the google-analytics snippet with the tracking code placeholder.

An example here.

_includes/analytics.html

<script>
    (function(i, s, o, g, r, a, m) {
        i['GoogleAnalyticsObject'] = r;
        i[r] = i[r] || function() {
            (i[r].q = i[r].q || []).push(arguments)
        }, i[r].l = 1 * new Date();
        a = s.createElement(o),
            m = s.getElementsByTagName(o)[0];
        a.async = 1;
        a.src = g;
        m.parentNode.insertBefore(a, m)
    })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');

    ga('create', '{{ site.google_analytics }}', 'auto');
    ga('send', 'pageview');
</script>

ArchLinux - tick tock

We all need time. And we all feel the need to keep looking at a clock.

For a default installation of arch + openbox, I do not have any clock. For seeing the time, I often have to use date command, or just look for my phone or wallclock.

A simple one liner to fix it.

xclock -digital -update 1 &

Tadaa.. You have a clock on your screen. Enter exit to quit the terminal.

Pro tip : Right click on title bar. Select Un/decorate. You have persistent clock which looks as if it is a part of the background. Beware, it becomes unmoveable.

Pro tip 2 : Use killall xclock to remove the clock.

Cheers

ArchLinux - Brighten up

Even though we have sophisticated commands like xbrightness and xrandr, it is fun to learn this mundane way to vary screen brightness.

With root permissions, navigate to this location /sys/class/backlight.

You might have one out of intel_backlight (Intel graphics) or acpi_video0 (ATI graphics). Go into that directory.

$ ls /sys/class/backlight/intel_backlight
actual_brightness  brightness  max_brightness  subsystem  uevent
bl_power           device      power           type

Now, cat max_brightness and brightness files to find out the max and current values of brightness.

$ cat /sys/class/backlight/intel_backlight/max_brightness 
4882

$ cat /sys/class/backlight/intel_backlight/brightness 
400

Now, to change brightness, change the value in the brightness file. You cannot make it higher than the max_brightness.

$ echo 200 > /sys/class/backlight/intel_backlight/brightness 

There you go, mundane method to change screen brightness.

Cheers

Refer

  1. https://wiki.archlinux.org/index.php/backlight