Archive

Posts Tagged ‘Java’

Service initialisation with automatic dependency based ordering

January 16th, 2012 Nick No comments

Situation

The Application Controller of our application initialises all of its services when it itself is initialised. Unsurprisingly, some services must be started before others; for example the Logging service must be started before the Configuration service, which must be started before the Persistence service, which must be started before the Authentication service and so on.

Currently, all this initialisation is done in one long initialiseServices() method, initialising each service in the correct order. If we create a new service then we just slot it into this method in the right place. Providing this order is not changed then everything is fine.

The problem

So what’s the problem? Well, apart from being a bit ugly, there is a practical problem that has arisen. Our client would like to be able to deploy parts of the application separately, which means we need to split it up into a core which rarely changes and separate modules which can be deployed independently. If one of these modules requires a new service, or one of its services becomes dependent on another, then the Application Controller will also need to be deployed. Not only will the client need to deploy the new module but also a whole new core. Also, the client must wait until both the module and the core builds become stable.

The solution

What would be ideal is if each module could tell the Application Controller which services it needs when the application starts. The Application Controller would then determine the order in which to initialise the services based on their dependencies. Cyclic dependencies would be detected upon startup.

A prototype

In order to demonstrate this, I’ve made a little mock-up. This is probably best understood by looking at the code, but I’ll try and explain it as best I can in words.

The idea is that all Services must extend an abstract base class; Service. The abstract Service class provides public method addDependency(Service service) which is used to specify the other services on which it is dependent. The sorting algorithm is not interested in services on which each service is dependent, but rather the services which depend on each service. This is because the graph of service dependencies is traversed depth-first, from the services without any other services on which they depend. Therefore, the addDependency(Service service) method actually calls a package-private addDependent(Service service) method on the passed service object.

Services are then added to a Service Manager. The services are initialised by calling initialiseServices() on the Service Manager which creates an instance of ServiceReactor which does the sorting, returning an ordered list of services which are to be initialised sequentially.

The ServiceReactor uses topological sorting to arrange the services based on the graph of dependencies.

The example I’ve provided sets up the simple graph as described here:
http://en.wikipedia.org/wiki/Topological_sorting

Note that I didn’t want to make a separate Service classes for each node, so I made an IdentifiableService which gets a unique integer passed to its constructor which is used to identify it as a separate Service. Of course in reality each Service would be defined by its own, separate implementation of the base Service class.

Feel free to download it and have a play with it. For example, try creating a circular dependency and you should get a DirectedCycleException. I know, it really is that much fun!

Download example:
ServiceReactor

Categories: Java Tags: , , ,

Attach IntelliJ debugger at application startup

March 24th, 2011 Nick 2 comments

Normally when I want to debug a Java appliaction, I run the application and then connect the IntelliJ remote debugger to the JVM. Today I needed to debug the boot sequence of the application which meant I needed the debugger attached right from the start so as to catch the breakpoints at the beginning of the boot sequence, connecting manually would be too late.

In IntelliJ I changed the debugger mode from “attach” to “listen”. It then told me to use these command line arguments for the JVM:

-Xdebug -Xrunjdwp:transport=dt_socket,server=n,address=nick-laptop:5005,onthrow=,suspend=y,onuncaught=

What it doesn’t say is what values to use for the “onthrow” and “onuncaught” options. After a bit of fiddling I got it to work by setting “onuncaught=n” and removing entirely the “onthrow” clause:

-Xdebug -Xrunjdwp:transport=dt_socket,server=n,address=nick-laptop:5005,suspend=y,onuncaught=n

Linux users…

If you’re not using Linux then you can skip this bit, if you are, then this might be useful. I found it annoying to set IntelliJ to listen for incoming debug connections before starting the application, most of the time it’s fine tohave the JVM in listen mode and initiate connections as-and-when from IntelliJ. As a solution I added a couple of aliases to my ~/.bashrc file so that I could swap the behaviour easily:

# For IntelliJ in attach mode
export MAVEN_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005"
alias ijattach='export MAVEN_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005"'

# For IntelliJ in listen mode
alias ijlisten='export MAVEN_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,server=n,address=nick-laptop:5005,suspend=y,onuncaught=n"'
Categories: Java Tags: , , ,

Spinning command line cursor in Java

January 29th, 2010 Nick No comments

As a follow-up to my previous article on displaying a spinning cursor to display program activity, I have created a more useful example that could be adapted for use.

The original problem was this – I was writing a program that performed a particular task and I needed some way of showing the program was alive and functioning correctly whilst doing the task.

In Windows this is done by changing the mouse cursor into an hourglass, unfortunately on the command line we don’t have such GUI luxuries. One classic option is to create a spinning line by displaying | / – \ and so on.

The example below creates two child threads; one to do a particular job (in this case slowly count to 10) and another thread to display a spinning cursor.

/**
 * Spinning cursor test class
 *
 * @author Nick Giles
 */
public class SpinTest
{
    /**
     * Thread which does the stuff we're interested in
     *
     */
    private Thread stuff;

    /**
     * Thread class which does stuff in the background
     *
     */
    private class Stuff implements Runnable
    {
        public void run()
        {
            int result = 0;

            try
            {
                // Slowly count to 10, although you can of course put whatever
                // you want here, presumably something a bit more useful
                while (result < 10)
                {
                    result++;
                    Thread.sleep(1000);
                }
            }
            catch (InterruptedException e)
            {
                // If interrupted then quietly end the thread, you may well
                // want to handle this in some way
            }
        }
    }

    /**
     * Spinner thread
     *
     */
    private class Spinner implements Runnable
    {
        public void run()
        {
            String[] phases = {"|", "/", "-", "\\"};

            try
            {
                while (true)
                {
                    for (String phase : phases)
                    {
                        System.out.printf("\b"+phase);

                        Thread.sleep(100);
                    }
                }
            }
            catch (InterruptedException e)
            {
                // No need to do anything if interrupted
            }
        }
    }

    /**
     * Handles all shutdown functions
     *
     */
    public class ShutdownHandler extends Thread
    {
        public void run()
        {
            // On interrupt, stop doing stuff
            stuff.interrupt();
        }
    }

    public void doStuff()
    {
        try
        {
            // Attach an object to handle shutdown signals (i.e. ctrl+c)
            Runtime.getRuntime().addShutdownHook(new ShutdownHandler()); 

            // Create a new thread for spinning the cursor
            Thread spinner = new Thread(new Spinner());

            // Create a new thread for doing stuff
            this.stuff = new Thread(new Stuff());

            // Nice message to user
            System.out.printf("Doing stuff...  ");

            // Start doing stuff
            this.stuff.start();

            // Start spinning the cursor
            spinner.start();

            // Check the thread doing stuff is still doing stuff
            while (stuff.isAlive())
            {
                stuff.join(1000);
            }

            System.out.printf("\bDone.\n");

            // The thread doing stuff has finished, so stop spinning
            spinner.interrupt();

            // Wait for the spinning thread to terminate
            spinner.join();

            System.out.println("The End.");
        }
        catch (InterruptedException e)
        {
            System.out.println("Interrupted");
        }
    }

    /**
     * Main method
     *
     */
    public static void main(String[] args)
    {
        SpinTest test = new SpinTest();

        test.doStuff();
    }
}

It’s a fairly basic implementation but it should be fairly simple to extend it for a real-world application.

Spinning command line cursor in Java and PHP

January 29th, 2010 Nick 1 comment

Update: I have created an updated article which describes a multithreaded approach in Java Spinning command line cursor in Java

I think I must be really bored this morning, I can’t believe I’m actually blogging this, but it might be useful for someone, who knows.   Anyway, I am currently writing a program that sits and does stuff for a very long time, and I need a way to nicely indicate the program is still running and doing its stuff.   So I have created a little method that prints a spinning cursor on the command line.   The implementation would of course have to be multithreaded; one thread to do stuff, the other to spin the cursor – if there’s time I’ll update it to a more complete solution, but for now here’s the spin implementation:


public class Spin
{
    public static void main(String[] args) throws InterruptedException
    {
        String[] phases = {"|", "/", "-", "\\"};

        System.out.printf("Spinning... |");

        while (true)
        {
            for (String phase : phases)
            {
                System.out.printf("\b"+phase);
                Thread.sleep(100);
            }
        }
    }
}

And here it is in PHP.

<?php

    $phases = array("|", "/", "-", "\\");

    printf("Spinning... |");

    while (1)
    {
        foreach ($phases AS $phase)
        {
            printf('%s%s', chr(8), $phase);
            usleep(100000); // Replace this with one iteration of doing stuff
        }
    }

Of course PHP doesn’t support threading so you’d have to call each iteration of the “doing stuff” loop inside the spin loop which would mean you’d get a bit of a jumpy spinning cursor but I think most people could live with that.

Categories: Java, PHP Tags: , , , , ,

Syntax error, parameterized types are only available if source level is 1.5

December 19th, 2009 Nick 2 comments

I recently installed Eclipse and all of a sudden my Java applications failed to build with the error:

Syntax error, parameterized types are only available if source level is 1.5

After a bit of Googling I figured out that Eclipse installed a different JVM and set it as the default one.   On Ubuntu (at least) the way to change the default JVM is by typing this into the console:

sudo update-alternatives --config java

It will show you which JVM is currently selected and allow you to choose a different one as default.

Categories: Java Tags: , , , , , ,

Java: touch – set file last modified time

December 11th, 2009 Nick No comments

I just discovered that I need to touch() a file in Java. It appears there isn’t a way to do this using the standard Java library, so I rolled my own:

import java.io.*;
import java.util.Date;

class Touch
{
    /**
     * Touches a given file
     *
     * @author Nick Giles <http://www/4pmp.com/>
     */
    public static void main(String args[])
    {
        try
        {
            // Create a new file object for the file we want to touch
            File f = new File("touch.txt");

            // See if the file already exists
            if (f.exists())
            {
                // The file already exists, so just update its last modified time
                if (!f.setLastModified(System.currentTimeMillis()))
                {
                    throw new IOException("Could not touch file");
                }
            }
            else
            {
                // The file doesn't exist, so create it
                f.createNewFile();
            }
        }
        catch (SecurityException e)
        {
            System.err.println("Security Error: " + e.getMessage());
        }
        catch (IOException e)
        {
            System.err.println("IO Error: " + e.getMessage());
        }
    }
}

Just like the Linux command, if the input is a directory then it will update the last modified time for the directory but not recurse into it. If you need to recurse then the above can easily be extended to recurse itself using f.isDirectory() and f.listFiles(). If anyone needs this then just let me know and I’ll rustle it up, but for now I’ll leave that as en exercise for the reader :-)

Categories: Java Tags: , , , ,