Java 7: Try-With-Resources (AutoCloseable)

Another great thing introduced with Java 7 is the “try-with-resources” construct – previously known as Automatic Resource Management (ARM). This feature is part of Project Coin, which is an umbrella project for a set of small changes to the Java language. You can see my other post on Java 7: Project Coin for more info.

When you work with files, networks streams or databases you follow a common pattern.

  1. Open resources
  2. Perform operation
  3. Close resources

You have to wrap the code in a try-finally block to make sure the resources are closed even if an exception occurs. Take a look at this example that copies the contents of one file to another file.

    public void oldStyleCopyFile(File source, File target) {
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream(source);
            out = new FileOutputStream(target);
            byte[] buffer = new byte[4096];
            int read;
            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

Java 7 introduces a new construct called try-with-resources. You can initialize the resources inside parenthesis between the try keyword and the opening bracket, and Java will automatically close them for you. This works for all resources that implement the AutoCloseable interface.

    public void newStyleCopyFile(File source, File target) {
        try (
                FileInputStream in = new FileInputStream(source);
                FileOutputStream out = new FileOutputStream(target);
        ) {
            byte[] buffer = new byte[4096];
            int read;
            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Java 7 also contains NIO.2 which improves file operations in Java, and adds several essential features that Java has been missing. For example, now you can copy a file in one line. As a bonus this method not only copies the file contents but also the file metadata!

    public void shortCopyFile(File source, File target) {
        try {
            Files.copy(source.toPath(), target.toPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Java 7: Project Coin

Java 7 is just around the corner. Sadly it does not contain the highly anticipated closures/lambda expressions, but instead it includes a set of small language changes developed under the codename “Project Coin”.

In this post I will explore the basic language changes.

Strings in switch

Yes, finally you can switch on string constants in switch statements!

    public void executeCommand(String command) {
        switch (command) {
            case "start":
                startService();
                break;

            case "stop":
                stopService();
                break;

            case "status":
                showStatus();
                break;

            default:
                unknownCommand();
        }
    }

 

Binary Literals and Underscores in Numeric Literals

If you work with computer graphics, signal processing or integrate with old native C libraries, you often have to perform bit-manipulations and bit-masking etc. For some strange reason Java only supported decimal, octal and hexadecimal literals. Java Coin adds support for binary literals with the 0b prefix, and now it is legal to use underscores inside all numeric literals to make them easier to read.

    public void numericLiterals() {
        int mask1 = 0b1000100010001000;
        int mask2 = 0b1000_1000_1000_1000;

        int color = 0xff_f0_fe_ff;

        int price = 1_000_000;

        double PI = 3.141_592_653_589_793d;
    }

 Type Inference for Constructing Instances of Generic Types

This feature is going to remove a lot the verbosity of generic types. Take for example this example of a Map of a List of Strings:

    public void createGenerics() {
        List<String> list = new ArrayList<String>();
        Map<String, List<String>> keyValues = new HashMap<String, List<String>>();
    }

    public void createWithDiamondOperator() {
        List<String> list = new ArrayList<>();
        Map<String, List<String>> keyValues = new HashMap<>();
    }

The first method demonstrates the old way of creating generified collections.

The second method demonstrates how you can save a lot of typing by using the diamond operator <> and let the compiler infer the types from the left hand side.

Multi-Catch Exceptions

If you want to perform the same exception handling for a set of Exception types you can now catch them in a single catch statement by separating the types with a pipe character

    public void multiCatch(Class<MultiCatch> myClass) {
        try {
            Method method = myClass.getMethod("sayHello");
        } catch (NoSuchMethodException | SecurityException e) {
            // common exception handling logic
        }
    }

Automatic Resource Management

The final part of Project Coin is support for automatic resource management, which I will explore in a separate blog post.

Simple HTML5 Todo List

Lately I have been experimenting with Ender. It is a JavaScript library with a twist. In fact the authors refer to it as “no-library library”. It is a tiny wrapper and a command line tool that you can use to construct a Javascript library from a range of microframeworks. This way you only get the features you actually need, and in theory you can pick and choose between alternative implementations of the individual featues, so you get a library that matches your preferred programming style.

I have created a small todo-list that uses local storage in the browser to persist your todo items. This way, the todolist will remember your items from last visit, without storing anything on the server!

Fra LED til Simon

Here is the slides, a video and the source code from a 15 minute speed-talk I did for the Tech Talk Tuesday at OSAA yesterday.
It shows the highlights of how to build a clone of the classic Simon game, using an Arduino and some buttons and LEDs. In Danish only!

Slides

View more presentations from giddy.

The Video Demonstration

Source Code

/*
 * Arduino Clone of the classic Simon Game
 *
 * Made at Hack Aarhus / OSAA
 * http://www.hackaarhus.dk
 * http://www.osaa.dk
 *
 * Released into the public domain by
 * Rene Hangstrup Moeller, July 2010
 *
 * http://www.giddyplanet.com
 */

//---------------------------------------------------------
//	GLOBALS weeeee!
//=========================================================

// the number of leds/switches
int SIZE = 4;

// milliseconds delay between each element in the sequence
int PLAY_DELAY = 250;
int INPUT_DELAY = 200;

// the sequence
int sequence[128];

// current sequence length
int seqlen = 0;

// Sound frequencies for each led-switch pair
int notes[] = {
    261/2, 392/2, 587/2, 880/2
};

//---------------------------------------------------------
//	PIN MAPPINGS
//=========================================================

// the buzzer control pin
int buzzPin = 11;

// calculate pin for led
int ledPin(int num) {
  return (num + 1) * 2;
}

// calculate pin for button
int buttonPin(int num) {
  return ledPin(num) + 1;
}

//---------------------------------------------------------
//	HELPER FUNCTIONS
//=========================================================

// mute the buzzer and turn off all leds
void turnOff() {
    noTone(buzzPin);
    for (int n = 0; n < SIZE; n++) {
      digitalWrite(ledPin(n), LOW);
    }
}

// new game
void newGame() {
  // generate random sequence with two entries
  sequence[0] = random(SIZE);
  sequence[1] = random(SIZE);
  seqlen = 2;

  // blink leds 10 times to indicate game start
  for (int i = 0; i < 10; i++) {
    for (int n = 0; n < SIZE; n++) {
      digitalWrite(ledPin(n), HIGH);
    }
    delay(200);

    turnOff();
    delay(200);
  }
}

// add an entry to the sequence
void expand() {
  sequence[seqlen++] = random(SIZE);
}

// play the sequence
void playSequence() {
  Serial.println("Playing sequence");

  for (int i = 0; i < seqlen; i++) {
    int v = sequence[i];
    tone(buzzPin, notes[v]);

    for (int n = 0; n < SIZE; n++) {
      digitalWrite(ledPin(n), n == v ? HIGH : LOW);
    }

    delay(PLAY_DELAY);
    noTone(buzzPin);

    for (int n = 0; n < SIZE; n++) {
      digitalWrite(ledPin(n), LOW);
    }

    delay(PLAY_DELAY);
  }
  turnOff();
}

// wait for button press
int nextButton() {

  while (true) {

    for (int n = 0; n < SIZE; n++) {
      if (digitalRead(buttonPin(n)) == HIGH) {
        digitalWrite(ledPin(n), HIGH);

        while (digitalRead(buttonPin(n)) == HIGH) {
          delay(INPUT_DELAY);
        }

        turnOff();
        return n;
      }
    }
    delay(INPUT_DELAY);
  }

  return 0; // never
}

// read sequence from player
int readSequence() {
  for (int i = 0; i < seqlen; i++) {
    int nb = nextButton();

    if (nb != sequence[i]) {
      Serial.println("Error");
      return false;
    }
  }

  Serial.println("Accepted");
  return true;
}

//---------------------------------------------------------
//	ARDUINO ENTRY POINTS
//=========================================================

// initialize the Arduino
void setup() {
  // initialize random number sequence
  randomSeed(micros() + analogRead(0));

  // configure pins for LEDs and buttons
  for (int i = 0; i < SIZE; i++) {
    pinMode(ledPin(i), OUTPUT);
    pinMode(buttonPin(i), INPUT);
  }

  // configure pin for sound
  pinMode(buzzPin, OUTPUT);

  // initialize serial communication for debugging
  Serial.begin(9600);
  Serial.println("Setup completed. Welcome to Simon");
}

// The game loop - each run corresponds to a game
void loop() {
  Serial.println("Starting new game");
  newGame();

  int running = true;

  while (running) {
    delay(1000);
    playSequence();
    running = readSequence();
    if (running) {
      expand();
    }
  }   

  delay(250);
}

Simplicity

Stumbled upon this fantastic quote:

It seems strange to have to emphasize simplicity. You’d think simple would be the default. Ornate is more work. But something seems to come over people when they try to be creative. Beginning writers adopt a pompous tone that doesn’t sound anything like the way they speak. Designers trying to be artistic resort to swooshes and curlicues. Painters discover that they’re expressionists. It’s all evasion. Underneath the long words or the “expressive” brush strokes, there is not much going on, and that’s frightening.

When you’re forced to be simple, you’re forced to face the real problem. When you can’t deliver ornament, you have to deliver substance.

http://www.paulgraham.com/taste.html