Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov


Published on

Published in: Engineering, Technology, Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • The invokevirtual part of the instruction is the one-byte operation code. The remainder of the instruction, #4, is the two-byte operand, which provides information about the method call in an abstract way. The operand refers to an entry in a pool of constants.
  • Type profile pollution in short – the VM says I don’t know what type I gonna see here.. I already saw 1001 of them … so I am gonna fallback full virtual dispatch instead of inline or caching and etc.
    @Brian Goetz
  • All four of the newly introduced “xxxxxExact()” methods throw an ArithmeticException if the number contained in the BigInteger instance cannot be provided in the specified form without looss of information.  BigInteger already had methods intValue() andlongValue() as well as inherited (from Number) methods shortValue() and byteValue()
  • Is it correct ? Is it ok ? .. Lets start eclipse. The idea here is that it makes you think.. But what about if no such number is found you got a bug since it prints 0 … as 0 is the first even number greater then 3 multiplied by 2…
  • You will notice it says Optional[8] so this is even a HINT hey.. this can be a null man… NOTE: you can extract the checks inside a methods that says isEven() and so on to be really easy to read and understand
  • Yes.. It has issues…you can read more here http://java.dzone.com/articles/optional-will-remain-option?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+javalobby%2Ffrontpage+%28Javalobby+%2F+Java+Zone%29
  • java.time
    The core of the API for representing date and time. It includes classes for date, time, date and time combined, time zones, instants, duration, and clocks. These classes are based on the calendar system defined in ISO-8601, and are immutable and thread-safe.
    The API for representing calendar systems other than the default ISO-8601. You can also define your own calendar system. This tutorial does not cover this package in any detail.
    Classes for formatting and parsing dates and times.
    Extended API, primarily for framework and library writers, allowing interoperations between the date and time classes, querying, and adjustment. Fields (TemporalField and ChronoField) and units (TemporalUnit and ChronoUnit) are defined in this package.
    Classes that support time zones, offsets from time zones, and time zone rules. If working with time zones, most developers will need to use only ZonedDateTime, and ZoneId or ZoneOffset.
  • * Seconds are captured to nanosecond precision.
    ** This class does not store this information, but has methods to provide time in these units.
    *** When a Period is added to a ZonedDateTime, daylight saving time or other local time differences are observed.
  • * Seconds are captured to nanosecond precision.
    ** This class does not store this information, but has methods to provide time in these units.
    *** When a Period is added to a ZonedDateTime, daylight saving time or other local time differences are observed.
  • Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov

    1. 1. TRADER.BG®
    2. 2. Bulgarian Java user group • http://java-bg.org • http://groups.google.com/group/bg-jug
    3. 3. Agenda • Java 7 yes.. 7 • Java 8 – Static methods on interfaces – Lamdas? – Exact Numeric Operations – Type Annotations – Optional – Date and Time – Nashorn
    4. 4. Java 7 • We all know about diamond operator right? – List<Integer> primes = new ArrayList<>(); • And Strings in switch • And Fork Join Framework • And Underscore in Numeric literals – int billion = 1_000_000_000; // 10^9 • And maybe catching Multiple Exception Type in Single Catch Block – catch(ClassNotFoundException|SQLException ex) • Binary Literals with prefix "0b“ – int binary = 0B0101_0000_1010_0010_1101_0000_1010_0010; • G1 Garbage Collector • And we all know about Automatic Resource Management
    5. 5. • But do we all know that we can use it with multiple resources try (PrintWriter catalogWriter = new PrintWriter( new FileOutputStream(new File("d:/temp/catalog.csv"))); PrintWriter mediaWriter = new PrintWriter( new FileOutputStream(new File("d:/temp/media.csv")))) { … }
    6. 6. And do you know about the “More Precise Rethrowing of Exception” • In Java version *.. yes we all know this is BAD public void obscure() throws Exception { try { new FileInputStream("abc.txt").read(); new SimpleDateFormat("ddMMyyyy").parse("12-03- 2014"); } catch (Exception ex) { System.out.println("Caught exception: " + ex.getMessage()); throw ex; } }
    7. 7. Java 7+ public void precise() throws ParseException, IOException { try { new FileInputStream("abc.txt").read(); new SimpleDateFormat("ddMMyyyy").parse("12-03- 2014"); } catch (Exception ex) { System.out.println("Caught exception: " + ex.getMessage()); throw ex; } } … try { test.precise(); } catch (ParseException | IOException e) { e.printStackTrace(); }
    8. 8. The biggest two additions to Java 7 are.. ?
    9. 9. The biggest two additions to Java 7 are.. ? • 1) MethodHandle Method handles gives us unrestricted capabilities for calling non-public methods. Compared to using the Reflection API, access checking is performed when the method handle is created as opposed to every time the method is called.
    10. 10. With reflection Class<?>[] argTypes = new Class[] { int.class, String.class }; Method meth = MethodAccessExampleWithArgs.class. getDeclaredMethod("bar", argTypes); meth.setAccessible(true); meth.invoke(isntance, 7, "Boba Fett");
    11. 11. With MethodHandle MethodType desc = MethodType.methodType(void.class, int.class, String.class); MethodHandle mh = MethodHandles.lookup().findVirtual(MethodAccessEx ampleWithArgs.class, "bar", desc); mh.invokeExact(mh0, 42, "R2D2");
    12. 12. And the second BIG addition to Java 7 is.. ? • 2) invokedynamic The culmination of invokedynamic is, of course, the ability to make a dynamic call that the JVM not only recognizes, but also optimizes in the same way it optimizes plain old static-typed calls.
    13. 13. What we all know? Before Java7 there were 4 bytecodes for method invocation • invokevirtual - Invokes a method on a class. • invokeinterface - Invokes a method on an interface. • invokestatic - Invokes a static method on a class. • invokespecial - Everything else called this way can be constructors, superclass methods, or private methods.
    14. 14. How invokedynamic look ? invokevirtual #4 //Method java/io/PrintStream.println:(Ljava/lang/St ring;)V invokedynamic #10 //NameAndTypelessThan:(Ljava/lang/Object;L java/lang/Object;) But wait. How does the JVM find the method if the receiver type isn't supplied? When the JVM sees an invokedynamic bytecode, it uses the new linkage mechanism to get to the method it needs.
    15. 15. How this works Well … it uses a puzzle of 3 parts: • AnonymousClassLoading provides a piece of that puzzle, making it easy to generate lightweight bits of code suitable for use as adapters and method handles. • MethodHandle provides another piece of that puzzle, serving as a direct method reference, allowing fast invocation, argument list manipulation, and functional composability. • The last piece of the puzzle, and probably the coolest one of all, is the bootstrapper. (and we will speak about all that a bit later  (~15 slides))
    16. 16. Anyway enough Java 7.. Java 8
    17. 17. And Java 8 is all about Lambdas right?
    18. 18. Yes.. but before the refresh on lambdas: Static methods on interfaces • You can declare static methods on interfaces: public interface ContentFormatter { public void format(); static String convertRegex(String regex) { ... } }
    19. 19. Yes.. but before the refresh on lambdas: Static methods on interfaces • You can declare static methods on interfaces: public interface ContentFormatter { public void format(); static String convertRegex(String regex) { ... } } • None of the implementing classes will have this method available to them • The idea : less utility classes.. We all have CollectionUtils right?
    20. 20. So..Lambdas… I see Lambdas everywhere… • Lambdas bring anonymous function types in Java (JSR 335): • Example: (x,y) -> x + y (parameters) -> {body}
    21. 21. Lambdas refresh • Lambdas can be used in place of functional interfaces (interfaces with just one method such as Runnable) • Example: new Thread(new Runnable() { @Override public void run() { System.out.println("It runs!"); } } ).start(); new Thread(() -> System.out.println("It runs!") ).start();
    22. 22. @FunctionalInterface(s) some notes @FunctionalInterface interface Test { public void doSomething(); }
    23. 23. This is NOT @FunctionalInterface @FunctionalInterface interface Test2 { public default void doSomething() {} }
    24. 24. This are valid @FunctionalInterface(s) @FunctionalInterface interface Test3 { public void doSomething(); public default void doSomethingDefault() {} } @FunctionalInterface interface Test4 { public void doSomething(); public static void doSomethingDefault() {} }
    25. 25. This look like a valid @FunctionalInterface but is NOT and can NOT be used as Lambda @FunctionalInterface interface Test5 { public <T> T doSomething(); } Lets suppose you have a method like this public static void something(Test5 t){ System.out.println(t.doSomething()); }
    26. 26. This is Invalid : something(() -> "cant do"); With Anonymous class.. (ugly one but is valid)… and with unchecked cast warning  (cuz of cast to Object WTF…) something(new Test5() { @Override public <T> T doSomething() { return (T) "hello"; } });
    27. 27. So use generic classes.. @FunctionalInterface @FunctionalInterface interface Test6<T> { public T doSomething(); }
    28. 28. And of course you can then consume and use this like that something(new Test6<Integer>() { @Override public Integer doSomething() { return 5; } }); //or something(() -> 5);
    29. 29. 2 notes about putting Lambdas on an API • Lets assume we had the following method pre Java 8 public static void doIt(Integer a){} • Let assume now.. That we want this integer to be fetched lazy or via some method internally so we may add another method like this: public static void doIt(Callable<Integer> a){ } So far so good.
    30. 30. However pre Java 8 we had a chance to do this for the next API version: public static void doIt(Integer a){ } public static void doIt(String a){ } But now .. we cant add this: public static void doIt (Callable<Integer> a){ } public static void doIt (Callable<String> a){ } Because the generics are removed and this two methods became the same so we got duplicated method. So this is something we need to think about.
    31. 31. And also lets say we had only one method with one generic type but we want to use another interface • So we had: public static void doIt(Callable<Integer> a){ } and we may add public static void doIt(Supplier<Integer> a){ } And that’s look fine… to us.
    32. 32. However when we want to call this and type : doIt(() -> 5); Now we (in fact all clients that used our API) get ambigous method. And the only workaround for them is to change their code to something like : doIt((Callable<Integer>)() -> 5) ; Which is… if first ugly and second it require manual change(s) in the client code.
    33. 33. Lets continue with Lambdas black magic
    34. 34. Lambdas are NOT Anonymous classes
    35. 35. What, why … so not just syntax sugar ? • Nope… if they were… we would have 1000 (one class per lambda) classes generated, visible and loaded each time – no meter invoked or not invoked in the current run. • It creates complicated lookup and “type profile pollution” • The worst is that the first version Java compiler emits will mean this will stay like that FOREVER
    36. 36. How lambdas magic work in few steps? • Desugaring lambda to a method (static or instance) • invokedynamic is used in the bytecode • Bootstrap method is called which is simply a piece of code that the JVM can call when it encounters a dynamic invocation. It has all the information about the call directly from the JVM itself. • Bootstrap uses different translation strategies for example MethodHandle to call right method, or code generatation of an inner class . Currently it uses “lambda metafactory” where it passes the interface+the desugared method like lambda$1 which returns an instance of the interface.
    37. 37. How this instance of an interface is returned is up 2 the VM implementation • Metafactory can spin inner classes dynamically. So generating the same class that the compiler should but runtime • Metafactory can create one wrapper class per instance type ( So one for Predicate, one for Runnable so on )- constructor takes method handle, methods just invoke the method handle • Dynamic proxies • OR private VM APIs
    38. 38. Some performance tests pre-pre-pre release (~2013) Single threaded Saturated Inner class 160 1407 Non capturing lambdas 636 23201 Capturing lambdas 170 1400 Operations per microsecond
    39. 39. No more lambdas… today ! topic.next() -Exact Numeric Operations • Java 8 has added several new “exact” methods to the Math class(and not only) protecting sensitive code from implicit overflows int safeC = Math.multiplyExact(bigA, bigB); // will throw ArithmeticException if result exceeds +-2^31
    40. 40. BigInteger & BigDecimal 4 new methods added to BigInteger class (also to BigDecimal) longValueExact(), intValueExact(), shortValueExact(), and byteValueExact(). and toBigIntegerExact() for BigDecimal All of the newly introduced “xxxxxExact()” methods throw an ArithmeticException if the number contained in the BigInteger instance cannot be provided in the specified form without loss of information
    41. 41. Annotations? Not your java 5 Annotations!
    42. 42. Annotations in Java 5/6/7 • Annotations on class declarations @Stateless public class Person
    43. 43. Annotations in Java 5/6/7 • Annotations on class declarations @Stateless public class Person • Annotations on method declarations @Override public String toString() {
    44. 44. Annotations in Java 5/6/7 • Annotations on class declarations @Stateless public class Person • Annotations on method declarations @Override public String toString() { • Annotations on class fields @PersistenceContext private EntityManager em;
    45. 45. Annotations in Java 5/6/7 • Annotations on class declarations @Stateless public class Person • Annotations on method declarations @Override public String toString() { • Annotations on class fields @PersistenceContext private EntityManager em; • Annotations on method parameters public Person getPersonByName(@PathParam("name") String name) {
    46. 46. New in Java 8 You can put annotations anywhere a type is specified: public void sayHello() { @Encrypted String data; List<@NonNull String> strings; HashMap names = (@Immutable HashMap) map; }
    47. 47. Declaring type annotations @Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE}) @Retention(RetentionPolicy.RUNTIME) public @interface Encrypted { } The enum value TYPE_PARAMETER allows an annotation to be applied at type variables (e.g. MyClass<T>). Annotations with target TYPE_USE can be applied at any type use.
    48. 48. Gotchas • Nobody will stop you doing bad things: public void passPassword(@Encrypted String pwd) {} public void hello() { @PlainText String myPass = "foo"; passPassword(myPass); } • The code above will compile, run… and …crash
    49. 49. • You can’t override methods based on annotations: interface Test { public void sayHello(@NotNull String notNull); public void sayHelloNullable(String canNull); } class TestImpl implements Test { @Override public void sayHello(String notNull) { // TODO Auto-generated method stub } @Override public void sayHelloNullable(@NotNull String notNull) { // TODO Auto-generated method stub } }
    50. 50. Examples: List<@ReadOnly @Localized Message> messages; Map<@NonNull String, @NonEmpty List<@Readonly Document>> documents; class MyClass{ private List<@Email String> emailAddresses; }
    51. 51. How to access this annotation? // get the email field Field emailAddressField = MyClass.class.getDeclaredField("emailAddresses"); // the field's type is both parameterized and annotated, // cast it to the right type representation AnnotatedParameterizedType annotatedParameterizedType = (AnnotatedParameterizedType) emailAddressField.getAnnotatedType(); // get all type parameters AnnotatedType[] annotatedActualTypeArguments = annotatedParameterizedType.getAnnotatedActualTypeArguments(); // the String parameter which contains the annotation AnnotatedType stringParameterType = annotatedActualTypeArguments[0]; // The actual annotation Annotation emailAnnotation = stringParameterType.getAnnotations()[0]; System.out.println(emailAnnotation); // @Email()
    52. 52. Method parameter names • Before Java 8, only parameter positions and types were preserved after compilation • In Java 8 you can have those in the .class files • They are not available by default – Need to enable it with -parameters option to javac
    53. 53. Getting parameter names public static List<String> getParameterNames(Method method) { Parameter[] parameters = method.getParameters(); List<String> parameterNames = new ArrayList<>(); for (Parameter parameter : parameters) { if(!parameter.isNamePresent()) { throw new IllegalArgumentException("Parameter names are not present!"); } String parameterName = parameter.getName(); parameterNames.add(parameterName); } return parameterNames; }
    54. 54. StringJoiner • StringJoiner is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.
    55. 55. In Java 8 Example The String "[George:Sally:Fred]" may be constructed as follows: StringJoiner sj = new StringJoiner(":", "[", "]"); sj.add("George").add("Sally").add("Fred"); String desiredString = sj.toString();
    56. 56. Used internally in multiple places List<String> cloudGroups = new ArrayList<>(); cloudGroups.add("Cirrus"); cloudGroups.add("Alto"); cloudGroups.add("Stratus"); cloudGroups.add("Vertical Growth"); cloudGroups.add("Special Clouds"); String cloudGroupsJoined = String.join("," ,cloudGroups);
    57. 57. List<String> cloudGroups = new ArrayList<>(); cloudGroups.add("Cirrus"); cloudGroups.add("Alto"); cloudGroups.add(null); cloudGroups.add("Special Clouds"); cloudGroups.add(null); String cloudGroupsJoined = cloudGroups.stream() .filter(Objects::nonNull).collect(Collectors.jo ining(","));
    58. 58. Base64 encode/decode // Encode String asB64 = Base64.getEncoder().encodeToString("some string".getBytes("utf-8")); System.out.println(asB64); // Output will be: c29tZSBzdHJpbmc= // Decode byte[] asBytes = Base64.getDecoder().decode("c29tZSBzdHJpbmc="); System.out.println(new String(asBytes, "utf- 8")); // And the output is: some string
    59. 59. Optional The main point behind Optional is to wrap an Object and to provide convenience API to handle nullability in a fluent manner. Optional<String> stringOrNot = Optional.of("123"); //This String reference will never be null String alwaysAString = stringOrNot.orElse("");
    60. 60. But lets first see a nice example by Venkat Subramaniam • Task is : Double the first even number greater than 3 Having as example List<Integer> values = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
    61. 61. Old way int result = 0; for(int e : values){ if(e > 3 && e% 2 == 0) { result = e * 2; break; } } System.out.println(result); Is it correct ? Is it ok ? .. Lets start eclipse
    62. 62. Ecilpse demo So the new way : System.out.println( values.stream() .filter(value -> value >3) .filter(value -> value % 2 == 0) .map(value -> value * 2) .findFirst() ); Lets read it, cant be that hard? But lets start it in eclipse.
    63. 63. So in summary Optional is heavily used in streaming API …! And you should think how to use it ….TODAY! // This Integer reference will be wrapped again Optional<Integer> integerOrNot = stringOrNot.map(Integer::parseInt); // This int reference will never be null int alwaysAnInt = stringOrNot .map(s -> Integer.parseInt(s)) .orElse(0); Arrays.asList(1, 2, 3) .stream() .findAny() .ifPresent(System.out::println); More at : http://java.dzone.com/articles/optional-will-remain-option
    64. 64. Date and Time API • The Date-Time API was developed using several design principles. – Clear: The methods in the API are well defined and their behavior is clear and expected. For example, invoking a method with a null parameter value typically triggers a NullPointerException. – Fluent. Because most methods do not allow parameters with a null value and do not return a null value, method calls can be chained together and the resulting code can be quickly understood. – Immutable
    65. 65. • The Date-Time API consists of the primary package, java.time, and four subpackages: • java.time • java.time.chrono • java.time.format • java.time.temporal • java.time.zone
    66. 66. Hint for the next slide * Seconds are captured to nanosecond precision. **This class does not store this information, but has methods to provide time in these units. *** When a Period is added to a ZonedDateTime, daylight saving time or other local time differences are observed.
    67. 67. Overview Class or Enum Year Mon th Day Hou rs Minu tes Secon ds* Zone Offset Zone ID toString Output Instant X 2013-08- 20T15:16:26.3 55Z LocalDate X X X 2013-08-20 LocalDateT ime X X X X X X 2013-08- 20T08:16:26.9 37 ZonedDate Time X X X X X X X X 2013-08- 21T00:16:26.9 41+09:00[Asia /Tokyo] LocalTime X X X 08:16:26.943 MonthDay X X --08-20
    68. 68. Overview Class or Enum Year Mon th Day Hou rs Minu tes Seco nds* Zone Offset Zone ID toString Output Year X 2013 YearMont h X X 2013-08 Month X AUGUST OffsetDate Time X X X X X X X 2013-08- 20T08:16:26.9 54-07:00 OffsetTime X X X X 08:16:26.957- 07:00 Duration ** ** ** X PT20H (20 hours) Period X X X *** *** P10D (10 days)
    69. 69. Method Naming Conventions in Date&Time API Prefix Method Type Use of static factory Creates an instance where the factory is primarily validating the input parameters, not converting them. from static factory Converts the input parameters to an instance of the target class, which may involve losing information from the input. parse static factory Parses the input string to produce an instance of the target class. format instance Uses the specified formatter to format the values in the temporal object to produce a string. get instance Returns a part of the state of the target object. is instance Queries the state of the target object. with instance Returns a copy of the target object with one element changed; this is the immutable equivalent to a set method on a JavaBean. plus instance Returns a copy of the target object with an amount of time added. minus instance Returns a copy of the target object with an amount of time subtracted. to instance Converts this object to another type. at instance Combines this object with another.
    70. 70. Month Month month = Month.AUGUST; Locale locale = Locale.getDefault(); System.out.println(month.getDisplayName( TextStyle.FULL, locale)); System.out.println(month.getDisplayName( TextStyle.NARROW, locale)); System.out.println(month.getDisplayName( TextStyle.SHORT, locale)); //August /A //Aug
    71. 71. LocalDate LocalDate date = LocalDate.of(2000, Month.NOVEMBER, 20); DayOfWeek dotw = LocalDate.of(2012, Month.JULY, 9).getDayOfWeek(); LocalDate date = LocalDate.of(2000, Month.NOVEMBER, 20); TemporalAdjuster adj = TemporalAdjusters.next(DayOfWeek.WEDNESDAY); LocalDate nextWed = date.with(adj); System.out.printf("For the date of %s, the next Wednesday is %s.%n",date, nextWed); //For the date of 2000-11-20, the next Wednesday is 2000-11-22.
    72. 72. MonthDay & Year MonthDay date = MonthDay.of(Month.FEBRUARY, 29); boolean validLeapYear = date.isValidYear(2010); boolean validLeapYear = Year.of(2012).isLeap();
    73. 73. LocalTime LocalTime thisSec = LocalTime.now(); someMethod(thisSec.getHour(), thisSec.getMinute(), thisSec.getSecond());
    74. 74. LocalDateTime System.out.printf("now: %s%n", LocalDateTime.now()); System.out.printf("Apr 15, 1994 @ 11:30am: %s%n", LocalDateTime.of(1994, Month.APRIL, 15, 11, 30)); System.out.printf("now (from Instant): %s%n", LocalDateTime.ofInstant(Instant.now(), ZoneId.systemDefault())); System.out.printf("6 months from now: %s%n", LocalDateTime.now().plusMonths(6)); System.out.printf("6 months ago: %s%n", LocalDateTime.now().minusMonths(6)); now: 2013-07-24T17:13:59.985 Apr 15, 1994 @ 11:30am: 1994-04-15T11:30 now (from Instant): 2013-07-24T17:14:00.479 6 months from now: 2014-01-24T17:14:00.480 6 months ago: 2013-01-24T17:14:00.481
    75. 75. Time Zone and Offset Classes • ZoneId specifies a time zone identifier and provides rules for converting between an Instant and a LocalDateTime. • ZoneOffset specifies a time zone offset from Greenwich/UTC time.
    76. 76. Example Set<String> allZones = new TreeSet<String>(ZoneId.getAvailableZoneIds ()); LocalDateTime dt = LocalDateTime.now(); for (String s : allZones) { ZoneId zone = ZoneId.of(s); ZonedDateTime zdt = dt.atZone(zone); ZoneOffset offset = zdt.getOffset(); System.out.printf(String.format("%35s %10s%n", zone, offset)); … Europe/Chisinau +03:00 Europe/Copenhagen +02:00 Europe/Dublin +01:00 Europe/Gibraltar +02:00
    77. 77. The Date-Time API provides three temporal-based classes that work with time zones: • ZonedDateTime handles a date and time with a corresponding time zone with a time zone offset from Greenwich/UTC. • OffsetDateTime handles a date and time with a corresponding time zone offset from Greenwich/UTC, without a time zone ID. • OffsetTime handles time with a corresponding time zone offset from Greenwich/UTC, without a time zone ID.
    78. 78. ZonedDateTime The ZonedDateTime class, in effect, combines the LocalDateTime class with the ZoneId class. It is used to represent a full date (year, month, day) and time (hour, minute, second, nanosecond) with a time zone (region/city, such as Europe/Paris).
    79. 79. Demo
    80. 80. OffsiteDateTime // Find the last Thursday in July 2013. LocalDateTime date = LocalDateTime.of(2013, Month.JULY, 20, 19, 30); ZoneOffset offset = ZoneOffset.of("-08:00"); OffsetDateTime date = OffsetDateTime.of(date, offset); OffsetDateTime lastThursday = date.with(TemporalAdjuster.lastInMonth(DayOfWeek.THURSD AY)); System.out.printf("The last Thursday in July 2013 is the %sth.%n", lastThursday.getDayOfMonth()); //The last Thursday in July 2013 is the 25th. .
    81. 81. Instant Class • One of the core classes of the Date-Time API import java.time.Instant; Instant timestamp = Instant.now(); //2013-05-30T23:38:23.085Z Instant oneHourLater = Instant.now().plusHours(1);
    82. 82. Instant Class (2) • There are methods for comparing instants, such as isAfter and isBefore. The until method returns how much time exists between two Instant objects. long secondsFromEpoch = Instant.ofEpochSecond(0L).until(Instant.now(), ChronoUnit.SECONDS);
    83. 83. Parsing String in = ...; LocalDate date = LocalDate.parse(in, DateTimeFormatter.BASIC_ISO_DATE);
    84. 84. String input = ...; try { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d yyyy"); LocalDate date = LocalDate.parse(input, formatter); System.out.printf("%s%n", date); } catch (DateTimeParseException exc) { System.out.printf("%s is not parsable!%n", input); throw exc; // Rethrow the exception. } // 'date' has been successfully parsed
    85. 85. Formatting ZoneId leavingZone = ...; ZonedDateTime departure = ...; try { DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a"); String out = departure.format(format); System.out.printf("LEAVING: %s (%s)%n", out, leavingZone); } catch (DateTimeException exc) { System.out.printf("%s can't be formatted!%n", departure); throw exc; } LEAVING: Jul 20 2013 07:30 PM (America/Los_Angeles)
    86. 86. Duration Instant t1, t2; ... long ns = Duration.between(t1, t2).toNanos(); Instant start; ... Duration gap = Duration.ofSeconds(10); Instant later = start.plus(gap); A Duration is not connected to the timeline, in that it does not track time zones or daylight saving time. Adding a Duration equivalent to 1 day to a ZonedDateTime results in exactly 24 hours being added
    87. 87. ChronoUnit import java.time.Instant; import java.time.temporal.Temporal; import java.time.temporal.ChronoUnit; Instant previous, current, gap; ... current = Instant.now(); if (previous != null) { gap = ChronoUnit.MILLIS.between(previous,current); }
    88. 88. Period • To define an amount of time with date-based values (years, months, days), use the Period class LocalDate today = LocalDate.now(); LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1); Period p = Period.between(birthday, today); long p2 = ChronoUnit.DAYS.between(birthday, today); System.out.println("You are " + p.getYears() + " years, " + p.getMonths() + " months, and " + p.getDays() + " days old. (" + p2 + " days total)"); //You are 53 years, 4 months, and 29 days old. (19508 days total)
    89. 89. calculate how long it is until your next birthday LocalDate birthday = LocalDate.of(1983, Month.OCTOBER, 28); LocalDate nextBDay = birthday.withYear(today.getYear()); //If your birthday has occurred this year already, add 1 to the year. if (nextBDay.isBefore(today) || nextBDay.isEqual(today)) { nextBDay = nextBDay.plusYears(1); } Period p = Period.between(today, nextBDay); long p2 = ChronoUnit.DAYS.between(today, nextBDay); System.out.println("There are " + p.getMonths() + " months, and " + p.getDays() + " days until your next birthday. (" + p2 + " total)");
    90. 90. Converting to/from a Non-ISO-Based Date LocalDateTime date = LocalDateTime.of(2013, Month.JULY, 20, 19, 30); JapaneseDate jdate = JapaneseDate.from(date); HijrahDate hdate = HijrahDate.from(date); MinguoDate mdate = MinguoDate.from(date); ThaiBuddhistDate tdate = ThaiBuddhistDate.from(date); LocalDate date = LocalDate.from(JapaneseDate.now());
    91. 91. Legacy Date-Time Code • Calendar.toInstant() converts the Calendar object to an Instant. • GregorianCalendar.toZonedDateTime() converts a GregorianCalendar instance to a ZonedDateTime. • GregorianCalendar.from(ZonedDateTime) creates a GregorianCalendar object using the default locale from a ZonedDateTime instance. • Date.from(Instant) creates a Date object from an Instant. • Date.toInstant() converts a Date object to an Instant. • TimeZone.toZoneId() converts a TimeZone object to a ZoneId
    92. 92. • The following example converts a Calendar instance to a ZonedDateTime instance. Note that a time zone must be supplied to convert from an Instant to a ZonedDateTime: Calendar now = Calendar.getInstance(); ZonedDateTime zdt = ZonedDateTime.ofInstant(now.toInstant(), ZoneId.systemDefault()));
    93. 93. Instant inst = date.toInstant(); Date newDate = Date.from(inst); Note : There is no one-to-one mapping correspondence between the two APIs, but the table on the next slide gives you a general idea of which functionality in the java.util date and time classes maps to the java.time APIs.
    94. 94. java.util Functionality java.time Functionality Comments java.util.Date java.time.Instant The Instant and Date classes are similar. Each class: - Represents an instantaneous point of time on the timeline (UTC) - Holds a time independent of a time zone - Is represented as epoch-seconds (since 1970-01-01T00:00:00Z) plus nanoseconds The Date.from(Instant) and Date.toInstant() methods allow conversion between these classes. java.util.GregorianCale ndar java.time.ZonedDateTime The ZonedDateTime class is the replacement for GregorianCalendar. It provides the following similar functionality. Human time representation is as follows: LocalDate: year, month, day LocalTime: hours, minutes, seconds, nanoseconds ZoneId: time zone ZoneOffset: current offset from GMT The GregorianCalendar.from(ZonedDateTim e) and GregorianCalendar.to(ZonedDateTim e) methods faciliate conversions between these classes.
    95. 95. java.util Functionality java.time Functionality Comments java.util.TimeZone java.time.ZoneId or java.time.ZoneOffset The ZoneId class specifies a time zone identifier and has access to the rules used each time zone. The ZoneOffset class specifies only an offset from Greenwich/UTC. For more information, see Time Zone and Offset Classes. GregorianCalendar with the date set to 1970-01-01 java.time.LocalTime Code that sets the date to 1970-01- 01 in a GregorianCalendar instance in order to use the time components can be replaced with an instance of LocalTime.
    96. 96. Nashorn Java(Script) Mitia Alexandrov
    97. 97. Was ist das? • Oracles runtime for ECMAScript 5.1 • GPL licensed • Part of OpenJDK • Released this march! • Just type jjs in the shell… and you are in!
    98. 98. Why? • Atwoods law: any application that can be written in JavaScript, will eventually be written in JavaScript • Oracle proving ground for support of dynamic languages • Currently supports ECMAScript 5.1 (but 100%). No backwards compatibility.
    99. 99. Why not Rhino • All code compiled to bytecode. No interpretation. • JSR-223 javax.script.* is the only public API.
    100. 100. Java -> JavaScript
    101. 101. Simple: import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class EvalScript { public static void main(String[] args) throws Exception { // create a script engine manager ScriptEngineManager factory = new ScriptEngineManager(); // create a Nashorn script engine ScriptEngine engine = factory.getEngineByName("nashorn"); // evaluate JavaScript statement try { engine.eval("print('Hello, World!');"); } catch (final ScriptException se) { se.printStackTrace(); } } }
    102. 102. Multiple invoke import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; public class Eval_Invocable { public static void main(String[] args) throws Exception { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("nashorn"); engine.eval("function f(x){return x < 2 ? 1 : f(x-1)*x} "); engine.eval("function sum(x,y){return x+y}"); Invocable i = (Invocable) engine; System.out.println(i.invokeFunction("f",5)); System.out.println(i.invokeFunction("f",10)); System.out.println(i.invokeFunction("sum",5,10)); System.out.println(i.invokeFunction("sum",10,15)); } }
    103. 103. Implement interface ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); engine.eval("function f(x){return x<2?1:f(x-1)*x};n" + "var i = 5;n" + "function run(){print('f('+i+')='+f(i++))}"); engine.eval("function sum(x,y){return x+y}"); Invocable i = (Invocable) engine; Runnable r = i.getInterface(Runnable.class); r.run(); Adder adder= i.getInterface(Adder.class); System.out.println(adder.sum(1,3)); public interface Adder { int sum(int a,int b); }
    104. 104. Passing variables public class Eval_Bind { public static void main(String... args) throws Exception { ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); Bindings b = engine.createBindings(); b.put("file", new File("/")); engine.eval("list = file.listFiles()", b); System.out.println(Arrays.toString((File[]) b.get("list"))); } }
    105. 105. JavaScript -> Java
    106. 106. Simple var timer = new java.util.Timer(); timer.schedule( new java.util.TimerTask({ run: function(){ print("Tick") } }) ,0,1000) java.lang.Thread.sleep(5000) timer.cancel();
    107. 107. Even more simple var timer2= new java.util.Timer(); timer2.schedule(function(){print("Tack")}, 0,1000) java.lang.Thread.sleep(5000) timer2.cancel();
    108. 108. Construct Java(Script) object • var linkedList = new java.util.LinkedList() • var LinkedList = java.util.LinkedList var list = new LinkedList() • var LinkedList = Java.type(“java.util.LinkedList”) var list = new LinkedList()
    109. 109. Types var ints = new (Java.type(“int[]”))(6) ints[0]=1 ints[1]=1.6 ints[2]=null ints[3]=“45” ints[4]=“str” Ints[5]=undefined print(ints) print(java.util.Arrays.toString(ints)) Output will be: [I@43re2sd [1, 1, 0, 45, 0, 0]
    110. 110. Types 2 var dbls = new (Java.type(“double[]”))(6) dbls [0]=1 dbls [1]=1.6 dbls [2]=null dbls [3]=“45” dbls [4]=“str” dbls [5]=undefined print(dbls ) print(java.util.Arrays.toString(dbls )) Output will be: [D@43re2sd [1.0, 1.6, 0.0, 45.0, NaN, NaN]
    111. 111. Type conversion • Passing JavaScript values to Java methods will use all allowed Java method invocation conversions… + all allowed JavaScript conversions • All native JS objects implement java.util.Map • And they do not implement java.util.List
    112. 112. Type conversion 2 Consider: static void about(Object object) { System.out.println(object.getClass()); }
    113. 113. Type conversion 2 MyJavaClass.about(123); // class java.lang.Integer MyJavaClass.about(49.99); // class java.lang.Double MyJavaClass.about(true); // class java.lang.Boolean MyJavaClass.about("hi there") // class java.lang.String MyJavaClass.about(new Number(23)); // class jdk.nashorn.internal.objects.NativeNumber MyJavaClass.about(new Date()); // class jdk.nashorn.internal.objects.NativeDate MyJavaClass.about(new RegExp()); // class jdk.nashorn.internal.objects.NativeRegExp MyJavaClass.about({foo: 'bar'}); // class jdk.nashorn.internal.scripts.JO4
    114. 114. Arrays conversions • Not converted automatically! • Explicit APIs provided: – var javaArray = Java.toJavaArray(jsArray,type) – var jsArray = Java.toJavaScriptArray(javaArray)
    115. 115. Static accesses Output: : / var ps = java.io.File.pathSeparator print(ps) var File = Java.type("java.io.File") var p = File.separator print(p)
    116. 116. By the way.. Its Java 8 so…
    117. 117. By the way.. Its Java 8 lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas lambdas … and default methods
    118. 118. So… yes .. last time lambdas for real! Output: [Ljava.lang.Object;@6591f517 [2, 4, 4, 8, 32, 42, 54] var stack = new java.util.LinkedList(); [1, 2, 3, 4,54,87,42,32,65,4,5,8,43].forEach(function(item) { stack.push(item); }); print(stack.getClass()); var sorted = stack .stream() .filter(function(i){return i%2==0}) .sorted() .toArray(); print(java.util.Arrays.toString(sorted));
    119. 119. Java 8…default methods Java: public interface DefTest { default void sayHello(String name){ System.out.println("Hello "+name); } } public class DefTestImpl implements DefTest { //nothing here } JavaScript: >jjs -cp . jjs> var DT = Java.type("DefTestImpl") jjs> DT [JavaClass DefTestImpl] jjs> var dt = new DT() jjs> dt.sayHello("World") Hello World
    120. 120. JavaScript(ing)
    121. 121. Scripting extensions • Additional classpath elements can be specified for the Java Virtual Machine (JVM). • JavaScript strict mode can be activated. • An intriguing scripting mode can be enabled.
    122. 122. Shell invocations Output: buzz:Nashorn mitia$ jjs -scripting scripting.js |> total 112 |> 0 drwxr-xr-x 16 mitia staff 544 21 апр 21:39 . |> 0 drwxr-xr-x 3 mitia staff 102 19 апр 14:26 .. |> 8 -rw-r--r-- 1 mitia staff 113 21 апр 21:32 Adder.class |> 8 -rw-r--r-- 1 mitia staff 603 21 апр 21:32 DefTest.class |> 8 -rw-r--r-- 1 mitia staff 273 21 апр 21:39 DefTestImpl.class |> 8 -rw-r--r-- 1 mitia staff 1001 21 апр 21:32 EvalScript.class |> 8 -rw-r--r-- 1 mitia staff 1379 21 апр 21:32 Eval_Bind.class |> 8 -rw-r--r-- 1 mitia staff 1402 21 апр 21:32 Eval_Invocable.class var lines = `ls –lsa`.split("n"); for each (var line in lines) { print("|> " + line); }
    123. 123. Shell invocations $ chmod +x executable.js $ ./executable.js Arguments (0) $ ./executable.js -- hello world ! Arguments (3) - hello - world - ! #!/usr/bin/env jjs -scripting print( "Arguments (${$ARG.length})"); for each (arg in $ARG) { print("- ${arg}") }
    124. 124. Benchmark
    125. 125. What we(well… ok I) didn’t speak about? … • Streaming API (but I guess Nikolay Tomitov spoke about this .. few ) • Stamped Locks • Concurrent Adders • Parallel Streams showing why the streaming API is so f*cking awesome • JavaFX • Secure Random generation • AND A LOT MORE (check this out www.baeldung.com/java8 )
    126. 126. Contacts • Blog : http://gochev.org • Facebook: https://www.facebook.com/ • Linkedin: https://www.linkedin.com/in/gochev • Skype: joke.gochev