lecture from javaday.bg by nayden gochev/ ivan ivanov and mitia alexandrov

129

Upload: nayden-gochev

Post on 26-Jan-2015

107 views

Category:

Engineering


0 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Page 2: Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov

TRADER.BG®

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

Bulgarian Java user group

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

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

Agenda

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

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

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

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

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

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

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

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

}

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

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

}

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

The biggest two additions to Java 7 are.. ?

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

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.

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

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

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

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

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

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.

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

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.

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

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.

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

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

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

Anyway enough Java 7.. Java 8

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

And Java 8 is all about Lambdas right?

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

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

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

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?

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

So..Lambdas… I see Lambdas everywhere…

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

• Example:

(x,y) -> x + y

(parameters) -> {body}

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

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

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

@FunctionalInterface(s) some notes

@FunctionalInterfaceinterface Test {

public void doSomething();}

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

This is NOT @FunctionalInterface

@FunctionalInterfaceinterface Test2 {

public default void doSomething() {}}

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

This are valid @FunctionalInterface(s)

@FunctionalInterfaceinterface Test3 {

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

{}}

@FunctionalInterfaceinterface Test4 {

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

{}}

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

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

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

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

});

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

So use generic classes.. @FunctionalInterface

@FunctionalInterfaceinterface Test6<T> {

public T doSomething();}

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

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

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

return 5;}

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

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

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.

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

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.

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

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.

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

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.

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

Lets continue with Lambdas black magic

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

Lambdas are NOT Anonymous classes

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

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

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

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.

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

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

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

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

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

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

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

Annotations? Not your java 5 Annotations!

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

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

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

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

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

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

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;

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

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

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

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

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

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.

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

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

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

• 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

}}

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

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

class MyClass{private List<@Email String>

emailAddresses;}

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

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

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

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

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

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

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

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.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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.

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

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

Page 65: Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Page 66: Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov

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

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

• 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

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

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.

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

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

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

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)

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

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.

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

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

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

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.

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

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

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

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

LocalTime

LocalTime thisSec = LocalTime.now();

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

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

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

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

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.

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

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

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

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.

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

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

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

Demo

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

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

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

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

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

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

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

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

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

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

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

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)

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

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

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

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

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

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)

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

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

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

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

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

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

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

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

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

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.

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

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.

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

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.

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

Nashorn

Java(Script)

Mitia Alexandrov

Page 99: Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and 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!

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

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.

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

Why not Rhino

• All code compiled to bytecode. No interpretation.

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

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

Java -> JavaScript

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

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

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

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

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

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

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

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

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

JavaScript -> Java

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

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

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

Even more simple

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

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

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

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

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

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

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]

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

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]

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

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

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

Type conversion 2

Consider:

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

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

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

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

Arrays conversions

• Not converted automatically!

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

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

Static accesses

Output::/

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

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

By the way.. Its Java 8

so…

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

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

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

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

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

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

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

JavaScript(ing)

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

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.

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

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

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

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

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

Benchmark

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

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 )

Page 128: Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Page 129: Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov

Contacts

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