Showing posts with label jdk9. Show all posts
Showing posts with label jdk9. Show all posts

Monday, 6 October 2025

Optional.or

Was working on something, and I wanted to combine two optionals. In my case, I know that only one of the two will be present (or none), so combining them would be nice.

I'm not a big fan of using .ifPresent() and .get() combos. So, let's try streams.

Using streams, this looks something like:

Luckily we have a Optional.or() nowadays (Since Java 9), that I haven't used before.

It looks a lot better:

The awesome part (which is not shown in the example above) is that the or() accepts a Supplier, which means the Supplier will not be called if a value is present in the first Optional.

This is similar to the short-circuit evaluation1 present in the || operator of the common if-statement.

References

[1] Wikipedia - Short-circuit evaluation
https://en.wikipedia.org/wiki/Short-circuit_evaluation
[2] Baeldung - Guide To Java Optional
https://www.baeldung.com/java-optional
[3] Combine two Java Optionals
https://www.agalera.eu/combine-two-optionals/

Thursday, 16 January 2020

Do not use Optional in method parameters

The Java language authors have been quite frank that Optional was intended for use only as a return type, as a way to convey that a method may or may not return a value.

At work there are some cases where providing an Optional as a method parameter is a good idea, because QueryDSL has been configured to automatically return an empty resultset if the optional is not present.

But an Optional as a method parameter seems to be a disputed design choice1.

A lot of Java tooling complains about it (SonarLint, Findbugs, etc).

A lot of people mention that method overloading might be a better and clearer choice.

For example:

I took a stab at it:

Than I had to go and throw up, this is ugly as sin!

The best answer I found on StackOverflow3 without Java 9 so far:

Now this seems very interesting, but they needed to invent something better. And they did. In Java 9.

Optional.ifPresentOrElse​

Perhaps this is why in Java 92 there is a new method in the Optional class called ifPresentOrElse​.

References

[1] StackOverflow - Should Java 8 getters return optional type?
https://stackoverflow.com/questions/26327957/should-java-8-getters-return-optional-type
[2] JavaDoc - Optional (Java SE 9 & JDK 9)
https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html
[3] StackOverflow - Functional style of Java 8's Optional.ifPresent and if-not-Present?
https://stackoverflow.com/questions/23773024/functional-style-of-java-8s-optional-ifpresent-and-if-not-present
IntelliJ Idea Blog - Java 8 Top Tips
https://blog.jetbrains.com/idea/2016/07/java-8-top-tips/
SonarSource rules - "Optional" should not be used for parameters
https://rules.sonarsource.com/java/RSPEC-3553
DZone - Optional Method Parameters
https://dzone.com/articles/optional-method-parameters

Wednesday, 16 August 2017

NLJUG JCP Event - Java 9

There was a session on Java 9 on Friday, the 11th of August 2017 in Utrecht1. I went. JUG-members across the world would dive into as much detail as possible in a short timeframe during an online session. It was coordinated between the NLJUG2 (Dutch Java Users Group), CJUG3 (Chicago Java Users Group) and VJUG4 (Virtual Java Users Group). The JPoint5 company provided the facilities to follow the session together with other Java people, which was very kind of them.

The session was split up into different parts:
  1. "The Pragmatic Developer’s Guide to Java 9” by Simon Maple (vJUG)
  2. "Java 9 and the impact on Maven projects” by Robert Scholte (Apache Maven)
  3. "Java 9 and Performance increases" by Jonathan Ross (CJUG)
  4. "Java EE 8 update" by Josh Juneau (CJUG)

It was quite convenient that Jonathan Ross happened to be in the neighbourhood, as he's usually found in the neighbourhood of Chicago. Apparently he is also fluent in Dutch. The coincidences were staggering.

I shall recap in short order all the subjects that passed the agenda.
Jigsaw
What the module system in Java brings to the table is the enforcement of boundaries between code. To my mind this is what is necessary to keep us programmers from unheedinly increasing the entropy in the system beyond manageable limits. Classpath will be replaced with Modulepath. We will have to see how that will work out. There is a new module-info.java file for expressing the different modules and the current module uses them.
JShell
The REPL for Java.
ProcessHandler
The "top" or "ps" command for Java.
Optional
It was already introduced in Java 8, but now it has a new stream() function, which isn't eager like map but lazy like streams are supposed to be.
Ahead-Of-Time compilation (AOT)
Causing faster startup times of your java programs, instead of Just-In-Time compilation (JIT). A big requirement for Internet Of Things stuff. (You cannot wait 10 seconds for your doorbell to start up)
CompileControl
Programmer written hints for the compiler
Compact strings
All string objects use UTF-16, which basically fits into two bytes. The vast majority of the strings in applications can be expressed by just one byte using ISO-8859-1/Latin-1. So for most strings, a byte-array makes more sense than a char-array. A special indicator if a string is UTF-8, will be used to decide upon a byte-array or a char-array for storage. The indicator does not increase memory size due to memory alignment.
Indified strings
Concatenating strings using invokeDynamic instead of StringBuilder. This is a major performance boost.
VarHandlers
A way of using primitives without having to wrap them in Objects (for example AtomicInteger). It looks a bit ugly, but it's better than using com.sun.Unsafe.
_ as keyword
Probably a first step for JDK 10 and unused parameters in Lambdas
Private methods in interfaces
Nice.
Try-with-resources small change
You can now use effectively final variables from outside the try block in the try-with-resources statement
Java 5 will no longer be supported by Java 9 compiler
Time to upgrade your ancient programs!
Jonathan Ross knows a lot about performance. I guess he needs it in his job in the Financial Markets.

Robert Scholte talked about Maven being ready for Java 9, even though our applications might not be ready. Java 9 brings some different requirements to the table, because of modules.

One of the big issues that might arise is that those different requirements might make the uptake of Java 9 a great deal slower than was the case for Java 8. Especially if you do not need modules right now.

Josh Juneau talked about JEE 8, the integration Java 8, and the new and upcoming release of the reference implementation Glassfish (with Payara being very close behind).

Other events scheduled.
August 19th, 2017
Virtual Hackday on Java 9 - https://www.meetup.com/virtualJUG/events/240545774/
Monday, October 23, 2017
Brian Goetz at the CJUG - https://www.meetup.com/ChicagoJUG/events/242432217/

References

[1] NLJUG JCP Event together with CJUG and VirtualJUG
https://www.eventbrite.nl/e/tickets-nljug-jcp-event-ism-cjug-en-virtualjug-36387496983
[2] NLJUG
http://www.nljug.org/
[3] CJUG
https://www.meetup.com/ChicagoJUG/
[4] VJUG
https://virtualjug.com/
[5] JPoint
https://www.jpoint.nl/
Java EE Guardians
https://javaee-guardians.io/
Java Public House (Podcasts)
http://www.javapubhouse.com/

Thursday, 5 November 2015

J-Fall 2015

“Once you stop learning, you start dying.”
- Albert Einstein

I just got back from J-Fall 20151.

Seeing as the location had been changed from Nijkerk to Ede, I was unable to attend the Early Bird sessions, much to my dismay. I did manage to hitch a ride with a colleague of mine, but in the future, I will try and get a train. The connection seems to be quite good and once more there is a shuttle bus riding between the location (Cinemec) and the trainstation.

What with traffic (congestion) and my colleague sleeping late, I did miss the first keynote (The Experimental Enterprise - Keynote ING), only arriving at the destination at around 09:45.

The list of sessions I witnessed:

Pushing the limits of Continuous Delivery - Keynote Quintor

Provided by Rene Boere and Pascal Snippen

A fascinating view on what Quintor uses to provide Continuous Delivery (CD) using Docker, Apache Mesos, Marathon and Consul combined with HAProxy. The use of container ships to emphasise Docker was inspired and probably is starting to be overused by now. The microservices landscape is large and you can no longer see the forest for the trees, test environments are hard to set up, deployments are complex and timeconsuming.

Automation of Continuous Delivery is the answer.

Microservices for Mortals

Provided by Bert Ertman

This lecture could be construed as a big, huge, warning if you wish to use Microservices. It had a metaphore comparing coding practices with Italian food. The old way of coding compares to Spaghetti. Then SOA (Service Oriented Architecture) was introduced and those layered coding practices compare to Lasagna. Now the new Microservices compare more to Ravioli (tight independent containers of code bundled together) with sauce. The main idea behind microservices seems to be the ability to easy adapt to change. There is no hard definition on what microservices are. Apparently, microservices are small enough to just replace them with a completely new implementation, or just run 10 instances of one easily. They do away with a lot of items we are software developers have gotten used to:
  • synchronous programming models
  • ACID
  • code reuse
  • using abstractions
Instead, because of the characteristics of Microservices, you get:
  • asynchronous programming models
  • any constraints need to be taken care of at the application level
  • code duplication, each micro service is independent of the others, so code reuse between microservices doesn't make sense
  • separate data storages (one data storage per microservice)
  • passing data using websockets or binary protocols or messaging (REST is too much overhead, I don't want to even mention XML. It's all fine for a public API though.)
  • prefer conventions over abstractions (see code reuse)
If you have not been doing Devops, you cannot get started using Microservices without getting into a world of hurt.

Code for failure. Microservices are brittle, the distributed asynchronous models make them so. Design for this! Use fail early, use resilience patterns, use redundancy, etc.

10 Awesome Tips for Enterprise Javascript - Oracle

Provided by Geertjan Wielenga

This lecture provided an excellent overview of the current JavaScript landscape. I especially liked the fact that he mentioned that at the end of the lecture the landscape will probably already have changed. The JavaScript ecosystem is in that much flux.

Nowadays we have multiple devices, all with different screensizes requiring responsive design. One common factor in all these devices, is that all of them possess a browser. And the Single Page Application (SPA) is becoming the internet-enabled "application" of choice. Page navigation is irrelevant when it comes to Single Page Applications, yet for most Java-based Web Frameworks, page navigation is still an important part of their programming model.

Also, resist the hype. Apparently most managers make bad architecture decision based on hype. And you, as a developer, shouldn't want that.

For some applications, Javascript actually doesn't make any sense. The example provided was air traffic controllers. But different architectures can play different roles, even in those applications where Javascript doesn't make any sense. for example:
mobile apps
notifications
web apps
reporting to (upper) management
application itself
what users actually need and use in day-to-day work

NetBeans provided really nice point-and-click programming of the new HTML 5 components. The new HTML 5 components look very snazzy. Apparently, every new HTML 5 component is itself composed of sub-html-components, called the Shadow DOM and can therefore be styled appropriately. CSS has been split up into approximately 50 CSS modules. JavaScript can be used to avoid having to hide HTML using CSS, because hiding certain HTML components still makes the browser get the linked resources contained in those HTML components. Especially on mobiles this can make a huge difference.

In the Java world, the acronym WORA (Write Once Run Anywhere) is very well known. In the JavaScript world its WONTA (Write Once, Never Touch Again). The projects are so small, and the evolution of the Javascript ecosystem is so quick, it makes more sense to re-design and re-write everything from scratch when required.

Oracle has defined a Javascript framework, which is basically a bundling of common javascript libraries, into what is called the "Oracle Javascript Extention Toolkit"2.

“Javascript is the assembly language of the web.”

Then there's, if you really do not want to touch JavaScript with a ten-foot pole, the transpilers:
Dukescript
write Java, but also HTML and CSS. Combine those.
GWT/Vaadin
provides a Java backend similar to the Swing toolkit, and translates your code into HTML,CSS and JavaScript for the frontend.
Dart
separate programming language for the web/mobile/desktop.
Typescript
provides static typing to javascript, a sort of superset of JavaScript following ECMA recommendations that is transpiled to JavaScript
Coffeescript
programming language that translates to javascript

The Java renaissance continues - Keynote Oracle

Provided by Sharat Chander

A motivating speech on the fact that Java is still a success primarily because of the community. And a personal appeal to every person there to connect to at least two in the audience during the conference.

Devops - Are you walking or still talking? - Keynote Capgemini

Provided by Remko Reinders

A lecture on Devops, more importantly, what it takes for an organisation to become a success at Devops and what you can do to help your organisation and yourself to become a success as well.

“Most people will talk the talk. Few will walk the walk. Be amongst those few.”
- Steve Maraboli

“Software is eating up the world.”
- Marc Andreessen, Wall Street Journal

Building Asynchronous and Non-Blocking HTTP Applications with Ratpack

Provided by Hubert Klein Ikkink

My first introduction to Ratpack3, which I had never heard of before. It is a small webserver, that can be programmed using Java 8 and Groovy. It uses Netty for the HTTP IO, has a very small footprint, is very fast and is asynchronous. Does not provide JEE, does not follow the Servlet API and can be started by running a Jar file. Spock is used for testing.

If you want a quick webserver to dish out some REST stuff in a distributed environment, this is it. Check his webblog4 for more information.

Java modularity, life after Java 9 - Luminis

Provided by Sander Mak & Paul Bakker

“Good fences make good neighbours.”
- Proverb

An excellent talk about the upcoming Jigsaw in Java 9. It provides a faster startup and a smaller footprint, essential for small devices. It compared what little information there is about Jigsaw to the existing implementation of OSGI. Modules are allowed to talk to other modules only by the service contract each module provides. Modules are defined in a module-info.java file. The segregation is looked after by the VM itself and cannot be circumvented. Layers are used to prevent different versions of the same module interfering with each other. Versioning isn't really built into the new system. There is a linking tool called jlink and module maker tool called jmod. Jdebs can provide your program with which modules it needs. Identification of a module is done using a newly defined namespace specific for modules.

Classpath scanning for annotations is going to be a problem. It is going to have to be service-oriented in the future.

Especially application servers are going to need a major overhaul, as well as several annotation-crosscutting concerns frameworks as REST and JPA implementations.

See http://bit.ly/java9demo for more information.

References

[1] NLJUG - J-Fall 2015
http://www.nljug.org/jfall/2015/
[2] Oracle JavaScript Extention Toolkit
http://oraclejet.org
[3] Ratpack
https://ratpack.io/
[4] Mr Haki's Webblog
http://mrhaki.blogspot.nl/