Devnexus 2019: Reflection and Unsafe alternates

java, java 11

As has been the norm for the past few years, I am very excited about attending Devnexus once again, in 2019. In my humble opinion, Devnexus is one of the best tech. conferences to attend. Devnexus is held in Atlanta, Georgia from March 6th – 8th 2019.

My presentation

I will be presenting on Friday, March 8th 2019, on the topic of Alternates to Reflection and Unsafe usage. This talk is a part presentation (small), part live coding kata session. Bring your laptop to participate in coding along – or – use a QR code scanner/scribbling device of your choice to capture the URL where you can check out the code to try out the coding portion later.



Many Java libraries and frameworks currently use Reflection and Unsafe APIs. With the newer modular Java some of these important tools of our trade may become incompatible and/or may not work as desired. In addition several enterprise applications also rely on Core Reflection, (if not the use of Unsafe APIs).


The essence of the session is to demonstrate the alternates for the current usage patterns for some of the simpler and more common usages of Java Reflection API and the sun.misc.Unsafe among applications, libraries and frameworks. An explanation of the newer Handles API will be followed with code that allows for a comparison between using both styles.

Oh, and spoiler alert: there may be an abridged fairy tale or two introduced during this talk.


This presentation is intended for the application developers and is aimed at helping them both understand reflection and the newer alternates. This may further evolve into developers contributing to applications, libraries and frameworks in converting to the newer APIs.

The coding portion of this session is a code kata, that has two different kinds of unit tests. The code contains passing JUnit tests which show how Core Reflection and Usafe APIs were used, and failing tests using new light-weight Method and Var Handle APIs that the attendees can solve-along (or take as homework to work on).


A coding kata is best described THE Dave Thomas (Author of the The Pragmatic Programmer). Please do read his blog at From Wikipedia:

A code kata is an exercise in programming which helps programmers hone their skills through practice and repetition.

How does one go about with this kata?


  1. Run the test class(es).
  2. One or more tests will fail with the test failure message.
  3. Fix the failing tests by taking hints from the TODOs.
  4. Repeat above steps until all tests pass.
  5. Rinse and repeat (delete and checkout again, then back to Step 1) to build muscle memory.

Each test class has two types of test methods:

  • Solved test methods show how an invocation/access can be achieved with the traditional calls.
  • Unsolved/failing test methods which provide TODO hints that will allow the kata-taker to manually solve the exercise to achieve the same with MethodHandles/VarHandles.

How to prepare for coding along

This kata is developed as a Java maven project. Ensure that you have:

  1. Apache Maven 3.3.x or above. Tested with Apache Maven 3.5.0.
  2. JDK 11. Tested with OpenJDK 11
  3. Your favorite Java IDE. IntelliJ IDEA Ultimate was used to develop this kata.
  4. Checkout the code from Github (link will be provided during the session).

Topics Covered


Reflection is heavy weight. Reflection has been around in the Java space since almost 1997 (Java 1.1). Thanks to some futuristic changes in Java back in early 2000s, newer, more safe and more lightweight alternates are now available for almost all of the usages of reflection. Alternates to reflection using MethodHandles introduced in Java 7 are described.

The code kata covers constructor invocation and method calls to public, private, package-protected and protected methods. The solved examples show how invocations are performed using the Core Reflection API. The unsolved or failing tests that need to be fixed carry TODOs with hints explaining how to solve them and thus learn the newer MethodHandle API.


Unsafe is, well, unsafe. The sun.misc.Unsafe is a goto for developers (specially library and framework developers). Unsafe API allows for lower level memory modifications of fields and was the “solution” to atomic operations prior to the introduction of Atomic* classes. The Unsafe API also exposed some “dangerous” functionality, which will be covered.

The code kata covers getters, compareAndSet operations using Unsafe. The Kata also makes a distinction of what was supported in sun.misc.Unsafe, but is no longer allowed with the new VarHandle API.


Some questions that usually popup during such a session including how the invocation happens, what the limitations are and how it all works. These are included in a more verbose appendix. A PDF copy of the presentation is included with the code. In addition, some of the features of Unsafe that cannot possibly be covered, given both the time limits of the presentation and the arrangement of the kata, are listed out in the appendix.

Take Away

The key take-away for an attendee of this presentation and kata is a solid understanding of the simpler and more common usages of Core Reflection API and Unsafe API alongside the newer Handles API both in similarity and in certain cases, how they differ.

Who knows if your next open source/enterprise contribution is with helping out a library, framework or an enterprise application in converting to the newer APIs ?

Switching between multiple JDKs on a Mac

java, java 10, java 11, java 8, java 9, technology

Blog post date: 2018-May-18
Relevant versions of Java: Java 1.7, 8, 9, 10, 11

We often work with different versions of Java. There are times when we would like to test our application/program against different JDKs. Or … we just love to collect all versions of Java released just to show off.

Either of these would mean some kind of control of the JAVA_HOME and the PATH environment variables.


Many developers have successfully overcome this with innovative scripts to quickly switch Java versions. I am one such developer and below is an explanation of my setup.

Current installations of JDK on my Mac:

  • JDK 1.7.0_80
  • JDK 1.8.0_172
  • JDK 9.0.4
  • JDK 10.0.1
  • JDK 11-ea+14

How does one determine the current installations of JDK?

On your Mac terminal run the command:

/usr/libexec/java_home -verbose

Sample output:

Matching Java Virtual Machines (5):
11, x86_64: "OpenJDK 11-ea" /Library/Java/JavaVirtualMachines/jdk-11.jdk/Contents/Home
10.0.1, x86_64: "OpenJDK 10.0.1" /Library/Java/JavaVirtualMachines/jdk-10.0.1.jdk/Contents/Home
9.0.4, x86_64: "OpenJDK 9.0.4" /Library/Java/JavaVirtualMachines/jdk-9.0.4.jdk/Contents/Home
1.8.0_172, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_172.jdk/Contents/Home
1.7.0_80, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_80.jdk/Contents/Home

Simple ! Quite easy to determine the current JDKs available.

How can I switch Java versions easily?

Aliases. That’s it. If you know this, you can skip the remaining part of this blog. What is really cool is how a single JVM exec command can be used to switch JDK versions.

Sharing an excerpt from a .bash_profile:

alias jdk11="export JAVA_HOME=`/usr/libexec/java_home -v 11` && export PATH=$JAVA_HOME/bin:$PATH; java -version"
alias jdk10="export JAVA_HOME=`/usr/libexec/java_home -v 10` && export PATH=$JAVA_HOME/bin:$PATH; java -version"
alias jdk9="export JAVA_HOME=`/usr/libexec/java_home -v 9` && export PATH=$JAVA_HOME/bin:$PATH; java -version"
alias jdk8="export JAVA_HOME=`/usr/libexec/java_home -v 1.8` && export PATH=$JAVA_HOME/bin:$PATH; java -version"
alias jdk7="export JAVA_HOME=`/usr/libexec/java_home -v 1.7` && export PATH=$JAVA_HOME/bin:$PATH; java -version"

Note how the Java versioning from 9 onwards is a full digit? The same applies with the default directory names of the installed JDKs. This was a deliberate change toshake off the 1.x naming style of prior versions of Java.

JDK switching output

A picture would do this more justice.
Switching JDKs at Terminal

Maintenance of JDKs

Needs Admin rights on the Mac !

Keeping the JDK versions up-to-date is in everyone’s best interest, both for the new features as well as any security patches. A few steps that can help with maintaining:

    1. Extract the latest build/patch of the JDK into the directory: /Library/Java/JavaVirtualMachines.
      • If an installer was used, most likely the directories are created.
      • If a tarball was extracted from, make sure to move the extracted directory under the parent mentioned above.


    1. Post-installation, open a new terminal shell (current shell will not pick up the latest patch of an existing version of the JDK).
      • Add the appropriate alias, if this is a new version of Java
      • If existing version being patched, then no further action is needed.


    1. Type in the appropriate alias and verify that the build/patch is what shows.


  1. Once verified, the options for removing the prior patch present themselves:
    • delete older build/patch since it is no longer useful to reclaim space.
    • retain older build/patch, for other usage. It is possible to manually switch to this build/patch:
      • export JAVA_HOME=/Library/Java/JavaVirtualMachines/
      • export PATH=$JAVA_HOME/bin:$PATH

That’s a wrap on Switching JDKs on a Mac. Hope this post was helpful.

Java 9 Features – Changes to Optional

java, java 9, technology


In Java 8, a new class named Optional was introduced. Or rather in the word-style of Douglas Adams, “in the beginning null was created. This made a lot of people angry and was widely regarded as a bad move“. Optional was introduced to alleviate some of that anger.

Optional relieved developers of the grief of null checks and the “fun” of a NullPointerException popping up when failing to null check.

In Java 8, the Optional already had very useful methods:

  • of – Wrap the non-null value into an Optional.
  • ofNullable – Wrap and return an Optional of the current value, if current value is null, return Optional.empty()
  • isPresent – Checks and returns a boolean indicating the presence of a non-null value in the Optional.
  • ifPresent – Checks and invokes the specified Consumer instance upon the presence of a non-null value in the Optional.
  • get – Fetch the value in the Optional if it is not null, else throw a NoSuchElementException
  • orElse – Fetch the value in the Optional if it is not null, else return the other element passed in.
  • orElseGet – Fetch the value in the Optional if it is not null, else return invoke the other Supplier to fetch an element instead.
  • orElseThrow – Fetch the value in the Optional if it is not null, else throw the passed in Exception.
  • filter – If the value exists, test the filtering Predicate on it and if true return result wrapped in an Optional, else return Optional.empty().
  • map – If the value exists, apply the mapping Function to it and return any non-null result wrapped in an Optional, else return Optional.empty().
  • flatMap – If the value exists, apply the Optional-bearing mapping Function to it and return any non-null result wrapped in an Optional, else return Optional.empty().

Java 9 changes

  • ifPresentOrElse – Checks and returns a boolean indicating the presence of a non-null value in the Optional, or else, invokes the Runnable action.
  • or – Wrap and return an Optional of the current value if not null; if current value is null, return Optional by invoking the specified Supplier
  • stream – Returns a sequential stream containing only the value, if the value is non-null.


Consider a situation where the code is to either run a Consumer if the value exists or else run a different action. This is not possible in the Java 8 Optional behavior. Optional in Java 8 provides an orElse or an orElseGet method, both of which actually return an unwrapped value, rather than act as an execution block.

Source at:

Pre-Java 8 :

if(preference != null) { 
} else {

In Java 8 :

if(optionalPreference.isPresent()) { 
} else {


// orElseGet returns a non-optional value
// it cannot be used to simply execute an action.
Preference p = optionalPreference.orElseGet(callAbsenceSupplier());

In Java 9 :



Per the Java 8 API, both the orElse and the orElseGet do not return an Optional, rather return the unwrapped value. It is possible that such a value is null. The or method is introduced as a means to execute a supplier on absence of an unwrapped value in the container, and returns an Optional, rather than the unwrapped value.

Source at:

Pre-Java 8 :

Preference preference = findPreference(name); 
if(preference == null) {
    preference = createPreference(name, description);
// preference can still be null !!!

In Java 8 :

Preference preference = 
            .orElseGet(getPreferenceSupplier(name, description));
// preference can still be null !!!

In Java 9 :

Optional optionalPreference = 
            .or(getOptionalPreferenceSupplier(name, description));
// optional preference, so, protected from being null !!!


Given a situation where a stream or collection of Optionals exist, and we need to extract values from each, if they contain non-null values. Optional::stream returns a stream with a single non-null value if the Optional has a non-null value, or returns an empty stream otherwise.

Source at:

Pre-Java 8 :

List preferences = new ArrayList();
for (String preferenceName : PREFERENCE_NAMES) {
    Preference aPreference = findPreference(preferenceName);
    if (aPreference != null) {

In Java 8 :

List preferences =
                .map(preferenceName -> findOptionalPreference(preferenceName))

In Java 9 :

List preferences =
                .map(preferenceName -> findOptionalPreference(preferenceName))

That’s a wrap on the Optional changes in Java 9. Hope this post was helpful.

Java 9 Features – Private Interface Methods

java, java 9, technology


A blog on Java 9 changes for interfaces.

Evolution of interfaces in Java:

Until Java 7, all versions of Java maintained the same set of features for interfaces. Interfaces can

Interfaces contained method signatures and were useful for storing public constants. Since then, constants have remained a staple of the interface. Recent changes have been more focused on methods.

Java 7

  • abstract methods – Method signatures as contracts that had to be implemented by the class that implemented the interface.

Java 8

  • default methods – Methods with an implementation in the interface, providing an option to the implementing class to override.

    This change allowed for extension and growth of existing APIs without major refactoring and without harming backward-compatibility. Best example of this is the Java 8 collection framework that introduced new features on the root interfaces without having to make significant changes to any of the implementations.

    See for sort(...) or spliterator() or replaceAll(...).

  • static methods – Methods with the static modifier with an implementation, which thus belong to the interface.

    These methods cannot be overwritten in implementing classes. Adding static methods allows the interface to control some behavior without allowing for an implementation to alter such behavior.

    See for comparingByKey() or comparingByValue().

Java 9

  • private methods – Methods with implementation in the interface that remain private to the interface alone.

    These methods are useful from an encapsulation perspective to hold some logic that the implementations should not override.

    While there is no concrete example in the JDK API that I could immediately find, there are several existing interfaces which have workarounds for encapsulating private methods via private inner classes. Such workarounds can be circumvented with private methods.

Java support in interfaces

  Java 7 Java 8 Java 9
abstract methods
default methods
public static methods
private methods
private static methods

Modifier combinations in Java 9

Combination Comment
[public] (naturally abstract) supported
[public] default supported
[public] static supported
private supported
private static supported
private abstract compile-time error
private default compile-time error

Java 8 Date Time API – A Kata

java, java 8, technology


This post is an extract of a Code Kata presentation I had hosted back in November 2015. Java 8 Date Time API was relatively new to many of the attendees.

This Kata-based style of teaching includes sharing a set of failing / non-functional JUnit tests with TODO comments indicating actions that need to be taken to resolve/pass the JUnit tests. Solving the JUnit tests repeatedly helps developers gain muscle-memory into using the feature (similar to the karate kata).

Link to the code kata is on Github, located at the bottom of the post.

Background: Why a new API

First, some background on why there was a need to create a new API.

Issues with java.util.Date


  • is mutable-only – Date instances are not immutable.
  • has concurrency problems – Date instances are not thread-safe.
  • has incorrect naming – Date is not a “date” but a “timestamp”.
  • lacks convention – Days start with 1, months with 0 and years with 1900.
  • lacks fluency – Cannot create durations (a quarter, 5 minutes) OR combos(year+month, date without seconds) etc.

Additional observations about the pre-Java 8 Date API

  • System.currentTimeInMillis() is not accurate and can return same value for multiple sequential calls.
  • java.util.Date vs. java.sql.Date – SQL flavor is only a DATE with no time.
  • java.sql.Timestamp – SQL flavor replicating java.util.Date but additionally storing nanoseconds.

Issues with java.util.Calendar


  • lacks clarity – Mix of dates and times.
  • has confusing timezone support – Not very easy to switch timezones, offsets etc.
  • has severe formatting hurdlesSimpleDateFormat and Calendar do not interoperate well.
  • presents extension hardships – New calendar systems are created by extending Calendar (therefore all it’s problems).

“Calendar is the Ravenous Bugblatter Beast of Traal for Date APIs” – Chandra Guntur (circa 2000).

What was proposed to fix this?

JSR-310: Date and Time API
Excerpts from JSR-310 (

  • “The main goal is to build upon the lessons learned from the first two APIs (Date and Calendar) in Java SE, providing a more advanced and comprehensive model for date and time manipulation.”
  • “The new API will be targeted at all applications needing a data model for dates and times. This model will go beyond classes to replace Date and Calendar, to include representations of date without time, time without date, durations and intervals.
  • “The new API will also tackle related date and time issues. These include formatting and parsing, taking into account the ISO8601 standard and its implementations, such as XML.”
  • “The final goal of the new API is to be simple to use. The API will need to contain some powerful features, but these must not be allowed to obscure the standard use cases. Part of being easy to use includes interaction with the existing Date and Calendar classes …”

Origins of the JSR-310

Java 8 Date Time API

The Java classes in lavender below are all linked to the JDK 8 API. Please feel free to click.

Date Time Classes

Dates and Times: Simple Date and Time ‘containers’

  • Instant stores a numeric timestamp from Java epoch, + nanoseconds.
  • LocalDate stores a date without a time portion (calendar date).
  • LocalTime stores a time without a date portion (wall clock).
  • LocalDateTime stores a date and time (LocalDate + Local Time).
  • ZonedDateTime stores a date and time with a time-zone.
  • OffsetTime stores a time and offset from UTC without a date.
  • OffsetDateTime stores a date with time and offset from UTC.

Ranges and Partials: Spans and ranges of temporality

  • Duration models time in nanoseconds for time intervals. (e.g. 5 mins)
  • Period models amount of time in years, months and/or days. (e.g. 2 Days)
  • Month stores a month on its own. (e.g. MARCH)
  • MonthDay stores a month and day without a year or time (e.g. date of birth)
  • Year stores a year on its own. (e.g. 2015)
  • YearMonth stores a year and month without a day or time. (e.g. credit card expiry)
  • DayOfWeek stores a day-of-week on its own. (e.g. WEDNESDAY)

Chronology: A calendar system to organize and identify dates

  • Chronology is a factory to create or fetch pre-built calendar systems.
    Default is IsoChronology (e.g. ThaiBuddhistChronology).
  • ChronoLocalDate stores a date without a time in an arbitrary chronology.
  • ChronoLocalDateTime stores a date and time in an arbitrary chronology.
  • ChronoZonedDateTime stores a date, time and timezone in an arbitrary chronology.
  • ChronoPeriod models a span on days/time for use in an arbitrary chronology.
  • Era stores a timeline [typically two per Chronology, but some have more eras].

Date Time Common API – Reference Table

Date and Time

Type Y M D H m S(n) Z ZId toString
Instant 1999-01-12T12:00:00.747Z
LocalDate 1999-01-12
LocalTime 12:00:00.747
LocalDateTime 1999-01-12T12:00:00.747
ZonedDateTime 1999-01-12T12:00:00.747-05:00 [America/New_York]
OffsetTime 12:00:00.747-05:00
OffsetDateTime 1999-01-12T12:00:00.747-05:00


Type Y M D H m S(n) Z ZId toString
Duration P22H
Period P15D


Type Y M D H m S(n) Z ZId toString
MonthDay -01-12
Year 1999
YearMonth 1999-01

Fluency and Symmetry in the new Date Time API

The Java 8 Date Time API introduces a certain symmetry in operations that make for a pleasant developer experience. Below is a list of prefixes for methods across the API that perform in a similar pattern where encountered.

  • of {static factory method prefix} – Factory method to obtain an instance with provided parameters – validates and builds with no conversion.example usage: LocalDate.of(...) or Instant.ofEpochSecond(...)
  • from {static factory method prefix} – Factory method to obtain an instance with provided parameters – validates, converts and builds.example usage: LocalDateTime.from(...) or OffsetTime.from(...)
  • parse {static factory method prefix} – Factory method to obtain an instance with provided CharSequence parameters, by parsing the content.example usage: LocalDate.parse(...) or OffsetDateTime.parse(...)
  • format {instance method prefix} – Formats the instance with provided formatter.example usage: localDate.format(formatter)
  • get {instance method prefix} – Return part of the state of the target temporal object.example usage: localDate.getDayOfWeek()
  • is {instance method prefix} – Queries a part of the state of the target temporal objectexample usage: localTime.isAfter(...)
  • with {instance method prefix} – Returns a copy of the immutable temporal object with a portion altered. Alternate for a set operation.example usage: offsetTime.withHour(...)
  • plus {instance method prefix} – Return a copy of the temporal object with an added time.example usage: localDate.plusWeeks(...)
  • minus {instance method prefix} – Return a copy of the temporal object with subtracted time.example usage: localTime.minusSeconds(...)
  • to {instance method prefix} – Convert the temporal object into a new temporal object of another type.example usage: localDateTime.toLocalDate(...)
  • at {instance method prefix} – Combine the temporal object into a new temporal object with supplied parameters.example usage: localDate.atTime(...)


The Code for the Kata is located at:

Your mission, should you choose to accept it, is to:

  1. setup the kata using your favorite IDE
  2. launch each JUnit test (Exercise1Test through Exercise5Test) and fix the tests, so all execute as instructed in the TODO above any commented lines.
  3. repeat as often as necessary to build muscle memory of using the awesome Date Time API

There are solutions, but looking at solutions may limit your learning different ways of solving the same problem.

Link to solutions:

I hope you found this post fun!

Happy coding!