java 7 new features

166
Java 7 New Features Jussi Pohjolainen

Upload: jussi-pohjolainen

Post on 19-May-2015

5.539 views

Category:

Technology


1 download

TRANSCRIPT

Page 1: Java 7 New Features

Java  7  New  Features  

Jussi  Pohjolainen  

Page 2: Java 7 New Features

Java  SE  7  Cer8fica8on  

•  “Raising  the  Bar”:  more  advanced  skills  needed  to  pass  

•  All  new  defini8on  and  focus:    – The  Associate  level  has  gone  through  significant  changes,  and  the  Professional  level  is  both  broader  and  deeper  

•  New  cer8fica8ons  –  Oracle  Cer8fied  Associate,  Java  SE  7  Programmer  –  Oracle  Cer8fied  Professional,  Java  SE  7  Programmer  

Page 3: Java 7 New Features

Oracle Certified Associate, Java SE 7 Programmer (OCA)

•  No  prequisi6es  •  Dura8on  140  min,  number  of  ques8ons  90,  passing  score  77%  

•  Price  200  –  300  e  

Page 4: Java 7 New Features

OCA: Exam Topics

•  Java  Basics  •  Working  with  Java  types  •  Using  opera8ons  and  Decision  Constructs  •  Crea8ng  and  Using  Arrays  •  Using  Loop  Constructs  •  Working  with  Methods  and  Encapsula8on  •  Working  with  Inheritance  •  Handling  Excep8ons  

Page 5: Java 7 New Features

Oracle Certified Professional, Java SE 7 Programmer (OCP)

•  You  have  to  pass  OCA  first!  •  Dura8on  150  min,  number  of  ques8ons  90,  passing  score  65  %  

•  Price  200  –  300  e  

Page 6: Java 7 New Features

OCP: Exam Topics

•  Java  Class  Design  •  Advanced  Class  Design  •  OO  Principles  •  Generics  and  Collec8on  •  String  processing  •  Excep8ons  and  Asser8ons  

•  Java  I/O  Fundamentals    

•  Java  File  I/O  (NIO.2)  •  Building  Database  Applica8ons  with  JDBC  

•  Threads  •  Concurrency  •  Localiza8on  

Page 7: Java 7 New Features

Upgrade  your  Cer8fica8on  

•  Prior  cer6fica6on  – Any  version  of  Oracle  Cer8fied  Professional,  Java  Programmer  OR  any  version  of  Sun  Cer8fied  Java  Programmer  

•  1Z0-­‐805  Upgrade  to  Java  SE  7  Programmer  •  Dur  150  min,  Number  of  ques8ons:  90,  passing  score:  60%  

•  Price  200  e  –  300  e  

Page 8: Java 7 New Features

Upgrade  Exam  Topics  •  Language  Enhancements  

–  Project  Coin  •  Design  pa@erns  

–  Singleton,  composi8on,  DAO,  factory  

•  Database  Applica6ons  with  JDBC  –  JDBC  API:  RowSetProvider,  

RowSetFactory,  new  RowSet  interfaces  

•  Concurrency  –  Atomic  variables,  locks,  

executors,  fork/join  •  Localiza6on  

–  Locales,  resource  bundles  •  Java  File  I/O  (NIO.2)  

–  Path  and  Files  -­‐  classes  

Page 9: Java 7 New Features
Page 10: Java 7 New Features

(RECAP)  JAVA  5  AND  6  

Page 11: Java 7 New Features

Versions  and  Naming  

JDK/Year  

JDK  1.1  (1997)   New  Event  Model,  Inner  classes,  JavaBeans  and  JDBC  

J2SE  1.2  (1998)   Collec8on  Framework,  Reflec8on,  Swing  API  

J2SE  1.3  (2000)   HotSpot  JVM,  JavaSound,  JNDI  

J2SE  1.4  (2002)   Regex,  excep8on  chaining,  XML  Parser,  XSLT,  Java  Web  Start  

J2SE  5.0  or  1.5  (2004)   For-­‐each,  generics,  autoboxing,  var-­‐args  

Java  SE  6  (2006)   Scrip8ng  support,  annota8ons,  GUI  enhancements  

Java  SE  7  (2011)   …  

Page 12: Java 7 New Features

New  Features  •  Java  SE  5  

–  Generics  –  Autoboxing  –  Improved  looping  syntax  –  Annota8ons  –  …  

•  Java  SE  6  –  XML  Processing  and  Web  Services  –  Scrip8ng  –  JDBC  4.0  –  …    

Page 13: Java 7 New Features

Generics   ArrayList list = new ArrayList();

list.add("a");

list.add("b");

list.add(new Integer(22));

Iterator i = list.iterator();

while(i.hasNext()) {

System.out.println((String) i.next());

}

Page 14: Java 7 New Features

Result  

Page 15: Java 7 New Features

Using  Generics   ArrayList<String> list = new ArrayList<String>();

list.add("a");

list.add("b");

list.add(new Integer(22));

Iterator<String> i = list.iterator();

while(i.hasNext()) {

System.out.println((String) i.next());

}

Page 16: Java 7 New Features

Result  

Page 17: Java 7 New Features

Enhanced  for  -­‐  loop   ArrayList<String> list = new ArrayList<String>();

list.add("a");

list.add("b");

list.add("c");

// Loop array or collection. Iteration used

// even without declaration! The list object

// must implement java.lang.Iterable interface

for(String alphabet : list) {

System.out.println(alphabet);

}

Page 18: Java 7 New Features

Java  1.4  import java.util.*; class Main { public static void main(String [] args) { // Does not work, 5 is not a Object type! someMethod(5); } public static void someMethod(Object a) { System.out.println(a.toString()); } }

Page 19: Java 7 New Features

Java  1.4:  Solu8on  import java.util.*; class Main { public static void main(String [] args) { Integer temp = new Integer(5); someMethod(temp); } public static void someMethod(Object a) { System.out.println(a.toString()); } }

Page 20: Java 7 New Features

Java  1.4:  Lot  of  Coding  

Integer a = new Integer(5);

Integer b = new Integer(6);

int aPrimitive = a.intValue();

Int bPrimitive = b.intValue();

Page 21: Java 7 New Features

Autoboxing  Comes  to  Rescue!  

class Main {

public static void main(String [] args) {

// Boxing

Integer a = 2;

// UnBoxing

int s = 5 + a;

}

}

Page 22: Java 7 New Features

Java  1.5  class Main { public static void main(String [] args) { // Works! someMethod(5); } public static void someMethod(Object a) { System.out.println(a.toString()); } }

Page 23: Java 7 New Features

Java  1.5:  For-­‐each  import java.util.*; class Main { public static void main(String [] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(5); list.add(new Integer(6)); list.add(7); for(int number : list) { System.out.println(number); } } }

Page 24: Java 7 New Features

for-­‐each  

Page 25: Java 7 New Features

Enum  •  An  enum  type  is  a  type  whose  fields  consist  of  a  fixed  set  of  

constants  •  Before  (not  type-­‐safe,  no  meaningful  prin8ng)   public static final int WHITE = 0; public static final int BLACK = 1; …  •  Now:    enum Color { WHITE, BLACK, RED, YELLOW, BLUE; }

Page 26: Java 7 New Features

Usage  enum Color { WHITE, BLACK, RED, YELLOW, BLUE; } class Main { public static void main(String [] args) { System.out.println(Color.WHITE); Color c1 = Color.RED; System.out.println(c1); }

Page 27: Java 7 New Features

Enum:  Far  more  than  in  other  languages  

•  Enum  declara8on  defines  a  full  fledged  class!  •  Enum  constants  are  public  final  sta6c  •  Compiler  adds  special  methods  like  values  that  returns  an  array  containing  all  the  values  of  the  enum.  

•  Enum  class  extends  java.lang.enum  

Page 28: Java 7 New Features

Enum  enum Color { WHITE, BLACK, RED, YELLOW, BLUE; } class Main { public static void main(String [] args) { for (Color c : Color.values()) { System.out.println(c); } } }

Page 29: Java 7 New Features

Enum  Fun  enum Color { WHITE, BLACK, RED, YELLOW, BLUE; @Override public String toString() { //only capitalize the first letter String s = super.toString(); return s.substring(0, 1) + s.substring(1).toLowerCase(); } } class App { public static void main(String [] args) { System.out.println(Color.WHITE); } }

Page 30: Java 7 New Features

Enum  Fun  enum Color { WHITE(2), BLACK(23), RED(123), YELLOW(124), BLUE(225); private int code; private Color(int c) { code = c; } public int getValue() { return code; } } class App { public static void main(String [] args) { System.out.println(Color.WHITE.getValue()); } }

Page 31: Java 7 New Features

Sta8c  Import  (1/2)  

class Main {

public static void main(String [] args) {

int x = Integer.parseInt("55");

int y = Integer.parseInt("56");

int x = Integer.parseInt("57");

}

}

Page 32: Java 7 New Features

Sta8c  Import  (2/2)  

import static java.lang.Integer.parseInt; class Main { public static void main(String [] args) { int x = parseInt("55"); int y = parseInt("56"); int z = parseInt("57"); } }

Page 33: Java 7 New Features

Metadata:  annota8ons  

•  With  Java  5  it’s  possible  to  add  metadata  to  methods,  parameters,  fields,  variables..  

•  Metadata  is  given  by  using  annota6ons  •  Many  annota3ons  replace  what  would  otherwise  have  been  comments  in  code.  

•  Java  5  has  built-­‐in  annota8ons  

Page 34: Java 7 New Features

Uses  

•  Informa8on  to  compiler  – Detect  errors  or  suppress  warnings  

•  Compiler-­‐8me  and  deployment-­‐8me  processing  – Somware  tools  may  generate  code,  XML  –  files..  

•  Typical  applica8on  programmers  will  never  have  to  define  an  annota8on  type,  but  it  is  not  hard  to  do  so.      

Page 35: Java 7 New Features

Example  

@Override

public void method() {

}

Page 36: Java 7 New Features

Example  

@Author(

name = ”Jussi Pohjolainen",

)

class MyClass() {

}

Page 37: Java 7 New Features

Example  

@Author(”Jussi Pohjolainen”)

class MyClass() {

}

Page 38: Java 7 New Features

Example  

@Author(

name = ”Jussi Pohjolainen",

date = ”2012-09-12"

)

class MyClass() {

}

Page 39: Java 7 New Features

Crea8ng  Annota8on  // Annotation type @interface ClassDocumentation { String author(); String date(); int currentRevision() default 1; } @ClassDocumentation( author = "Jussi Pohjolainen", date = "2012-09-12", currentRevision = 2 ) class Foo { }

Page 40: Java 7 New Features

Javadoc  

Page 41: Java 7 New Features

Crea8ng  Annota8on  import java.lang.annotation.*; @Documented @interface ClassDocumentation { String author(); String date(); int currentRevision() default 1; } @ClassDocumentation( author = "Jussi Pohjolainen", date = "2012-09-12", currentRevision = 2 ) class Foo { }

Page 42: Java 7 New Features

Javadoc  now  

Page 43: Java 7 New Features

Targets  // Annotation type import java.lang.annotation.*; @Target(ElementType.METHOD) @interface Something { String foo(); } class Foo { @Something(foo = "hello") public void method() { } }

Page 44: Java 7 New Features

Override:  Does  not  Compile!  class Human { public void eat() { System.out.println("Eats food"); } } class Programmer extends Human { @Override public void eatSomeTypo() { System.out.println("Eats pizza"); } } class Main { public static void main(String [] args) { Programmer jack = new Programmer(); jack.eat(); } }

Page 45: Java 7 New Features

Other  Annota8ons  used  By  Compiler  

•  @Depricated –  Gives  warning  if  when  depricated  method  or  class  is  used  

•  @SuppressWarnings –  Suppress  all  warnings  that  would  normally  generate  

Page 46: Java 7 New Features

System.out.format  import java.util.Date;

class Main {

public static void main(String [] args) {

Date d = new Date();

// Lot of format characters available!

System.out.format("Today is %TF", d);

}

}

Page 47: Java 7 New Features
Page 48: Java 7 New Features

Variable  Argument  List  class Main { public static void printGreeting(String... names) { for (String n : names) { System.out.println("Hello " + n + ". "); } } public static void main(String[] args) { String [] names = {"Jack", "Paul"}; printGreeting("Jack", "Paul"); printGreeting(names); } }

Page 49: Java 7 New Features

User  Input:  Scanner  

Scanner in = new Scanner(System.in);

int a = in.nextInt();

String b = in.nextLine();

Page 50: Java 7 New Features

Java  6:  XML  &  Web  Services  

•  Easy  way  of  crea8ng  Web  Services  •  Expose  web  service  with  a  simple  annota8on    

Page 51: Java 7 New Features

Web  Service  package hello; import javax.jws.WebService; @WebService public class CircleFunctions { public double getArea(double r) {

return java.lang.Math.PI * (r * r); } public double getCircumference(double r) { return 2 * java.lang.Math.PI * r; } }

Page 52: Java 7 New Features

Server  package hello;

import javax.xml.ws.Endpoint; class Publish {

public static void main(String[] args) {

Endpoint.publish( "http://localhost:8080/circlefunctions", new CircleFunctions());

}

}

Page 53: Java 7 New Features

Generate  Stub  Files  

•  Generate  stub  files:  – wsgen –cp . hello.CircleFunctions

Page 54: Java 7 New Features
Page 55: Java 7 New Features

Java  6:  Rhino  

•  Framework  to  connect  to  Java  programs  to  scrip6ng-­‐language  interpreters.  

•  Rhino  JS  Engine  comes  with  Java  6  •  To  ability  to  run  JS  from  Java  and  JS  from  command  line  

•  Rhino  is  wrioen  in  Java  

Page 56: Java 7 New Features

Example  import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class Main { public static void main(String[] args) { ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); // Now we have a script engine instance that // can execute some JavaScript try { engine.eval("print('Hello')"); } catch (ScriptException ex) { ex.printStackTrace(); } } }

Page 57: Java 7 New Features

Java  6:  GUI  

•  Faster  Splash  Screens  – SplashScreen  class  – java -splash:java-logo.jpeg Main

•  System  tray  support  •  Wri8ng  of  Gif  -­‐  files  

Page 58: Java 7 New Features

Java  6:  DB  Support  

•  Java  6  comes  with  preinstalled  rela8onal  database,  Oracle  release  of  Apache  Derby  Project  

•  Java  DB  is  installed  automa8cally  as  part  of  the  Java  SE  Development  Kit  (JDK).  

•  For  a  Java  DB  installa8on,  set  the  DERBY_HOME  environment  variable  and  classpaths  

•  Two  modes:  Embedded  and  Server  

Page 59: Java 7 New Features

Derby  loca8on  

Page 60: Java 7 New Features

Derby  Path  Serngs  

Page 61: Java 7 New Features

Derby  System  Info  

Page 62: Java 7 New Features

Crea8ng  Database  

Page 63: Java 7 New Features

ij  

•  The  ij  is  an  interac8ve  scrip8ng  tool  •  Queries  against  a  Derby  database  •  Can  be  started  with  “ij”  if  in  path  

Page 64: Java 7 New Features
Page 65: Java 7 New Features

EXERCISE  1  

Page 66: Java 7 New Features

JAVA  7  NEW  FEATURES  

Page 67: Java 7 New Features

Overview  

•  Java  7  is  an  evolu6onary  update  •  In  overall  

– 1)  Small  language  changes  (Project  Coin)  – 2)  Updates  to  File  API  – 3)  Updates  to  virtual  machine,  invokedynamic  – 4)  Lot  of  smaller  updates  

Page 68: Java 7 New Features

Java  7:  Feature  changes  •  Virtual  Machine  

–  JSR  292:  JVM  support  for  dynamic  languages  •  Language  changes  

–  JSR  334:  Small  language  changes  (Project  Coin)  •  IO  

–  JSR  203:  New  file  I/O  library  •  I18n  

–  Unicode  6.0,  separate  user  locale  and  user-­‐interface  locale  •  Client  

–  Java  2D  and  Swing  updates  •  JDBC  

–  JDBC  4.1  (autoclosable)  •  Web  

–  Update  XML  stack  to  latest  version  

 

Page 69: Java 7 New Features

Java  Specifica8on  Request  (JSR)  

•  JSR  is  a  formal  document  that  describes  specifica8ons  and  technologies  for  Java  plavorm  

•  List  of  JSRs  – http://en.wikipedia.org/wiki/Java_Community_Process#List_of_JSRs

•  You  can  see  each  JSR  from  jcp.org  – http://jcp.org/en/jsr/detail?id=334 (project coin)

Page 70: Java 7 New Features

Tools  

•  Download  Java  SE  7  from  Oracle  – http://www.oracle.com/technetwork/java/javase/downloads/index.html

•  Full  support  from  Netbeans  7  and  Eclipse  3.7.1  •  If  you  need  to  compile  to  older  versions,  use  

– javac –source 6 –target 6 MyApp.java

Page 71: Java 7 New Features

PROJECT  COIN  (JSR  334)  

Page 72: Java 7 New Features

Project  Coin  

•  Adds  small  language  changes  to  Java  SE  7  •  Changes  are  

1.  Strings  in  switch  2.  Binary  integral  literals  and  underscores  in  

numeric  literals  3.  Mul8-­‐catch    4.  Improved  Type  Inference  for  Generic  Instance  

Crea8on  5.  try-­‐with-­‐resources  statement  

Page 73: Java 7 New Features

1.  Strings  in  switch  

•  Now  you  can  use  Strings  in  switch  statement  •  No  duplicate  labels  •  No  null  labels    

Page 74: Java 7 New Features

Example  

Page 75: Java 7 New Features

2.  Binary  integral  literals  and  underscores  in  numeric  literals  

•  Improve  readibility  – int billion = 1_000_000_000;

•  Binary  literals,  add  prefix  0b  to  number  – int one = 0b0000_0001;

Page 76: Java 7 New Features

Example  

Page 77: Java 7 New Features

3.  Mul8-­‐catch  

•  Defining  mul8ple  excep8ons  in  one  catch  block  

•  Use  |  (or)  as  separator  between  excep8on  types  

•  Simplify  excep6on  handling  

Page 78: Java 7 New Features

Example  

Page 79: Java 7 New Features

4.  Type  Inference  

•  For  collec8ons,  no  need  to  repeat  the  generic  typing  (diamond)  

– Map<String, String> coll = new HashMap<>();

Page 80: Java 7 New Features

5.  try-­‐with-­‐resources  statement  

•  When  you  open  a  stream,  you  must  close  it  •  If  done  correctly,  closing  of  the  stream  may  require  lot  of  coding…  

Page 81: Java 7 New Features
Page 82: Java 7 New Features

Java  7  to  the  rescue!  

Page 83: Java 7 New Features

How?  

•  Virtual  Machine  will  call  automa6cally  the  close  method  upon  exi8ng  the  try  block  (like  finally)  

•  The  resource  object  must  implement  AutoCloseable  interface  

•  The  interface  has  only  one  method:  close •  If  closing  causes  excep8on,  it’s  suppressed  (ignore).  Possible  to  get  it  using  getSuppressed()  method  

Page 84: Java 7 New Features

Java  7  API  

Page 85: Java 7 New Features

Exercise  2  

Page 86: Java 7 New Features

FILE  SYSTEM  

Page 87: Java 7 New Features

API  Updates  to  File  System  

•  java.io  and  java.nio  are  updated  •  Called  NIO.2  revision  •  New  classes  (java.nio):  

– Path  –  Locate  a  file  in  a  file  system  •  Paths – Convert  a  URI  to  Path  object  

– Files  –  Operate  on  files,  directories  and  other  types  of  files  

– FileVisitor  –  Traversing  files  in  a  tree    – WatchService  –  File  change  modifica8on  API  

Page 88: Java 7 New Features

java.nio.file.Path

•  Absolute  or  rela8ve  path,  refers  to  files  in  file  system.  •  Suppor+ng  API  to  java.io.File •  File  to  Path:  

–  File f = new File(”/foo/bar/file.txt”); –  Path p = f.toPath();

•  Path  to  File  –  File f2 = p.toFile();

•  Path  is  an  interface!  Instan8a8ng  using  either  File  or  or  Paths  class  –  Path p = Paths.get(“file.txt”);

Page 89: Java 7 New Features

Nio2:  Features  

•  Able  to  access  informa8on  about  the  path  •  Support  for  directory  watching  •  Improved  support  for  large  directories  

– No  hanging  or  out  of  memories  when  dealing  with  massive  directory  trees  

Page 90: Java 7 New Features

Demo:  Path  -­‐  class  

Page 91: Java 7 New Features

java.nio.file.Files

•  Features  – Copy  – Create  directories  – Create  files  – Create  links  – Use  of  the  “temp”  –  folder  – Delete  – Aoributes  –  Modified/Owner/Permission  – Read  /  Write  

Page 92: Java 7 New Features

java.nio.file.Files

•  Sta8c  methods  for  reading,  wri8ng  and  manipula8ng  files  and  directories  

•  Files  uses  Path  objects!  •  Methods  like  

– createFile(Path p, ..); – delete(Path p); – move(…) – write(Path p, byte [] b, ..) – readAllLines(Path p, Charset cs)

Page 93: Java 7 New Features

Example  

Page 94: Java 7 New Features

Example  

Page 95: Java 7 New Features

java.nio.file.FileVisitor

•  Recursively  visit  files  in  a  file  tree  –  Example:  delete  every  .class  file  in  a  tree  

•  Implement  a  class  that  implements  FileVisitor  interface  –  preVisitDirectory  –  postVisitDirectory  –  visitFile  –  visitFileFailed  

•  Or  extend  SimpleFileVisitor  that  has  default  behaviour  for  each  of  these  methods!  

Page 96: Java 7 New Features

Idea  

•  File  tree  traversal  completes  when  all  accessible  files  in  tree  has  been  visited  or  a  visit  returns  TERMINATE  

•  Symbolic  links  are  not  followed  by  this  method  by  default  

•  You  can  set  the  depth:  0  (only  star8ng  file)  to  MAX_VALUE  (all  levels)  

Page 97: Java 7 New Features

Traversing  the  Tree  

Page 98: Java 7 New Features

FileVisitor  

Page 99: Java 7 New Features
Page 100: Java 7 New Features
Page 101: Java 7 New Features

java.nio.file.WatchService

•  Monitor  directory  for  changes  •  Example:  text  editor  no8fies  if  someone  else  has  made  changes  to  your  document    –  (“The  following  files  were  changes  by  another  program”)  

•  Watch  Service  API  enables  you  to  register  a  directory  with  the  watch  service  

•  When  registering  tell  are  you  interested  in  file  crea8on,  file  dele8on  or  file  modifica8on!  

Page 102: Java 7 New Features

Steps  

•  Create  WatchService  “watcher”  for  the  file  system  •  Register  a  directory  with  the  watcher.  Specify  also  types  you  are  interested  in:  modify,  delete…  

•  Implement  infinite  loop  for  wai8ng  of  incoming  events.  When  event  occurs,  a  key  is  signaled  and  put  tuo  queue  

•  Retrieve  the  key,  obtain  file  name  from  the  key  •  Retrieve  a  event  from  the  key  and  process  as  needed  •  Reset  the  key  and  resume  wai8ng  for  events  •  Close  the  service  

Page 103: Java 7 New Features

Registering  

Page 104: Java 7 New Features

Polling  

Page 105: Java 7 New Features
Page 106: Java 7 New Features

Exercise  3  

Page 107: Java 7 New Features

SWING  ENHANCEMENTS  

Page 108: Java 7 New Features

Swing  Enhancements  

•  JLayer  •  Nimbus  Look  &  Feel  •  Shaped  and  Translucent  Windows  

Page 109: Java 7 New Features

JLayer  

•  JLayer  enables  you  to  draw  on  components  and  respond  to  component  events  without  modifying  the  underlying  component  directly  

•  So  you  add  a  layer  on  top  another  component  

Page 110: Java 7 New Features

Nimbus  

Page 111: Java 7 New Features

About  Nimbus  

•  Moved  to  standard  API  namespace:  javax.swing  

•  Cross-­‐plavorm  look  and  feel  •  Uses  2D  Vector  Graphics  •  Highly  Customizable  

Page 112: Java 7 New Features

Serng  Theme  

•  When  star8ng  – UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");

•  Amer  start  – 

UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");

–  SwingUtilities.updateComponentTreeUI(this);

Page 113: Java 7 New Features

Component  Sizes  

Page 114: Java 7 New Features

Changing  Color  Theme  

Page 115: Java 7 New Features

Replace  Default  Color  •  UIManager.put("nimbusBase", new Color(...)); •  UIManager.put("nimbusBlueGrey", new Color(...)); •  UIManager.put("control", new Color(...));

Page 116: Java 7 New Features

Translucent  Window  

Page 117: Java 7 New Features

GUIs  in  the  future..  Java  Swing?  

Page 118: Java 7 New Features

Java  FX  

•  JavaFX  is  the  next  step  in  the  evolu8on  of  Java  as  rich  client  plavorm  

•  XML-­‐based  markup  language  for  defining  user  interfaces.  

•  Mul8-­‐touch  support!  •  Visual  UI  Design  tool  •  Is  JavaFX  replacing  Swing?  Yes.  However,  it  takes  6me…  

Page 119: Java 7 New Features

Exercise  4  

Page 120: Java 7 New Features

INVOKEDYNAMIC  (JSR  292)  

Page 121: Java 7 New Features

Word  about  JVM  when  you  write  in  Java:     Object x; ... x.equals("hello");  this  is  compiled  into  something  like:     aload_1 ; push local variable 1 (i.e. 'x') onto stack ldc "hello" ; push the string "hello" onto stack ; invoke the equals method invokevirtual java/lang/Object/equals(Ljava/lang/Object;)Z ; the boolean result is now on the stack  

Page 122: Java 7 New Features

Method  Invica8on  in  JVM  

•  invokevirtual  –  dispatches  a  Java  Method    •  invokespecial  –  instance  ini3aliza3on  (constructor)  

•  invokeinterface  –  dispatches  a  method  declared  inside  interface  

•  invokestatic  –  calls  a  sta3c  method  •  invokedynamic  (new!)  

Page 123: Java 7 New Features

InvokeDynamic  

•  Possible  to  call  methods  that  were  not  known  compile  8me!  

•  You  can  use  API  to  use  bytecode  command  invokedynamic  

Page 124: Java 7 New Features

Example  

Page 125: Java 7 New Features

Determing  the  Method  in  run8me  

Page 126: Java 7 New Features

What  is  the  use?  

•  For  normal  coding,  rare  uses  •  Some  u8li8es  (reflec8on)  •  For  future:  Virtual  machine  supports  different  languages!  Scrip8ng  languages  

Page 127: Java 7 New Features

Exercise  5  

Page 128: Java 7 New Features

CONCURRENCY  UPDATES:        FORK/JOIN  

Page 129: Java 7 New Features

Fork  /  Join  

•  API  for  parallel,  divide  and  conquer  algorithm  •  Large  task,  split  into  two.  If  the  two  tasks  are  large  enough,  split  these  again…  con8nue  this  un8l  tasks  are  acceptable  size  

•  When  task  is  completed,  it’s  joined  with  the  other  task..  this  will  con8nue  un8l  one  task  is  returned  

Page 130: Java 7 New Features

Fork/Join  •  Fork/Join  framework  helps  take  advantage  of  mul6ple  processors  when  crea8ng  threading  

•  Designed  for  work  that  can  be  broken  into  smaller  pieces  recursively  

•  Meant  for  dividing  work  to  subparts,  executes  in  parallel,  then  joining  them  again.  

•  Idea:  – Worker  threads  in  thread  pool  (ForkJoinPool    -­‐  class)  – When  worker  thread  run  out  of  of  things  to  do,  the  worker  thread  can  steal  tasks  from  other  threads  that  are  s8ll  busy  (ForkJoinTask  –  class)  

Page 131: Java 7 New Features

Example  

•  Increment  array  values  by  one.  •  One  solu8on  

– Create  loop  from  0  –  array.length  and  increment  each  value.  Not  effec6ve  for  large  arrays!  

•  Another  solu8on  –  If  array  is  large,  split  the  array  into  two  (or  more)  and  increment  these  in  parallel  

– Processing  is  done  in  separate  CPUs  when  using  Fork/Join!    

Page 132: Java 7 New Features

Basic  Use:  ForkJoinTask if (my portion of the work is small enough) {

do the work directly

}

else {

split my work into independent pieces

invoke the the pieces (fork)

wait for the results (join)

compose result

}

Page 133: Java 7 New Features

Classes  

•  ForkJoinTasks  runs  in  ForkJoinPool •  Two  concrete  tasks  (subclasses  of  ForkJoinTask):  

•  RecursiveTask – Compute  method  returns  some  value.  

•  RecursiveAction •  Compute  method  doesn’t  return  a  value.  

•  ForkJoinPool – Manage  and  monitor  the  tasks.  

Page 134: Java 7 New Features

Example  

•  We  want  to  calculate  the  sum  of  array  –  {1,2,3,4,5}  =>  15  

•  This  can  be  done  using  fork/join.  •  Divide  the  array  to  pieces  and  calculate  the  sum  in  different  tasks.  

 

Page 135: Java 7 New Features

{10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30}

{10,11,12,13,14,15,16,17,18,19,20} {21,22,23,24,25,26,27,28,29,30}

{10,11,12,13,14,15} {16,17,18,19,20} {21,22,23,24,25} {26,27,28,29,30}

75 + 90 + 115 + 140

420

Page 136: Java 7 New Features

Start  the  Calcula8on  

Page 137: Java 7 New Features

Structure  of  the  SumTask  class SumTask extends RecursiveTask<Long> { private static final int THRESHOLD = 5000; private int [] array; private int start; private int end; public SumTask(int [] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public Long compute() {...} }

Page 138: Java 7 New Features

compute()  

Page 139: Java 7 New Features
Page 140: Java 7 New Features

Exercise  6  

Page 141: Java 7 New Features

VIRTUAL  MACHINE  UPDATES  

Page 142: Java 7 New Features

Virtual  Machine  Updates  

•  invokedynamic  •  New  garbage  collector  algorithm:  G1  

Page 143: Java 7 New Features

Garbage  Collector  

•  Garbage  collector  works  to  reclaim  areas  of  memory  within  an  applica8on  that  will  never  be  accessed  again  

•  Two  steps  – Which  objects  are  no  longer  referenced?  – Reclaim  memory  of  dead  objects  

Page 144: Java 7 New Features

GC  Algorithms  

•  Java  SE  main  algorithms  – Serial  collector  – Parallel  collector  – Concurrent-­‐mark-­‐sweep  collector  (CMS)  

•  And  now  a  new!  – G1  collector  

•  Plan  is  that  G1  will  replace  CMS  

Page 145: Java 7 New Features

Different  algorithms  

•  Serial  collector  – Uses  single  thread  to  perform  garbage  collec8on.  Best-­‐suited  for  singleprocessor  machines.  On  by  default.  

•  Parallel  collector  –  Is  Parallel  but  not  concurrent.  Pauses  threads  to  do  the  work!  

– For  apps  with  medium-­‐  or  large-­‐sized  data  sets  that  run  on  mul8processor  environments.  

Page 146: Java 7 New Features

Different  algorithms  •  CMS  

–  Is  parallel  and  par8ally  concurrent.  Pauses  some  threads  to  do  its  work.    

–  It  is  designed  for  applica8ons  with  medium-­‐  to  large-­‐sized  data  sets  for  which  response  6me  is  more  important  than  overall  throughput,  since  the  techniques  used  to  minimize  pauses  can  reduce  applica8on  performance  

•  G1  –  Is  parallel  and  mostly  concurrent.  Pauses  some  threads,  but  only  during  certain  phases  of  collec8on.  

–  Targeted  for  mul8-­‐processor  server  side  apps  with  large  memories  and  response  8me  is  important.  You  can  set  pause-­‐6mes.  

Page 147: Java 7 New Features

Serng  the  Algorithm  

java -XX:+UseSerialGC MyApp

java -XX:+UseParallelGC MyApp

java -XX:+UseConcMarkSweepGC MyApp

java -XX:+UseG1GC MyApp

Page 148: Java 7 New Features

JDBC  4.1  

Page 149: Java 7 New Features

JDBC  4.1  

1.   AutoClosable:  Connec8on,  ResultSet,  Statement  

2.   RowSet  1.1:  RowSetFactory  –  easy  crea8on  of  JdbcRowSet  

Page 150: Java 7 New Features

Automa8cally  Close  Resources  

•  Automa8cally  close:  – java.sql.Connection – java.sql.Statement – java.sql.ResultSet

Page 151: Java 7 New Features

import java.io.*;

import java.net.*;

import java.sql.*;

class MyJDBC {

public static void main(String [] args) {

String driver = "jstels.jdbc.csv.CsvDriver2";

String url = "jdbc:jstels:csv:./csvfiles";

try {

// Load and register the driver

Class.forName(driver);

} catch(ClassNotFoundException e) {

e.printStackTrace();

System.exit(0);

}

Page 152: Java 7 New Features

try(Connection conn = DriverManager.getConnection(url)) {

// Create a connection to the database

String sql = "SELECT * FROM products";

try (Statement stmt = conn.createStatement()) {

// ResultSet is automatically closed, when Statement is closed.

ResultSet rs = stmt.executeQuery(sql);

String prodid, desc;

// Iterate over the ResultSet using next()

while(rs.next()){

// Use the appropriate getter functions to access columns

prodid = rs.getString("PRODID");

desc = rs.getString("DESCRIPTION");

System.out.println(prodid + " " + desc);

}

}

} catch(SQLException e) {

e.printStackTrace();

}

}

}

Page 153: Java 7 New Features

Enhanced  ResultSet  

•  A  JdbcRowSet  object  is  an  enhanced  ResultSet  object.    

•  Main  uses  of  a  JdbcRowSet  object  is  to  make  a  ResultSet  object  scrollable  and  updatable  when  it  does  not  otherwise  have  those  capabili8es  

•  You  can  add  listeners:    –  addRowSetListener  

•  cursorMoved  •  rowChanged  •  rowSetChanged  

Page 154: Java 7 New Features

Java  7:  RowSet  1.1  

•  RowSetFactory  –  easy  crea8on  of  RowSet  Object  

•  Different  Row  sets  – FilteredRowSet  

•  Filters  number  of  rows  visible  in  RowSet  object,  work  only  with  data  that  is  relevant  

– CachedRowSet  •  Operates  without  being  connected  to  database  

Page 155: Java 7 New Features

RowSetFactory myRowSetFactory = null;

try {

// Java 7: Create instance of JdbcRowSet using RowSetFactory

myRowSetFactory = RowSetProvider.newFactory();

// Closing the JdbcRowSet

try (JdbcRowSet jdbcRs = myRowSetFactory.createJdbcRowSet()) {

jdbcRs.setUrl(url);

jdbcRs.setCommand("select * from products");

jdbcRs.execute();

jdbcRs.next();

System.out.println(jdbcRs.getString(1));

System.out.println(jdbcRs.getString(2));

jdbcRs.next();

System.out.println(jdbcRs.getString(1));

System.out.println(jdbcRs.getString(2));

jdbcRs.previous();

System.out.println(jdbcRs.getString(1));

System.out.println(jdbcRs.getString(2));

}

} catch(SQLException e) {

e.printStackTrace();

}

Page 156: Java 7 New Features

JAVA  8  

Page 157: Java 7 New Features
Page 158: Java 7 New Features

Some  of  Proposed  content  

•  Project  Jigsaw  •  Project  Lambda  •  JavaFX  3.0  •  Device  Support  

– Mul8-­‐touch,  Camera,  Loca8on,  Compass,  Accelerometer  

 

Page 159: Java 7 New Features

Jigsaw  •  Group  of  classes  and  resources  and  a  special  module-­‐info  file  that  declares  dependencies  

•  Module  is  a  collec8on  of  classes  with  a  name,  version  number  and  formal  descrip8on  of  it’s  rela8onship  with  other  modules.  

•  Most  important  rela8onship:  dependence  (requires)  

module com.greetings @ 0.1 { requires org.astro @ 1.2; // requires a specific version class com.greetings.Hello; }

Page 160: Java 7 New Features

Lambda  

•  Perhaps  the  most  important  language  change:  Lambda  expressions  

Page 161: Java 7 New Features

Mo8va8on  class ButtonHandler implements ActionListener {

public void actionPerformed(ActionEvent e) {

//do something

}

}

class UIBuilder {

public UIBuilder() {

button.addActionListener(new ButtonHandler());

}

}

Page 162: Java 7 New Features

Mo8va8on  class UIBuilder {

public UIBuilder() {

button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent event) {

//do something

}

}

}

}

We  must  create  instance  to  just  call  one  

method!  

Page 163: Java 7 New Features

Lambda  Expression!  class UIBuilder {

public UIBuilder() {

button.addActionListener(ActionEvent e -> // do something )

}

}

Page 164: Java 7 New Features

Lambda  Expressions  

•  Lambda  expressions  are  8ny  anonymous  methods  

•  The  syntax  –  (type  parameter)  -­‐>  func8on_body  

•  Example  –  (String  s1,  String  s2)  -­‐>  s1.length()  –  s2.length()  

Page 165: Java 7 New Features

Lambda  Expressions  

•  Lambda  expressions  are  8ny  anonymous  methods  •  The  syntax  

–  (type parameter) -> function_body •  Example  

–  (String s1, String s2) -> s1.length() – s2.length()

•  Example  –  List <String> list = Arrays.asList("looooong", "short", "tiny" );

–  Collections.sort(list, (String s1, String s2) -> s1.length() - s2.length());

Page 166: Java 7 New Features

Thank  you!