Skip navigation
1 2 3 Previous Next

Vincent VAUBAN's Blog

197 posts
vvauban

Be aware of rownum

Posted by vvauban Jul 4, 2019
select * from emp where ROWNUM <= 5 order by sal desc;

The intention was most likely to get the five highest-paid people—a top- N query.

What the query will return is five random records (the first five the query happens to hit), sorted by salary.

https://blogs.oracle.com/oraclemagazine/on-rownum-and-limiting-results

https://youtu.be/FenOzLslj4c

by Alina Yurenko, Oracle

 

I Graal VM pros

 

Why GraalVM

  • Universal Virtual Machine

  • Efficient/Performant

  • Multilingual/Polyglot

  • Embeddable

  • Secure

  • Open source

 

Graal VM sits between languages and platforms

graal1-remastered.png

 

GraalVM architecture

 

graal2-remastered.png

 

GraalVM Compiler

 

  • Modern compiler, written from scratch

  • Integrates with the HotSpot JVM

  • Focus on high performance and extensibility

  • Optimized performance for a wide set of languages

 

Compiler interaction with VM

 

graal3b-remastered.png

Demo: java performance

 

commands:

mvn clean install

java -jar -XX:USeJVMCICompiler target/benchmark.jar

java -jar target/benchmark.jar

 

So, on a simple jar performance benchmarking, it results that GraalVM compiler builds a jar which is twenty times faster than the standard hotspot compiler build jar.

 

 

Advanced optimizations are done by GraalVM

 

  • Inlining

  • Polymorphic inlining

  • Partial escape analysis (calculates if objects need to be allocated to the heap)

  • Path duplication

  • And many more

 

 

Compiling Scala faster with Graal VM

graal4.png

 

 

 

 

II Polyglot programs

Language implementation API

 

  • Run programming languages efficiently on GraalVM

  • Create language interpreters as Java programs using Truffle API

  • Get access to the rich tooling, provided by the GraalVM ecosystem

graal3n5-remastered.png

 

Polyglot capabilities

 

  • Run JavaScript, R, Python, or Ruby in the context of Java applications

  • Secure sandboxing mechanisms

  • Zero overhead interoperability

  • Work with one set of tools for all languages

 

Enable more language

 

$GRAAL_HOME/bi/gu install python

$GRAAL_HOME/bi/gu install r

$GRAAL_HOME/bi/gu install ruby

 

 

Demo: polyglot program

 

command:

node --jvm --polyglot server.js

 

So, an application can run with different languages in the same js file: Java standard libraries, R methods, and JS.

 

III Native images

 

Pros

 

  • Instant startup, low footprint

  • Works with memory management

  • Secure execution

  • AOT-compiled using the Graal compiler

 

Native images are precompiled ahead of time

 

graal6-remastered.png

 

Native image generation

 

It takes all the classes needed from the JDK, then it is optimized, then it is put in the binary with a substrate VM (little implementation of VM.)

 

 

Demo: Native images

 

commands:

native-image ListDir

time java ListDir

time ./ListDir

So the native binary application is ten times quicker than the regular application due to the Ahead Of Time compilation.

 

graal7.png

 

 

IV Ecosystem

 

  • Spring Framework

  • Micronaut

  • Fn Project

  • Helidon

 

V Sum-up

 

  • Fast Java, Scala, Kotlin, Groovy, Clojure

  • Instant startup, low footprint

  • Polyglot & embeddable VM

  • Interoperability between node.js, Python, Ruby, R

 

https://youtu.be/FenOzLslj4c

vvauban

Modular development with JDK9

Posted by vvauban May 30, 2019

https://youtu.be/gtcTftvj0d0

 

by Alex Buckley, Java platform group, Oracle --Octobre 2017--

 

modular-dev-jdk9.png

 

Part I: Programming in the large

Programs are classes

 

It seems that an application could be a single package containing a few very rich classes all sharing data and fields accessible within the package and where a handful of public classes form the entry points or the API of the application.

Wrong!

 

Programs do not consist of a handful of packages anymore.

 

Problem: The only way to share code between packages is with the public modifier but then you're sharing it with everyone.

 

So: A package is a great way to organize classes but most people wish there was a way to organize packages to modules.

Let's define a module: A module is a set of packages designed for reuse.

In conclusion: In JDK9, programs are modules.

 

Example: java.base module

 

java.base

java.lang

java.io

java.net

java.util

com.sun.crypto.provider

sun.nio.ch

sun.reflect.annotation

sun.security.provider

In blue, are the packages that can be used outside of the module.

In red, are the packages that can be used only inside of the module.

 

The module is  declared in a file: module-info.java.

//module-info.java

module java.base {

     exports java.lang;

     exports java.io;

     exports java.net;

     exports java.util;

}

  -->It gives the name of the module
  -->and its exported packages

 

So: A module is a set of exported packages and concealed packages.

 

Accessibility JDK1-JDK8 vs JDK9


  -->JDK1-JDK8


      # public
      # protected
      # package
      # private


  -->JDK9


      # public to everyone
      # public but only to friend modules
      # public only within a module
     # protected
      # package
      # private

Access control is more powerful in JDK9 than JDK8

 

Take as an example an 'Hello world' module

 

  -->The class

 

// src/com/example/hello/SayHello.java
package com.example.hello;
import java.lang.*;
public class SayHello {
     public static void main(String[] args){
          System.out.println("Hello world");
     }
}

 

  -->The module information

 

// src/module-infor.java
module hello.world {
     exports com.example.hello;
}

 

  -->The compilation command

 

javac -d classes -sourcepath src module-info.java com/example/hello/SayHello.java

 

This module requires the java.lang package from the base module.

 

What if multiple modules export the imported package if we intends to reuse the Java base module we should specify it.

 

With? The 'requires' directive.

 

What happens if code uses concealed packages? Find another api which is not concealed.

 

BE AWARE THAT

  • module-info exports PACKAGES

  • but requires MODULES

 

because "The unit of reuse is the unit of release".

 

Ok, but how do you run a modules application?
java -p mods -m hello-world

  • -p mods specifies that modular jars are to be found in the mod directory

  • and -m HelloWorld specifies the module to run

 

 

Constraints at the modular application resolution:


  -->No missing dependencies
  -->No cyclic dependencies
  -->No split packages (no classes loading doubloons from different jars)

 

Friends modules


You can select a restricted list of jars with whom you will share a package by the following directive:

exports my.package to friend1, friend2;

This avoid 'my.package' to be overloaded by anyone else which would create undesirable dependency to 'my.package'.

 

Summary of part I: Programming in the large


  -->A module is a set of packages designed for reuse
  -->Modules offer strong encapsulation and reliable dependencies
  -->Module-aware tooling is a big part of modular development

 

Part II: Migrating to modules

 

There 3 kinds of code to consider:


  -->My application code
  -->The libraries code
  -->The JDK code

 

The JDK code is already modularized: java.base, java.logging, java.sql, and java.xml modules.
The librairies code migration to modules depends of the editors of these libs.
And the code of my application is up to me to modularize it.

 

How?


  -->Modules of my application


       # Name: that's easy
       # What modules does it require?
       # What packages does it export?

To know the dependencies of your jars, use jdeps: it report to you which jars your jar depends of.

 

jdeps -s lib/myapp.jar

It is not necessary to put 'requires java.base' because it is put for you by the compiler.

So, how do you specify in module-info.java modules that do not exist yet?Use automatic modules.

 

Automatic modules


  -->"Real" modules
  -->No changes to someone else's JAR file
  -->Module name derived from JAR file name (Hyphens to dots, no version)
  -->Exports all its packages
  -->Requires all other modules

 

Summary of part II: Migration to modules


  -->Each application JAR is usually a good candidate to be a module
  -->Each library JAR will modularize at its own pace
  -->Automatic modules mean you're not waiting for the weakest link

 

Part III: The modular JDK

The JDK is huge ten of thousands of class.

In fact, the JDK is an aggregation of frameworks (swing, crypto, xml...)

This resulting coupling of frameworks has collateral effects: development and testing costs, difficulty to secure the whole, memory footprint.

So it has been broken on modules:

 

java.se-graph.png

This accomplishment will prevent any recreation of monolith.

Java EE modules are deprecated for removal:

  • java.activation

  • java.corba

  • java.transaction

  • java.xml.bind

  • java.xml.ws

  • java.xml.ws.annotation

 

Illegal access to JDK internals causes runtime warnings.

Changes unrelated to modules:

  • Maven

  • Eclipse

  • Spring ElasticSearch

  • JUnit

  • Gradle

  • IntelliJ

  • Hibernate

  • Hadoop

  • ASM

 

Summary of part III: The modular JDK


  -->Modules all the way down
  -->JDK internals are accessible temporarily in JDK9
  -->You may need to upgrade tools and librairies to their JDK9-aware versions

 

Summary of summaries


  -->A module is a set of packages designed for reuse
  -->Automatic modules assist with migration to modules
  -->You may need to upgrade tools and librairies to their JDK9-aware versions

modular-dev-jdk9.png

vvauban

JAVA SE 11 new features

Posted by vvauban May 19, 2019

https://learn.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=2078

by Aurelio Garcia Ribeyro (Director of Product Management, Java SE --Oracle--), Nick Ristuccia (Senior Curriculum Developer, Oracle), Mikael Vidstedt (Software development director, Oracle), Glenn Maslen (Senior Manager, Curriculum Product Management, Oracle)

1) Release cadence overview


Previous JDK release model was two year based
New JDK release model is 6 months based for feature releases
New JDK release model offer Long Term Support (LTS) releases say releases with a wide range of year supports (contrary of the 6 months feature release support)
These LTS will occured every three years
Oracle JDK and Open JDK will be interchangeable from Java 11
Licensing between Oracle JDK and Open JDK differs: Open JDK is GPL (free) licensed while Oracle JDK is commercial licensed.
The cost of Oracle JDK license is due to the support going with it.

 

 

2) Making Java more Open

What was recently been open-sourced:


*Application class data sharing (OpenJDK 10)


  -->Enables you to place classes from the standard extensions directories and the application class path in the shared archive


*Project ZGC (OpenJDK 11)


  -->Low latency garbage collector to suport multi-terabytes heaps


*Flight recorder (OpenJDK 11)


  -->Collects diagnostic and profiling data about a running Java application


*Mission Control (JMC Project in OpenJDK)


  -->Monitor and manage Java applications with minimal performance overhead


*Usage logger


  -->Locally reports how Java is being used in your system

 

3) New in Java SE 11

17 JEPs

 

*JEP 330: Launching single source file programs


  -->Simplify the 'on ra;p' for new Java users
  -->Example:


    Before: $Javac -d classes HelloWorld.java
             $Java -cp classes HelloWorld
     After:  $java HelloWold.java

     With:
     class HelloWorld {
          public static void main(String... args){
               System.out.println("HelloWorld");
          }
      }

 

*JEP 321: HTTP Client
HTTP client that implements HTTP/2 and WebSocket


  -->Standardizes the incubated HTTP client API in the java.net.http package
  -->It supports


        # HTTP/1.1 and HTTP/2
        # both synchronous and asynchronous programming models
        # handles request and response bodies as reactive-streams, and
        # follows the familiar builder pattern

 

*JEP 332: Transport Layer Security (TLS) 1.3


  -->TLS 1.3 is a major overhaul of the TLS protocol and provides significant security and performance improvements over previous versions
  -->TLS 1.3 is a new version which supersedes and obsoletes previous versions of TLS including version 1.2 (RFC 5246)
  -->It also obsoletes or changes other TLS features such as the OCSP stapling extensions (RFC 6066, RFC 6961), and the session hash and extended master secret extension (RFC 7627)
  -->Deliver new cryptographic algorithm support for the following optional TLS 1.3 features


        # ChaCha20/Poly1305 cipher suites (8140466)
        # X25519/X448 elliptic curve algorithms (8171279)
        # edDSA signature algorithms (8166596)

 

*JEP 328: Java Flight Recorder
Profiling with extremely low overhead


  -->Enabled with -XX:StartFlightRecording option
  -->Built deep inside the JVM & JDK, by the engineers developing the JVM/JDK
  -->Always on -less that 1% overhead in production deployment
  -->High performance flight recording engine and data collection for Enterprise mission-critical workload


        # Access to data already collected in the JVM runtime
        # Thread local native buffers
        # Invariant TSC for time stamping
        # More accurate method profiling (method profiling data even from outside safe-points)
        # Faster and more accurate allocation profiling with automatic memory leak detection

 

*JEP 333: ZGC - Predictable, low latency, large heap GC


  -->Multi-terabyte heaps
  -->10ms Max GC pause time
  --> Lay the foundation for future GC features
  -->15% Max application throughput reduction

 

java-20190518-1.png

 

 

 

*JEP 286: Local-Variable type inference (JDK10)


  -->Previously, all local variable declarations required an explicit type on the left-hand side


  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();


  -->Now, the explicit type can be replaced by the reserved type name var
  -->The compiler infers the variable type from the initializer on the right-hand side


  var outputStream = new ByteArrayOutputStream();

 

*JEP 286: Example of benefits


  -->Code to read a line of text from a socket using try-with-resources:


  try(InputStream is = socket.getInputSTream();
      InputStreamReader isr = new InputStreamReader(is, charsetName);
      BufferedReader buf = new BufferedReader(isr)) {
     return buf.readLine();
}


  -->With local-variable type inference:


  try(var inputStream = socket.getInputStream();
      var reader = new InputStreamReader(inputStream, charsetName);
      var bufReader = new BufferedReader(reader)){
      return bufReader.readLine();
}


      # Variable names align (more readable)
      # Class names aren't repeated (more concise)

 

*JEP 286: Reserved Type Name var


  -->Keywords cannot be used for variable names


     int else - 10;   //Not valid


  -->var is not a keyword


     int var = 20; //Valid, but not recommended
                   //Old code like this won't break under Java 11


  -->var for type inference is only used when we know we're looking for type information


      var x =30;

 

*JEP 286: Where can it be used?


  -->Local variables with initial value


     var itemDescritpion = "Shirt";  //inferred as String


   -->Enhanced for-loop indexes


      for(var item : itemArray)     //inferred as Item object


  -->Traditional for-loop index variables


    for(var i=0;i<10;i++)   //inferred as int


  -->Some non-denotable types:


       # Intersection types
       # Anononymous class types

 

*JEP 286: Where can it not be used?


  -->Declarations without an initial value


     var price;


  -->Initialization with a null value


     var price = null;


  -->Compound declarations


     var price=9.95, tax=0.05;


  -->Array Initializers


     var prices = {9.95, 5, 3.50};


  -->Fields


     public var price;


  -->Parameters


     public void setPrice(var price){…}


  -->Method return type


     public var getPrice(){
         return price;
     }

 

*JEP 286: Why not?


  -->Consider this bad-example method:


     public var getSomething(var something){  //How should this compile?
           return something;  //something could be anything
     }


  -->Type inference is an algorithm, not magic


      # A goal of this feature is to let developers more-quickly read and understand code
      # Both humans and the compiler require context for understanding


  -->Prevent "action at a distance" issues


      # Don't allowcode elsewhere to conflict on what type to infer--This prevents binary incompatibilities--
      # Type must be inferred where the variable is declared

 

*JEP 286: The debate


  -->Arguments against this feature:


       # "Useful information will be hidden"
       # "Readibility will be impaired"
       # "Bad developers will misuse and overuse the feature to write terrible code"


  -->Arguments for this feature:


       # "Redundant information is removed"
       # "Code is more concise and readable"
       # "Bad developers will write terrible code no matter what"


  -->Like all features, it must be used with judgment
  -->Follow these guidelines to more effectively realize the benefits:

 

*JEP 286: Guideline 1

Choose a variable name thatt provides useful information


  -->Consider names that express the variable's role or nature:


    try(Stream<Customer> result = dbconn.executeQuery(query)){
            return result.map(...).filter(...).findAny();
     }
     becomes
     try(var customers= dbconn.executeQuery(query)){
            return result.map(...).filter(...).findAny();
     }


  -->Consider names that convey the variable's meaning or type:


     List<Customer> x = dbconn.executeQuery(query);
     becomes
     var custList = dbconn.executeQuery(query);

 

*JEP 286: Guideline 2
Miniimize the scope of local variables


     var items = new ArrayList<Item>(...);
     items.add(MUST_BE_PROCESSED_LAST);
     for(var item: items) ...


  -->Imagine, we change it by a set, knowing that a set does not have iterator order (so MUST_BE_PROCESSED_LAST is no sure to be processed last). And that the scope of the variable is extended by hundred of line of codes between the initial instructions:


     var items = new HashSet<Iten>(...);
     // ... 100 lines of code ...
     // ... 100 lines of code ...
     // ... 100 lines of code ...
     // ... 100 lines of code ...
     // ... 100 lines of code ...
      items.add(MUST_BE_PROCESSED_LAST);
     for(var item: items) ...


  -->The result is that, it leads to a bug so shorten the scope

 

*JEP 286: Guideline 3
Consider var when the initializer provides sufficient information


  -->Here both sides of these statements offer type information:


    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
     BufferedReader reader = Files.newBufferedReader(...);
     List<String> list = List.of("a","b","c");  //Before


  -->Constructor or factory method calls are enough context:


     var outputStream = new ByteArrayOutputStream();
     var reader = Files.newBufferedReader(...);
     var list = List.of("a","b","c");  //After

 

*JEP 286: Guideline 4
Consider var to split chained or nested expressions


  -->These examples take a collection of Strings and find which occurs most
  -->As a single expression, it's hard to decipher the stream and optional mix:


     return strings.stream()     //before
              .collect(groupingBy(s->s, counting()))
              .entrySet()
              .stream()
              .max(Map.Entry.comparingByValue())
              .map(Map.Entry::getKey);


  -->Splitting it may yield a good balance of readibility and concision:


     var freqMap = strings.stream()    //After
               .collect(groupingBy(s->s,counting()));
     var maxEntryOpt = freqMap.entrySet()
               .stream()
               .max(Map.Entry.comparingByValue());
     return maxEntryOpt.map(Map.Entry::getKey);

 

*JEP 286: Guideline 5
Don't worry too much about "Programming to the interface" with local variables


  -->A common Java idiom is to construct an instance with a concrete initializer type, but assign it to a variable of an interface type


      List<string> list = new ArrayList<String>();
                        = new CopyOnWriteArrayList<String>();
                        = new LinkedList<String>();


  -->This isn't possible with local variable type inference


      var list = new ArrayList<String>();

 

*JEP 286: Guideline 6
Take care using var with diamond or generic methods


  -->Consider this statement:     


       PriorityQueue<Item> itemQueue = new PriorityQueue<Item>();


  -->The "diamond" feature lets you omit explicit type information:


       PriorityQueue<Item> itemQueue = new PriorityQueue<>();


  -->var also lets you omit explicit type information:


       var itemQueue = new PriorityQueue<Item>();


  -->Using both strips the statement of context:


       var itemQueue = new PriorityQueue<>();  //Inferred as
                                               //PriorityQueue<Object>
                                               //which may not be helpful


  -->Arguments can provide context so type is inferred properly:


      Comparator<String> comp = ...;             //Inferred as
      var itemQueue = new PriorityQueue<>(comp); //PriorityQueue<String>

 

*JEP 286: Guideline 7
Take care using var with literals


  -->There is no issue with boolean, character, long, and String literals:


     //Before                    //After
     boolean ready = true;       var ready = true;
     char ch='\ufffd';           var ch = '\ufffd';
     long sum = 0L;              var sum = 0L;
     Strng label = "wombat";     var label = "wombat";


  -->Whole numbers require care, as they may be inferred as integer types:


     byte flags = 0:              var flags=0;
     short mask = 0x7fff;         var mask = 0x7fff;
     long base=17;                var base = 17;


  -->Floating point numbers require a little care, if you previously mixed types:


      float f1 = 1.0f;             var f1 = 1.0f;
      float f2 = 2.0;              var f2 = 2.0; //inferred as double
      double d3 =3.0;              var d3 =3.0;
      double d4 = 4.0f;            var d4 = 4.0f; //inferred as float

 

*JEP 323: Local-variable syntax for lambda parameters


  -->Lambda expressions could be explicitly typed:


     (Item x, int y) -> x.process(y)


  -->Lambda expressions could be implicitly typed:


     (x,y) -> x.process(y)


  -->Now, lambda expressions can also be implicitly typed with the var syntax:


     (var x, var y) -> x.process(y)

 

*JEP 323: Benefits


  -->Uniform syntax for local-variables type inferences:


     var x = new BigClassNamesMakeReadingHard();
     (var x, var y) -> x.process(y)


  -->Previously, annotations and modifiers required explicitly typed lambdas:


      (@Nonnull BigClassNamesMakeReadingHard x, final int y) -> x.process(y)


  -->var provides the more-readable implicitly typed alternative:


       (@Nonnull var x, final var y) -> x.process(y)

 

*JEP 323: these won't compile


  -->You could never mix implicitly and explicitly typed lambda parameters:


    (Item x, y) -> x.process(y)


  -->You cannot mix var and non-var in implicitly typed lambda expressions:


     (var x, y) -> x.process(y)


  -->You cannot mix var and non-var in explicitly typed lambda expressions:


     (var x, int y) -> x.process(y)


  -->You cannot omit parenthesis for single explicitly typed or var parameters:


     Item x -> x.toString();
     var x -> x.toString();


4) Beyond Java 11

 

*The next big opportunitues after Java 11


  -->Containers
  -->Predictability
  -->Performance
  -->Data optimization
  -->HW acceleration
  -->Scalability
  -->Continual language enhancements

 

*Specific projects on openjdk.java.net


  -->Panama
  -->Skara
  -->Portola
  -->Valhalla
  -->Loom
  -->Amber

 

*Project Valhalla


The data layout we have now

java-20190518-2.png

 

The data layout we want

java-20190518-3.png

 

 

*Project Loom


  -->Easier and more scalable concurrency model


      # making blocking calls virtually free


  -->"Fibers" (lightweight threads) and continuations


      # Millions of fibers can be spawned in a singe JVM instance

 

*Project Amber


  -->Language improvements


      # Dynamic Class-File Constants
      # Raw string literals
      # Switch expressions (preview in the JDK12)
      # Pattern matching

 

*Project Panama


  -->Foreign functions & data
  -->Simple, safe, and performant replacement for JNI
  -->Access to low-level hardware functionality through normal Java code


      # Vector instructions, special memory types (for example non-volatile memory)


  -->Big data, Machine Learning

 

*Project Skara


  -->Proposes to investigate alternative SCM and code review options for the JDK source code
  -->Options being investigated include those based upon Git rather than Mercurial
  -->Goal is to help OpenJDK contributors to be more productive, both seasoned committers and relative newcomers

 

*In a world of containers, we expect


  -->Safety and security becoming increasingly more important
  -->Sprawl


       # Many instances
       # Mix of different applications
       # Heterogeneous machines
       # Heterogeneous container configurations

 

*Java in a world of containers
Java's characteristics make it ideal for a container environment


  -->Managed language/runtime
  -->Hardware and operating system agnostic
  -->Safety and security enforced by JVM
  -->Reliable: Compatibility is a key design goal
  -->Runtime adaptive: JVM ensures stable execution when environment changes
  -->Rich eco system
  -->We are committed to keeping Java the first choice for container deployments

 

*Container awareness


  -->JDK-8146115: Docker container detection and resource configuration usage (jdk8, jdk10+)
  -->JDK-8186248: More flexible, percentage based heap sizing flags (jdk10+)
  -->JDK-8179498: Namespace aware attach (jdk10+)
  -->JDK-8193710: Docker container aware jcmd (jdk11+)
  -->JDK-8203357: JDK internal container metrics API (jdk11+)
  -->... and more to come!


also view Matthew Gilliard's blog: https://mjg123.github.io/2018/01/10/Java-in-containers-jdk10.html

 

*Java & container

java-20190518-4.png

 

 

*Alpine Linux & musl libc

Small. Simple. Secure.


  -->Alpine Linux is a security-oriented, lightweight Linux distribution based on musl libc and busybox. ( https://www.alpinelinux.org)
  -->musl is lightweight, fast, simple, free, and strives to be correct in the sense of standards-conformance and safety ( https://www.musl-libc.org )

 

*Project "Portola" - Alpine Linux/musl


  -->OpneJDK project "Portola" provides a port of the JDK to Alpine/musl
  -->The Alpine Linux base image weighs in at 4MB


       # Uses the "musl" C library


http://openjdk.java.net/projects/portola/
http://hg.openjdk.java.net/portola/portola
portola-dev@openjdk.java.net

 

java-20190518-5.png

 

 

5) Training


  -->A choice of live and self-paced Java training titles
  -->Obtainable as:


      # Individual titles and exams
      # Learning subscription containing groups of online coursed with certification access


  -->Training for new Java programmers starting on Java 11
  -->Training for programmers moving up from JDK 8
  -->Titles available by February 2019

 

*Training


  -->Upgrading from Java 8 to Java 11: Exam 1Z0-817
  -->Java Novice (starting on Java 11): Exams: 1Z0-815 & 1Z0-816


http://education.oracle.comjava-20190518-6.png

 

 

 

6) Summary


  -->The Java platform development on OpenJDK is becoming more open
  -->JDK  11, the next LTS release, includes innovations, security, productivity and performance improvements
  -->Oracle is simplifying Java licensing by transitioning out of the BCL "dual purpose" license
  -->Oracle University offers courses and learning subscriptions - including Java 11 - for new and upgrading Java programmers
  -->Beyond Java 11, we have a solid technical roadmap


https://learn.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=2078

https://docs.oracle.com/javase/8/docs/api/java/util/function/UnaryOperator.html

 

Function<T,R> represents a function that accepts one argument and produces a result.

Where T is the type of the input to the function and R is the type of the result of the function.

There is a specialization of Function for the case where the operand T and result R are of the same type: UnaryOperator<T>

public interface UnaryOperator<T> extends Function<T,T> represents an operation on a single operand that produces a result of the same type as its operand.

UnaryOperator<Integer> doubleIt = x->x*2;

int y = doubleIt.apply(2);

System.out.println(y);

https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join(long)

 

public final void join(long millis) throws InterruptedException

Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.

This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked.

 

In other way

The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing,

t.join();

causes the current thread to pause execution until t's thread terminates. Overloads of join allow the programmer to specify a waiting period. However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify.

Like sleep, join responds to an interrupt by exiting with an InterruptedException.

https://docs.oracle.com/javase/8/docs/api/java/time/ZoneId.html#getAvailableZoneIds--

 

 

public static Set<String> getAvailableZoneIds() gets the set of available zone IDs.

This set includes the string form of all available region-based IDs. Offset-based zone IDs are not included in the returned set. The ID can be passed to of(String) to create a ZoneId.

 

LocalDateTime dt = LocalDateTime.now();

List<String> zoneList = new ArrayList<>(ZoneId.getAvailableZoneIds());

for (String zoneId : zoneList) {

     ZoneId zone = ZoneId.of(zoneId);

     ZonedDateTime zdt = dt.atZone(zone);

     ZoneOffset zos = zdt.getOffset();

     // replace Z to +00:00

     String offset = zos.getId().replaceAll("Z", "+00:00");

     String out = String.format("%35s (UTC%s) %n", zoneId.toString(),offset);

     System.out.printf(out);//prints the zone ids and their offset, ex: America/Cuiaba (UTC-03:00)

}

https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html#and-java.util.function.Predicate-

 

default Predicate<T> and(Predicate<? super T> other)

Returns a composed predicate that represents a short-circuiting logical AND of this predicate and another. When evaluating the composed predicate, if this predicate is false, then the other predicate is not evaluated.

 

Predicate<String> widthLessThan20 = s->s.length()<20;

Predicate<String> containAVowel = s-> s.contains("a");

System.out.println("Less than 20 characters and containing the 'a' letter:");

System.out.println(widthLessThan20.and(containAVowel).test("Oracle community"));//true

https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html#constructor

 

You can reference a constructor by using the name new.

The functional interface Supplier contains one method get that takes no arguments and returns an object. Consequently, you can invoke a method with  a constructor reference as follows:

Supplier<List<String>> s =ArrayList<String>::new;

List<String> l = s.get();

So be sure the class invoking new by reference syntax contains a no-arg constructor.

https://docs.oracle.com/javase/7/docs/api/java/util/ConcurrentModificationException.html

 

public class ConcurrentModificationException extends RuntimeException

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

 

For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it.

List<String> list = new ArrayList<String>();

for(String s : list)

{

     //modifying list results in ConcurrentModificationException

     list.add("don't do this");    

}

 

Note that the Iterator<> class has a few methods that can circumvent this:

for(Iterator it = list.iterator(); it.hasNext())

{

     //no ConcurrentModificationException

     it.remove();

}

https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#lines-java.nio.file.Path-java.nio.charset.Charset-

 

public static Stream<String> lines(Path path, Charset cs) throws IOException

Read all lines from a file as a Stream. Unlike readAllLines, this method does not read all lines into a List, but instead populates lazily as the stream is consumed.

Bytes from the file are decoded into characters using the specified charset and the same line terminators as specified by readAllLines are supported.

 

 

Code to read from a text file using lines() and forEach() methods.

Path path = Paths.get("/root/test.txt");

try (Stream<String> lines = Files.lines(path)) {

     lines.forEach(s -> System.out.println(s));

} catch (IOException ex) {

      // do something or re-throw...

}

https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#syntax

 

A lambda expression consists of the following:

  • A comma-separated list of formal parameters enclosed in parentheses.

  • The arrow token, ->

  • A body, which consists of a single expression or a statement block.

 

 

( Integer i ) -> System.out.println(i+" ");

https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html

 

LocalDate represents a date without a time-zone in the ISO-8601 calendar system, such as 2007-12-03.

 

  • LocalDate plus(long amountToAdd, TemporalUnit unit) returns a copy of this date with the specified amount added.

  • LocalDate plus(TemporalAmount amountToAdd) returns a copy of this date with the specified amount added.

  • LocalDate plusDays(long daysToAdd) returns a copy of this LocalDate with the specified number of days added.

  • LocalDate plusMonths(long monthsToAdd) returns a copy of this LocalDate with the specified number of months added.

  • LocalDate plusWeeks(long weeksToAdd) returns a copy of this LocalDate with the specified number of weeks added.

  • LocalDate plusYears(long yearsToAdd) returns a copy of this LocalDate with the specified number of years added.

 

LocalDate date = LocalDate.parse("2018-12-12");

System.out.println(date.plusDays(2)); //2018-12-14

 

The methods to "plus" hours, minutes, seconds, nanos belong to LocalDateTime

https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html

 

First convert your regular stream to an IntStream by mapToInt method:

IntStream mapToInt(ToIntFunction<? super T> mapper)

Returns an IntStream consisting of the results of applying the given function to the elements of this stream.

 

Then use the sum method:

int sum()

Returns the sum of elements in this stream. This is a special case of a reduction and is equivalent to: return reduce(0, Integer::sum);

 

Example:

int sum = widgets.stream()

                      .filter(w -> w.getColor() == RED)

                      .mapToInt(w -> w.getWeight())

                      .sum();

https://www.slideshare.net/martyhall/file-io-in-java-8-part-1-applying-the-power-of-streams

 

public static Stream<Path> list(Path dir) throws IOException

Return a lazily populated Stream, the elements of which are the entries in the directory. The listing is not recursive.

The elements of the stream are Path objects that are obtained as if by resolving the name of the directory entry against dir.

 

 

Stream<Path> paths = Files.list(Paths.get("MyDocuments"));

paths.forEach(System.out::println);

 

See also Files.walk, Files.find