Se ha denunciado esta presentación.
Se está descargando tu SlideShare. ×
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Cargando en…3
×

Eche un vistazo a continuación

1 de 166 Anuncio

Más Contenido Relacionado

Presentaciones para usted (20)

Similares a Java 7 New Features (20)

Anuncio

Más de Jussi Pohjolainen (20)

Más reciente (20)

Anuncio

Java 7 New Features

  1. 1. Java  7  New  Features   Jussi  Pohjolainen  
  2. 2. 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  
  3. 3. Oracle Certified Associate, Java SE 7 Programmer (OCA) •  No  prequisi6es   •  Dura8on  140  min,  number  of  ques8ons  90,   passing  score  77%   •  Price  200  –  300  e  
  4. 4. 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  
  5. 5. 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  
  6. 6. OCP: Exam Topics •  Java  Class  Design   •  Java  File  I/O  (NIO.2)   •  Advanced  Class  Design   •  Building  Database   •  OO  Principles   Applica8ons  with  JDBC   •  Generics  and  Collec8on   •  Threads   •  String  processing   •  Concurrency   •  Excep8ons  and   •  Localiza8on   Asser8ons   •  Java  I/O  Fundamentals    
  7. 7. 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  
  8. 8. Upgrade  Exam  Topics   •  Language  Enhancements   •  Concurrency   –  Project  Coin   –  Atomic  variables,  locks,   •  Design  pa@erns   executors,  fork/join   –  Singleton,  composi8on,  DAO,   •  Localiza6on   factory   –  Locales,  resource  bundles   •  Database  Applica6ons  with  JDBC   •  Java  File  I/O  (NIO.2)   –  JDBC  API:  RowSetProvider,   –  Path  and  Files  -­‐  classes   RowSetFactory,  new  RowSet   interfaces  
  9. 9. (RECAP)  JAVA  5  AND  6  
  10. 10. 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)   …  
  11. 11. New  Features   •  Java  SE  5   –  Generics   –  Autoboxing   –  Improved  looping  syntax   –  Annota8ons   –  …   •  Java  SE  6   –  XML  Processing  and  Web  Services   –  Scrip8ng   –  JDBC  4.0   –  …    
  12. 12. 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()); }
  13. 13. Result  
  14. 14. 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()); }
  15. 15. Result  
  16. 16. 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); }
  17. 17. 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()); } }
  18. 18. 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()); } }
  19. 19. Java  1.4:  Lot  of  Coding   Integer a = new Integer(5); Integer b = new Integer(6); int aPrimitive = a.intValue(); Int bPrimitive = b.intValue();
  20. 20. Autoboxing  Comes  to  Rescue!   class Main { public static void main(String [] args) { // Boxing Integer a = 2; // UnBoxing int s = 5 + a; } }
  21. 21. 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()); } }
  22. 22. 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); } } }
  23. 23. for-­‐each  
  24. 24. 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; }
  25. 25. 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); }
  26. 26. 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  
  27. 27. 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); } } }
  28. 28. 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); } }
  29. 29. 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()); } }
  30. 30. 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"); } }
  31. 31. 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"); } }
  32. 32. 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  
  33. 33. 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.      
  34. 34. Example   @Override public void method() { … }
  35. 35. Example   @Author( name = ”Jussi Pohjolainen", ) class MyClass() { … }
  36. 36. Example   @Author(”Jussi Pohjolainen”) class MyClass() { … }
  37. 37. Example   @Author( name = ”Jussi Pohjolainen", date = ”2012-09-12" ) class MyClass() { … }
  38. 38. 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 { }
  39. 39. Javadoc  
  40. 40. 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 { }
  41. 41. Javadoc  now  
  42. 42. Targets   // Annotation type import java.lang.annotation.*; @Target(ElementType.METHOD) @interface Something { String foo(); } class Foo { @Something(foo = "hello") public void method() { } }
  43. 43. 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(); } }
  44. 44. Other  Annota8ons  used  By  Compiler   •  @Depricated –  Gives  warning  if  when   depricated  method  or  class  is  used   •  @SuppressWarnings –  Suppress  all  warnings   that  would  normally  generate  
  45. 45. 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); } }
  46. 46. 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); } }
  47. 47. User  Input:  Scanner   Scanner in = new Scanner(System.in); int a = in.nextInt(); String b = in.nextLine();
  48. 48. Java  6:  XML  &  Web  Services   •  Easy  way  of  crea8ng  Web  Services   •  Expose  web  service  with  a  simple  annota8on    
  49. 49. 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; } }
  50. 50. Server   package hello; import javax.xml.ws.Endpoint; class Publish { public static void main(String[] args) { Endpoint.publish( "http://localhost:8080/circlefunctions", new CircleFunctions()); } }
  51. 51. Generate  Stub  Files   •  Generate  stub  files:   –  wsgen –cp . hello.CircleFunctions
  52. 52. 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  
  53. 53. 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(); } } }
  54. 54. Java  6:  GUI   •  Faster  Splash  Screens   –  SplashScreen  class   –  java -splash:java-logo.jpeg Main •  System  tray  support   •  Wri8ng  of  Gif  -­‐  files  
  55. 55. 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  
  56. 56. Derby  loca8on  
  57. 57. Derby  Path  Serngs  
  58. 58. Derby  System  Info  
  59. 59. Crea8ng  Database  
  60. 60. ij   •  The  ij  is  an  interac8ve  scrip8ng  tool   •  Queries  against  a  Derby  database   •  Can  be  started  with  “ij”  if  in  path  
  61. 61. EXERCISE  1  
  62. 62. JAVA  7  NEW  FEATURES  
  63. 63. 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  
  64. 64. 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    
  65. 65. 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)
  66. 66. 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
  67. 67. PROJECT  COIN  (JSR  334)  
  68. 68. 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  
  69. 69. 1.  Strings  in  switch   •  Now  you  can  use  Strings  in  switch  statement   •  No  duplicate  labels   •  No  null  labels    
  70. 70. Example  
  71. 71. 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;
  72. 72. Example  
  73. 73. 3.  Mul8-­‐catch   •  Defining  mul8ple  excep8ons  in  one  catch   block   •  Use  |  (or)  as  separator  between  excep8on   types   •  Simplify  excep6on  handling  
  74. 74. Example  
  75. 75. 4.  Type  Inference   •  For  collec8ons,  no  need  to  repeat  the  generic   typing  (diamond)   –  Map<String, String> coll = new HashMap<>();
  76. 76. 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…  
  77. 77. Java  7  to  the  rescue!  
  78. 78. 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  
  79. 79. Java  7  API  
  80. 80. Exercise  2  
  81. 81. FILE  SYSTEM  
  82. 82. 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  
  83. 83. 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”);
  84. 84. 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  
  85. 85. Demo:  Path  -­‐  class  
  86. 86. java.nio.file.Files •  Features   –  Copy   –  Create  directories   –  Create  files   –  Create  links   –  Use  of  the  “temp”  –  folder   –  Delete   –  Aoributes  –  Modified/Owner/Permission   –  Read  /  Write  
  87. 87. 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)
  88. 88. Example  
  89. 89. Example  
  90. 90. 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!  
  91. 91. 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)  
  92. 92. Traversing  the  Tree  
  93. 93. FileVisitor  
  94. 94. 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!  
  95. 95. 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  
  96. 96. Registering  
  97. 97. Polling  
  98. 98. Exercise  3  
  99. 99. SWING  ENHANCEMENTS  
  100. 100. Swing  Enhancements   •  JLayer   •  Nimbus  Look  &  Feel   •  Shaped  and  Translucent  Windows  
  101. 101. 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  
  102. 102. Nimbus  
  103. 103. About  Nimbus   •  Moved  to  standard  API  namespace:   javax.swing   •  Cross-­‐plavorm  look  and  feel   •  Uses  2D  Vector  Graphics   •  Highly  Customizable  
  104. 104. Serng  Theme   •  When  star8ng   –  UIManager.setLookAndFeel("javax.swing.plaf.nimb us.NimbusLookAndFeel"); •  Amer  start   –  UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusL ookAndFeel"); –  SwingUtilities.updateComponentTreeUI(this);
  105. 105. Component  Sizes  
  106. 106. Changing  Color  Theme  
  107. 107. Replace  Default  Color   •  UIManager.put("nimbusBase", new Color(...)); •  UIManager.put("nimbusBlueGrey", new Color(...)); •  UIManager.put("control", new Color(...));
  108. 108. Translucent  Window  
  109. 109. GUIs  in  the  future..  Java  Swing?  
  110. 110. 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…  
  111. 111. Exercise  4  
  112. 112. INVOKEDYNAMIC  (JSR  292)  
  113. 113. 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  
  114. 114. 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!)  
  115. 115. InvokeDynamic   •  Possible  to  call  methods  that  were  not  known   compile  8me!   •  You  can  use  API  to  use  bytecode  command   invokedynamic  
  116. 116. Example  
  117. 117. Determing  the  Method  in  run8me  
  118. 118. What  is  the  use?   •  For  normal  coding,  rare  uses   •  Some  u8li8es  (reflec8on)   •  For  future:  Virtual  machine  supports  different   languages!  Scrip8ng  languages  
  119. 119. Exercise  5  
  120. 120. CONCURRENCY  UPDATES:        FORK/JOIN  
  121. 121. 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  
  122. 122. 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)  
  123. 123. 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!    
  124. 124. 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 }
  125. 125. 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.  
  126. 126. 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.    
  127. 127. {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
  128. 128. Start  the  Calcula8on  
  129. 129. 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() {...} }
  130. 130. compute()  
  131. 131. Exercise  6  
  132. 132. VIRTUAL  MACHINE  UPDATES  
  133. 133. Virtual  Machine  Updates   •  invokedynamic   •  New  garbage  collector  algorithm:  G1  
  134. 134. 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  
  135. 135. 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  
  136. 136. 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.  
  137. 137. 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.  
  138. 138. Serng  the  Algorithm   java -XX:+UseSerialGC MyApp java -XX:+UseParallelGC MyApp java -XX:+UseConcMarkSweepGC MyApp java -XX:+UseG1GC MyApp
  139. 139. JDBC  4.1  
  140. 140. JDBC  4.1   1.  AutoClosable:  Connec8on,  ResultSet,   Statement   2.  RowSet  1.1:  RowSetFactory  –  easy  crea8on  of   JdbcRowSet  
  141. 141. Automa8cally  Close  Resources   •  Automa8cally  close:   –  java.sql.Connection –  java.sql.Statement –  java.sql.ResultSet
  142. 142. 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); }
  143. 143. 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(); } } }
  144. 144. 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  
  145. 145. 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  
  146. 146. 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(); }
  147. 147. JAVA  8  
  148. 148. Some  of  Proposed  content   •  Project  Jigsaw   •  Project  Lambda   •  JavaFX  3.0   •  Device  Support   –  Mul8-­‐touch,  Camera,  Loca8on,  Compass,   Accelerometer    
  149. 149. 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; }
  150. 150. Lambda   •  Perhaps  the  most  important  language  change:   Lambda  expressions  
  151. 151. Mo8va8on   class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { //do something } } class UIBuilder { public UIBuilder() { button.addActionListener(new ButtonHandler()); } }
  152. 152. 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!  
  153. 153. Lambda  Expression!   class UIBuilder { public UIBuilder() { button.addActionListener(ActionEvent e -> // do something ) } }
  154. 154. Lambda  Expressions   •  Lambda  expressions  are  8ny  anonymous   methods   •  The  syntax   –  (type  parameter)  -­‐>  func8on_body   •  Example   –  (String  s1,  String  s2)  -­‐>  s1.length()  –  s2.length()  
  155. 155. 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());
  156. 156. Thank  you!  

×