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

Preview:

DESCRIPTION

 

Citation preview

TRADER.BG®

Bulgarian Java user group

• http://java-bg.org• http://groups.google.com/group/bg-jug

Agenda

• Java 7 yes.. 7 • Java 8– Static methods on interfaces– Lamdas?

– Exact Numeric Operations– Type Annotations– Optional– Date and Time– Nashorn

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

• 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")))) {…}

And do you know about the “More Precise Rethrowing of Exception”

• In Java version *.. yes we all know this is BADpublic 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;}

}

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();

}

The biggest two additions to Java 7 are.. ?

The biggest two additions to Java 7 are.. ?

• 1) MethodHandleMethod 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.

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");

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");

And the second BIG addition to Java 7 is.. ?

• 2) invokedynamicThe 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.

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.

How invokedynamic look ?invokevirtual #4 //Method java/io/PrintStream.println:(Ljava/lang/String;)V

invokedynamic #10 //NameAndTypelessThan:(Ljava/lang/Object;Ljava/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.

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))

Anyway enough Java 7.. Java 8

And Java 8 is all about Lambdas right?

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) { ... }}

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?

So..Lambdas… I see Lambdas everywhere…

• Lambdas bring anonymous function types in Java (JSR 335):

• Example:

(x,y) -> x + y

(parameters) -> {body}

Lambdas refresh

• Lambdas can be used in place of functional interfaces (interfaces with just one method such as Runnable)

• Example:new Thread(new Runnable() {

@Overridepublic void run() {

System.out.println("It runs!"); }}).start();

new Thread(() -> System.out.println("It runs!") ).start();

@FunctionalInterface(s) some notes

@FunctionalInterfaceinterface Test {

public void doSomething();}

This is NOT @FunctionalInterface

@FunctionalInterfaceinterface Test2 {

public default void doSomething() {}}

This are valid @FunctionalInterface(s)

@FunctionalInterfaceinterface Test3 {

public void doSomething();public default void doSomethingDefault()

{}}

@FunctionalInterfaceinterface Test4 {

public void doSomething();public static void doSomethingDefault()

{}}

This look like a valid @FunctionalInterface but is NOT and can NOT be used as Lambda

@FunctionalInterfaceinterface Test5 {

public <T> T doSomething();}

Lets suppose you have a method like thispublic static void something(Test5 t){

System.out.println(t.doSomething());}

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() {@Overridepublic <T> T doSomething() {

return (T) "hello";}

});

So use generic classes.. @FunctionalInterface

@FunctionalInterfaceinterface Test6<T> {

public T doSomething();}

And of course you can then consume and use this like that

something(new Test6<Integer>() {@Overridepublic Integer doSomething() {

return 5;}

});//orsomething(() -> 5);

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.

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.

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 addpublic static void doIt(Supplier<Integer> a){ }And that’s look fine… to us.

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.

Lets continue with Lambdas black magic

Lambdas are NOT Anonymous classes

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

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.

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

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

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

Annotations? Not your java 5 Annotations!

Annotations in Java 5/6/7• Annotations on class declarations @Stateless public class Person

Annotations in Java 5/6/7• Annotations on class declarations @Stateless public class Person

• Annotations on method declarations @Override public String toString() {

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 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) {

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;}

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.

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

• 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 {@Overridepublic void sayHello(String notNull) {

// TODO Auto-generated method stub}@Overridepublic void sayHelloNullable(@NotNull String

notNull) {// TODO Auto-generated method stub

}}

Examples:List<@ReadOnly @Localized Message> messages;Map<@NonNull String, @NonEmpty List<@Readonly Document>> documents;

class MyClass{private List<@Email String>

emailAddresses;}

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 representationAnnotatedParameterizedType annotatedParameterizedType = (AnnotatedParameterizedType) emailAddressField.getAnnotatedType();// get all type parametersAnnotatedType[] annotatedActualTypeArguments = annotatedParameterizedType.getAnnotatedActualTypeArguments();// the String parameter which contains the annotationAnnotatedType stringParameterType = annotatedActualTypeArguments[0];// The actual annotationAnnotation emailAnnotation = stringParameterType.getAnnotations()[0];

System.out.println(emailAnnotation); // @Email()

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

Getting parameter namespublic 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;}

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.

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();

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);

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.joining(","));

Base64 encode/decode// Encode String asB64 = Base64.getEncoder().encodeToString("some string".getBytes("utf-8"));

System.out.println(asB64); // Output will be: c29tZSBzdHJpbmc=

// Decodebyte[] asBytes = Base64.getDecoder().decode("c29tZSBzdHJpbmc=");

System.out.println(new String(asBytes, "utf-8")); // And the output is: some string

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("");

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);

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

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.

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 againOptional<Integer> integerOrNot = stringOrNot.map(Integer::parseInt);

// This int reference will never be nullint 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

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

• 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

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.

OverviewClass or Enum Year Mon

th Day Hours

Minutes

Seconds*

Zone Offset

Zone ID

toString Output

Instant X 2013-08-20T15:16:26.355Z

LocalDate X X X 2013-08-20

LocalDateTime X X X X X X

2013-08-20T08:16:26.937

ZonedDateTime X X X X X X X X

2013-08-21T00:16:26.941+09:00[Asia/Tokyo]

LocalTime X X X 08:16:26.943MonthDay X X --08-20

OverviewClass or Enum Year Mon

th Day Hours

Minutes

Seconds*

Zone Offset

Zone ID

toString Output

Year X 2013YearMonth X X 2013-08Month X AUGUST

OffsetDateTime X X X X X X X

2013-08-20T08:16:26.954-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)

Method Naming Conventions in Date&Time APIPrefix 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 instanceReturns 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.

MonthMonth 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

LocalDateLocalDate 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.

MonthDay & YearMonthDay date = MonthDay.of(Month.FEBRUARY, 29);boolean validLeapYear = date.isValidYear(2010);

boolean validLeapYear = Year.of(2012).isLeap();

LocalTime

LocalTime thisSec = LocalTime.now();

someMethod(thisSec.getHour(),thisSec.getMinute(),thisSec.getSecond());

LocalDateTimeSystem.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.985Apr 15, 1994 @ 11:30am: 1994-04-15T11:30now (from Instant): 2013-07-24T17:14:00.4796 months from now: 2014-01-24T17:14:00.4806 months ago: 2013-01-24T17:14:00.481

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.

ExampleSet<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

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.

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).

Demo

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.THURSDAY));

System.out.printf("The last Thursday in July 2013 is the %sth.%n", lastThursday.getDayOfMonth());

//The last Thursday in July 2013 is the 25th..

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.085ZInstant oneHourLater = Instant.now().plusHours(1);

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);

ParsingString in = ...;LocalDate date = LocalDate.parse(in, DateTimeFormatter.BASIC_ISO_DATE);

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

FormattingZoneId 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)

DurationInstant 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

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);}

Period• To define an amount of time with date-based values

(years, months, days), use the Period classLocalDate 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)

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)");

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());

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

• 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()));

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.

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 nanosecondsThe Date.from(Instant) and Date.toInstant() methods allow conversion between these classes.

java.util.GregorianCalendar 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 GMTThe GregorianCalendar.from(ZonedDateTime) and GregorianCalendar.to(ZonedDateTime) methods faciliate conversions between these classes.

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.

Nashorn

Java(Script)

Mitia Alexandrov

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!

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.

Why not Rhino

• All code compiled to bytecode. No interpretation.

• JSR-223 javax.script.* is the only public API.

Java -> JavaScript

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(); } }}

Multiple invokeimport 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)); }}

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);}

Passing variablespublic 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"))); }}

JavaScript -> Java

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();

Even more simple

var timer2= new java.util.Timer();

timer2.schedule(function(){print("Tack")},0,1000)

java.lang.Thread.sleep(5000)timer2.cancel();

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()

Typesvar ints = new (Java.type(“int[]”))(6)ints[0]=1ints[1]=1.6ints[2]=nullints[3]=“45”ints[4]=“str”Ints[5]=undefinedprint(ints)print(java.util.Arrays.toString(ints))

Output will be:[I@43re2sd[1, 1, 0, 45, 0, 0]

Types 2var dbls = new (Java.type(“double[]”))(6)dbls [0]=1dbls [1]=1.6dbls [2]=nulldbls [3]=“45”dbls [4]=“str”dbls [5]=undefinedprint(dbls )print(java.util.Arrays.toString(dbls ))

Output will be:[D@43re2sd[1.0, 1.6, 0.0, 45.0, NaN, NaN]

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

Type conversion 2

Consider:

static void about(Object object) { System.out.println(object.getClass());}

Type conversion 2MyJavaClass.about(123);// class java.lang.IntegerMyJavaClass.about(49.99);// class java.lang.DoubleMyJavaClass.about(true);// class java.lang.BooleanMyJavaClass.about("hi there")// class java.lang.StringMyJavaClass.about(new Number(23));// class jdk.nashorn.internal.objects.NativeNumberMyJavaClass.about(new Date());// class jdk.nashorn.internal.objects.NativeDateMyJavaClass.about(new RegExp());// class jdk.nashorn.internal.objects.NativeRegExpMyJavaClass.about({foo: 'bar'});// class jdk.nashorn.internal.scripts.JO4

Arrays conversions

• Not converted automatically!

• Explicit APIs provided:– var javaArray = Java.toJavaArray(jsArray,type)– var jsArray = Java.toJavaScriptArray(javaArray)

Static accesses

Output::/

var ps = java.io.File.pathSeparatorprint(ps)var File = Java.type("java.io.File")var p = File.separatorprint(p)

By the way.. Its Java 8

so…

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

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));

Java 8…default methodsJava: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

JavaScript(ing)

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.

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);} 

Shell invocations

$ chmod +x executable.js$ ./executable.jsArguments (0)$ ./executable.js -- hello world !Arguments (3)- hello- world- !

#!/usr/bin/env jjs -scriptingprint("Arguments (${$ARG.length})");for each (arg in $ARG) { print("- ${arg}")}

Benchmark

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 )

Contacts

• Blog : http://gochev.org• Facebook: https://www.facebook.com/• Linkedin: https://www.linkedin.com/in/gochev• Skype: joke.gochev

Recommended