<Swing Dev> Swing and imageio-related types that are candidates to be FunctionalInterfaces in JDK 8

Brian Goetz brian.goetz at oracle.com
Tue Feb 12 15:04:31 UTC 2013


>    Lambda is a new feature in Open JDK 8.  Could you give some
> explanation about Lambda and FunctionalInterface annotation usage in
> AWT/Swing?
>
>    Here are some statements that can be correct or not (I am not an
> expert in JDK lambda):
>
>    1. It is good practice to use Lambda for the AWT/Swing listeners:
>           button.addActionListener(e -> ui.dazzle(e.getModifiers()));
>        http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-4.html

Generally yes.  In cases where a lambda is a possibility, you still have 
a choice of a lambda or an inner class.  The benefit of using a lambda 
is inversely proportional to the code size of the body.  So for a one 
liner, you get your biggest syntactic payback.  Lambdas also have some 
performance advantages; their worst case performance equals inner 
classes best case performance.

>     2. Adding  FunctionalInterface annotation allows the compiler to
> check that the interface has only one abstract method.

Correct.  It also captures and documents your INTENT that this is a type 
suitable as a lambda target type.

>        However, all works in the same way if an interface does not have
> the FunctionalInterface annotation.

Correct.  The compiler does not use @FI to determine target type 
compatibility.

>    3. Users should care about Swing classes usage in Lambda methods
> invoked in in parallel because Swing classes should be updated from ETD.

Here, lambdas are exactly the same story as inner classes.  A lambda 
expression evaluates to an object of a given functional interface type; 
no threads involved.  And the APIs we are introducing in Java SE 8 do 
not introduce any additional non-explicit concurrency or parallelism. 
If you *ask* for parallelism, you'll get it, but if you simply say

   collection.forEach(e -> System.out.println(e));

the forEach loop will invoke the lambdas sequentially in the current thread.

>    May be something else that could give better understanding of the
> Lambda features usage in AWT/Swing and how Swing should be adopted for
> the Lambda?

The primary benefits will be:
  - decreased capture cost (lambda capture is often cheaper than inner 
class capture)
  - More readable code

These benefits in turn enable API designers to design APIs that have 
finer-grained interactions between the client and library.  For example, 
with lambdas, SwingWorker might have been practical to write as a method 
instead of a class.




More information about the swing-dev mailing list