JDK7 The Future of The Java Platform

I am very like to play with JDK 7 and with their new features. Not only because this is the future of the Java SE and JDK, but because new features is possible to extend the capabilities of your applications with less coding.

Now I’ll try to figure out some of new features and small changes in JDK 7 and Java SE 7.


Small (Language) Changes: Project Coin

Strings in Switch.
Earlier in the switch design could use types char, byte, short, int, Character, Byte, Short, Integer and Enum.
Now, supported and line – String:

switch (str) {
    case "Oracle":
        doOracleMethod(); break;
    case "Sun":
        doSunMethod(); break;
    default:
        doDefault();
}

Diamond Operator < >
Operator < > (Diamond) is designed for easy creation of instances of parameterized types.

Instead:

Map<String, List<String>> anagrams = new HashMap<String, List<String>>();

Now you can write slightly shorter:

Map<String, List<String>> anagrams = new HashMap<>();

Binary Literals.
Support of the binary representation of integers:

int  i   = 0b11;
long num = 0b111110100000000L;

Underscores in Numbers.
Comfortable record of the long numbers:

int  bigMask = 0b1010_0101;
long big     = 9_223_783_036_967_937L;
int  i       = 91_000_000;

Unsigned literals.

byte b = 0xffu;

Now supports all types and submission:

long n9 = 0b1111_0000_1111_1111_1111L;

Resource Management.
Manually closing resources is tricky and tedious.

public void copy(String src, String dest) throws IOException {
    InputStream in = new FileInputStream(src);
    try {
        OutputStream out = new FileOutputStream(dest);
            try {
                 byte[] buf = new byte[8 * 1024];
                 int n;
                 while ((n  = in.read(buf)) >= 0)
                      out.write(buf, 0, n);
            } finally {
                 out.close();
            }
    } finally {
            in.close();
    }
}

Now Automatic Resource Management.

static void copy(String src, String dest) throws IOException {
     try (InputStream in  = new FileInputStream(src);
         OutputStream out = new FileOutputStream(dest)) {
         byte[] buf = new byte[8192];
         int n;
         while ((n  = in.read(buf)) >= 0)
             out.write(buf, 0, n);
     }
//in and out closes
}

Index Syntax for Lists and Maps.

List<String> list = Arrays.asList(new String[] {"a", "b", "c"});
String firstElement = list[0];

Map<Integer, String> map = new HashMap<>();
map[1] = "One";

Multi Catch (Maybe Back in JDK7).

  • Longstanding request to allow catching Ex1 and Ex2 together;
  • Members of e1 and e2 have direct common superclass;
  • ObjectStreamException.
// Old way
try { ...
} catch (InvalidClassException e) { foo(); }
} catch (InvalidObjectException e) { foo(); }
} catch (FileNotFoundException e) { bar(); }

// Possibly new way. Forgotten old
try { ...
} catch (InvalidClassException, InvalidObjectException e1) { foo(); }
} catch (FileNotFoundException e2) { bar(); }

Want to learn more?
Project Coin →


Modularity in JDK 7

This is important change in the language and JVM!
What is a module?

  • New construction in the Java language. The module combines classes and interfaces from one or more packages;
  • New access modifier. Elements of API can be accessed from different packages that belong to the module, and at the same time be hidden from access from other modules and applications;
  • The module is characterized by name and version. Introduction versions depending on the specific control system modules. JDK 7 will use Jigsaw – system management modules with open source;
  • It can depend on other modules. Description of the module, its dependencies and additional information are placed in the file module-info.java

Sample of the module with versioning:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// example/module-info.java
module org.planetjdk.example @ 1.0 { // Module name
      system jigsaw;                 // Module system
      requires module jdom @ 1.*;    // All of dependencies
      requires module tagsoup @ 1.2.*;
      requires module rome @ = 1.0;
      requires module rome-fetcher @ = 1.0;
      requires module joda-time @  [1.6, 2.0];
      requires module java-xml @ 7.*;
      requires module java-base @ 7.*;
      class org.planetjdk.example.Main; // Main class
}

From monolithic JDK to a set of modules!

This will:

  • Increase the download speed and performance;
  • To reduce memory consumption;
  • Effectively manage extensibility of the platform;
  • Create modular applications and libraries.

Want to learn more?

Project Jigsaw →


Dynamic Languages Support (Da Vinci Machine Project)

The goal of the project:
Effective implementation by the virtual machine applications written in dynamic programming languages (Ruby, Python, Groovy, Scala and others).

How it works?

JSR 292 adds a new JVM instruction invokeDynamic. This instruction allows dynamic selection and timing method being called by download-able methods (bootstrap methods), and references to methods (method handles).

Links to the methods developed under JSR 292, can be optimized by the JIT compiler. Different adapters provide change, rearranging, adding, deleting and other operations with the arguments of the method, called by link.

An experimental version of the implementation of instruction invokeDynamic and links to methods have been added to JDK7.
In addition, as part of JSR 292 is being developed:

  • Continuations and coroutines;
  • The introduction of interfaces and methods to existing classes;
  • Dynamically change classes;
  • Optimize tail recursion;
  • Other opportunities.

Want to learn more?

Multi-Language VM

Project Lead


Annotations on the types in JDK 7

Annotations appeared in JDK 1.5. In JDK 7, this functionality is significantly enhanced!

What has changed?

Previously, annotations could be used for element declarations API: classes, interfaces, fields, methods, constructors, annotations and packages. Annotations allow, for example, to carry out useful test for Java programs:

@Override
int overriddenMethod() {}

JSR 308 significantly expands the annotated Java space program, which significantly increases the possibility of verifying the source code. All use types can be annotated:

  • Types of parameters and return types;
  • Inherited types;
  • Types of parameterization;
  • Types in cast and other operations.

New annotations allow for more precise control of the data, for example, to minimize the possibility of NullPointerException or unauthorized alteration of data.

Examples:

// List of non-zero rows
List<@NonNull String> stringList;

// Nonempty list of strings
@NonEmpty List<String> stringList;

// Method should not change the arg and its object
void marshall(@Readonly Object arg) @Readonly

Want to learn more?

JSR308 Washington EDU

JSR308 on JCP


New I / O capabilities

  • Access to extended attributes of files and file systems;
  • Notifications of changes to files and directories;
  • Asynchronous I / O;
  • Support MIME-type information files;
  • Copying and moving files means the file system.

Other options:

  • Working with symbolic links;
  • Improved mechanisms for networking;
  • Free access to the contents of binary files;
  • Ability to add functionality to work with the new file system.

Want to learn more?

NIO.2 Project

More NIO APIs for Java

Also, you may download the latest JDK 7 snapshot, install it and look at the JDK_HOME/sample/nio/ for examples of use NIO.2.


Java SE on the desktop. What’s new?

JLayer:

  • The universal decorator for Swing components;
  • It helps to expand the capabilities of existing components without the need to fix their code;
  • Use the pattern “decorator” – wrap components and implement the logic, as well as any special effects with a class LayerUI;
  • Is already available in the JDK 7.

Here is a simple example how to create and use LayerUI which paints translucent foreground over the layer:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// wrap your component
JXLayer<JComponent> layer = new JXLayer<JComponent>(myComponent);

// create custom LayerUI
AbstractLayerUI<JComponent> layerUI = new AbstractLayerUI<JComponent>() {
    @Override
    protected void paintLayer(Graphics2D g2, JXLayer<JComponent> l) {
        // this paints layer as is
        super.paintLayer(g2, l);

        // custom painting: here we paint translucent foreground over the whole layer
        g2.setColor(new Color(0, 128, 0, 128));
        g2.fillRect(0, 0, l.getWidth(), l.getHeight());
    }
};

// set our LayerUI
layer.setUI(layerUI);

// add the layer as a usual component
frame.add(layer);

Let’s see how to apply the grayScale effect to a layer:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// wrap you component
JXLayer<JComponent> layer = new JXLayer<JComponent>(myComponent);

// here we use BufferedLayerUI which can work with BufferedImageOps
BufferedLayerUI<JComponent> bufferedLayerUI = new BufferedLayerUI<JComponent>();

// create a ColorConvertOp to apply grayScale effect
BufferedImageOp grayScaleOp = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);

// create a BufferedImageOpEffect with the provided BufferedImageOp
BufferedImageOpEffect imageOpEffect = new BufferedImageOpEffect(grayScaleOp);

// set BufferedImageOpEffect to the bufferedLayerUI
bufferedLayerUI.setLayerEffects(imageOpEffect);

// set the bufferedLayerUI to the layer
layer.setUI(bufferedLayerUI);

// add the layer as a usual component
frame.add(layer);

More about JXLayer

JWebPane.

  • Component for integration with the Java Web application;
  • Based on WebKit – the modern handling Web content with open source;
  • Provides a display of HTML / CSS / JavaScript;
  • Supports access to the context of JavaScript;
  • Accesses the DOM;
  • Compliant W3C.

That’s than easy:

JWebPane browser = new JWebPane();
new JFrame("Browser").add(browser);
browser.load(someURL);

You may check it out by download the latest JDK 7 snapshot!.

  • Miller

    Why did you mention ObjectStreamException? It’s inside this lib starting at Java 1.1 same as the subclasses. And did you check your examples? Most don’t compile because the language features are not implemented (yet).

  • terje

    Nice post! There ‘s only one thing I don’t understand though, this line:

    byte b = 0xffu;

    0xffu is 255, but byte can only have numbers in the range [-128,127], so what will happen here? Imho, more logical would be to have

    ubyte b = 0xff;

    which would mean that ubyte has numbers in the range [0,255] & this assignment is then possible.

    Can someone explain me how this is working please?

  • http://apupeikis.wordpress.com apupeikis

    I’m mentioned about ObjectStreamException for shortness. We may catch InvalidClassException, InvalidObjectException and any other subclasses separately if we need so. But if we just want to catch an exception without specific subclasses we may use ObjectStreamException instead.
    I’m playing with JDK7 and, unfortunately, you right. Still not all features are workable. Thus, we need to remember, what JDK7 is not a final release. It just a snapshot of the development process. It’s a short observe of new features what will be available in the final release.

  • http://apupeikis.wordpress.com apupeikis

    The ‘u’ character here will talk to compiler what it will be an unsigned literals.
    With signed literals they can have range [-128, 127] as you mentioned. As unsigned, they can have range [0, 255].
    May be this will help you -> http://www.daniweb.com/forums/thread110076.html#

  • zammbi

    Is JWebpane coming in Java 7? I thought it was going to be separate library.

  • http://apupeikis.wordpress.com apupeikis

    I was wondering if the Swing team would work to push it and in the works projects into JDK 7 before its release. We’ll see it. On Sun Tech Days I’m hear about it.

  • Zs

    I haven’t found any reference to JWebpane in the jdk, where it is?

  • http://apupeikis.wordpress.com apupeikis
  • http://www.healthandskinny.com Michal Runyan

    thanks to your ideas , i¡¯d adore to adhere to your weblog as usually as i can.possess a good day

  • http://webhostingpadcoupon.blog.com/ Webhostingpad Coupon Code

    Ah, I find the fact has unlimited debatable points. I do not need to argue with you right here, however I’ve my very own opinions as well. Anyway, you did an important job in writing the put up, and would like to praise you for the onerous work. Keep up with the great job!

  • http://polprav.blogspot.com/2010/04/elitech.html Vero_nikky_19

    it was very interesting to read.
    I want to quote your post in my blog. It can?
    And you et an account on Twitter?

  • http://www.apleben.com Alexander Pupeikis

    sure, you can make it. and yes, I’m on twitter.

  • http://www.pozycjonowanie-google.us/pozycjonowanie-warszawa/ pozycjonowanie warszawa

    I am quite interesting in this topic hope you will elaborate more on it in future posts

  • http://reallyreview.blogspot.com/2010/07/is-article-creation-software-scam.html Matthew Barranco

    I found your entry interesting so I’ve added a Trackback to it on my weblog :) … thanks

  • Doradztwo kredytowe

    When I search for blogs I never know what I will find and that is half of the fun of it really. I was surprised I ran across yours though. It is excellent writing though. You have talent in there – keep it up.

  • http://ask.com ask

    I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own BlogEngine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it.

  • http://www.olyd.com/ Wonda Sokol

    What a comment!! Very informative and also easy to understand. Looking for more such comments!! Do you have a facebook?
    I recommended it on digg. The only thing that it’s missing is a bit of speed, the pictures are appearing slowly. However thank you for this information.

  • Lyme disease

    Appreciate it for this is what fine article; this is the kind of aspect that prevents me though out the day.I have forever really been seeking around for one’s web page soon after I over heard about them from a buddy and was happy when I was in a position to uncover it after searching for some time. Being a experienced blogger, I’m delighted to view other people taking gumption and donating towards the neighborhood. I just wanted to comment to display my appreciation in your publish as it is really inviting, and lots of freelance writers tend not to get the credit they ought to have. I’m positive I’ll be back again and will send out some of my buddies.

  • http://www.apleben.com Alexander Pupeikis

    Thanks a lot for your “short” review :)