"The Real World"

Erhvervsakademi Midtvest, Herning
@maxandersen
2024-03-05

redhat

Spørgsmål:

Kender du til Java?

Bruger du Java?

Er Java dødt?

Myths eller ?

  1. Ingen bruger Java!

  2. Java er langsomt!

  3. Java er omstændeligt!

  4. Java er svært at bruge!

Hvordan endte jeg her?

  • '94-'96 - Datamatiker i Ikast

  • '98-'00 - Datalog i Aalborg

  • '00-'04 - Softwareudvikler i Aarhus

  • '04-'17 - Open Source Udvikler i Neuchatel, Schweiz

  • '21-'24 - Open Source Udvikler i Pederstrup, Fyn

adaptabledinosaur
Bidraget til

Hibernate, JBoss AS/WildFly, JBoss Tools, Eclipse, Ceylon, OpenShift, Quarkus, …​

Arbejdet tæt sammen med

OpenJDK, GraalVM, Apache Camel, vert.x, KeyCloak, Microsoft VSCode, JetBrains, Docker, …​

Sideprojekter

JBang, Home Assistant, …​

Top Programmeringssprog

Java, Python

Myths eller ?

  1. Ingen bruger Java!

  2. Java er langsomt!

  3. Java er omstændeligt!

  4. Java er svært at bruge!

Myte #1: Ingen bruger Java!

"Every backend at ??? is basically a Java app…​.2800 Java applications…​microservices of a variety of sizes…​.1500 internal libraries" - February 2024

"Every backend at Netflix is basically a Java app…​.2800 Java applications…​microservices of a variety of sizes…​.1500 internal libraries" - February 2024

netflixjava

Andre Store ?

Microsoft, Amazon, Google, Twitter, LinkedIn, NASDAQ, Red Hat & IBM …​

Hvad med Startups ?

Spotify, Slack, Lyft, DoorDash, Instagram, BitPanda, Uber, Airbnb, …​real-time financial trading!

Danmark ?

Danske Bank, Maersk, Systematic, Netcompany, Trifork, LEGO, Bang & Olufsen, KMD, DSB, Rejseplanen, BankData, JYSK, TDC, Yousee, 3, Maersk, Grundfoss, Orested, Danfoss,Norlys,Skat og andre ministerier, Region Midt/Hoved, Schneider electric, …​

Hvad med Python? C#? Go? Rust? JavaScript?

  • Python - DataScience

  • Go/Rust - System/cloud-native

  • JavaScript - Frontend

  • C# - Windows/Backend

  • Java - Backend/Enterprise

Hvad siger Data ?

Myte #1: Ingen bruger Java!

Conclusion?

mythbusted

Myth #2: Java er Langsomt

1️⃣🐝🏎️

The One Billion Row Challenge

1brc

1️⃣🐝🏎️ Results

Baseline: 4m 49s

Result: 1.5s

192x faster

Hvordan?

  • Minimer IO

  • Divde & Conquer

  • Udnyt CPU arkitektur

  • Optimeret hukommelse (unsafe())

  • GraalVM native binary

Tidens trend

  • Build Time vs Run Time

  • JavaVM vs Native Image

  • Quarkus, Micronaut, Helidon, Spring Boot, …​

The classic way

buildruntime 1

The classic way

buildruntime 2

The classic way

buildruntime 3

The classic way

buildruntime 4

The classic way

buildruntime 5

The Quarkus Way

buildruntime 6

Myte #2: Java er Langsomt?

Conclusion?

mythbusted

Myte #3: Java er Omstændeligt

Java Hello World

public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello, World");
  }
}

Java 21 Hello World

void main() {
  System.out.println("Hello, World");
}

Java 22(?) Hello World

void main() {
  println("Hello, World");
}

Java Release Cadence

javaversionhistory

Pre-Java 5: File I/O

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {
    public static void main(String[] args) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("example.txt"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Java 7: try-with-resources

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import static java.lang.System.out;

public class ReadFile {
    public static void main(String[] args) {
        try (BufferedReader reader = new BufferedReader(
                new FileReader("example.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Java 8: Streams & Lambdas

import java.io.IOException;
import static java.nio.file.Files.lines;
import java.nio.file.Paths;
import java.util.stream.Stream;
import static java.lang.System.out;

public class ReadFile {
    public static void main(String[] args) {
        try (Stream<String> stream = lines(Paths.get("example.txt"))) {
            stream.forEach(out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Java 10: var

import java.io.IOException;
import static java.nio.file.Files.lines;
import java.nio.file.Paths;
import java.util.stream.Stream;
import static java.lang.System.out;

public class ReadFile {
    public static void main(String[] args) {
        try (var stream = lines(Paths.get("example.txt"))) {
            stream.forEach(out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Java 11: readString

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static java.nio.file.Files.readString;
import static java.lang.System.out;

public class ReadFile {
    public static void main(String[] args) {
        try {
            var content = readString(Path.of("example.txt"));
            out.println(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Java 21: unnamed class

import java.io.IOException;
import static java.nio.file.Path.of;
import static java.nio.file.Files.readString;
import static java.lang.System.out;

void main() {
    try {
        out.println(readString(of("example.txt")));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Java 22?: default imports

import static java.nio.file.Path.of;
import static java.nio.file.Files.readString;

void main() {
    try {
        println(readString(of("example.txt")));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Pre-Java 5: File I/O

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {
    public static void main(String[] args) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("example.txt"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Notable others

Java: Strenge

String navn = "John";
int alder = 55;
String indhold = "Hej " + navn + ",\n\n" +
                "Du er " + alder + " år gammel.\n\n" +
                "De bedste hilsner,\n" +
                "Max";

Java 17 & 21: Text Blocks & Templates

String navn = "John";
int alder = 55;
String indhold = STR."""
                Hej \{navn},

                Du er \{alder} år gammel.

                De bedste hilsner,
                Max
                """;

Data Classes

class Employee {

    private String firstName;
    private String lastName;
    private int Id;

    public Employee(String firstName, String lastName,
                    int Id)
    {

        this.firstName = firstName;
        this.lastName = lastName;
        this.Id = Id;
    }

    public void setFirstName(String firstName)
    {
        this.firstName = firstName;
    }

    public String getFirstName() { return firstName; }

    public void setLastName(String lasstName)
    {

        this.lastName = lastName;
    }

    public String getLastName() { return lastName; }

    public void setId(int Id) { this.Id = Id; }

    public int getId() { return Id; }

    public String toString()
    {

        return "Employee [firstName=" + firstName
            + ", lastName=" + lastName + ", Id=" + Id + "]";
    }

    @Override public int hashCode()
    {

        final int prime = 31;
        int result = 1;

        result = prime * result + Id;
        result = prime * result
                 + ((firstName == null)
                        ? 0
                        : firstName.hashCode());
        result
            = prime * result
              + ((lastName == null) ? 0
                                    : lastName.hashCode());

        return result;
    }

    @Override public boolean equals(Object obj)
    {

        if (this == obj)
            return true;

        if (obj == null)
            return false;

        if (getClass() != obj.getClass())
            return false;

        Employee other = (Employee)obj;

        if (Id != other.Id)
            return false;

        if (firstName == null) {
            if (other.firstName != null)
                return false;
        }

        else if (!firstName.equals(other.firstName))
            return false;

        if (lastName == null) {
            if (other.lastName != null)
                return false;
        }

        else if (!lastName.equals(other.lastName))
            return false;

        return true;
    }
}

Java 14: Records

public record Employee(int id,
                       String firstName,
                       String lastName) {}

Hvad er der sket?

  • 30 års "bagage" som verdens mest populære sprog

  • Skoler/Universiteter opdaterer ikke hvad der virker

Myte #3: Java er Omstændeligt?

Conclusion?

mythbusted

Myte #4: Java er Svært at Bruge

Dagens enterprise Java

  • javac, java, jar, war, ear, …​

  • Maven/Gradle ?

  • JavaEE/Jakarta & Spring Boot ?

  • IntelliJ/Eclipse/VSCode ?

Getting Started with Java

The JBang Way

Installation

curl -Ls https://sh.jbang.dev | bash -s - app setup
  • Downloads and configure JBang

  • If no Java found, downloads Java 11

Everywhere

$ jbang -c 'println("Hello World")'
Hello World
$ jbang -c 'println("Hello "  + args[0])' Universe
Hello Universe
  • -c evaluates code via JShell

  • Handles user arguments

  • No files to create

  • No public static class main

$ jbang -i
|  Welcome to JShell -- Version 11.0.15
|  For an introduction type: /help intro

jshell> println("Hello!")
Hello

Any Java

$ jbang --java 17 -i
WARNING: Using incubator modules: jdk.incubator.vector, jdk.incubator.foreign
|  Welcome to JShell -- Version 17
|  For an introduction type: /help intro

jshell>

Files

$ jbang init hello.java
[jbang] File initialized. You can now run it with
'jbang hello.java' or edit it using
'jbang edit --open=[editor] hello.java' where [editor]
is your editor or IDE, e.g. 'eclipse'
$ jbang hello.java
[jbang] Building jar...
Hello World
$ ./hello.Java
Hello World

Init w/Templates

$ jbang init -t cli app.java
[jbang] File initialized. You can now run it with
'jbang app.java' or edit it using
'jbang edit --open=[editor] app.java' where [editor]
is your editor or IDE, e.g. 'eclipse'

app.java

 ///usr/bin/env jbang "$0" "$@" ; exit $?
 //DEPS info.picocli:picocli:4.5.0

import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Parameters;

import java.util.concurrent.Callable;

@Command(name = "app", mixinStandardHelpOptions = true, version = "app 0.1",
        description = "app made with jbang")
class app implements Callable<Integer> {

    @Parameters(index = "0", description = "The greeting to print", defaultValue = "World!")
    private String greeting;

    public static void main(String... args) {
        int exitCode = new CommandLine(new app()).execute(args);
        System.exit(exitCode);
    }

    @Override
    public Integer call() throws Exception { // your business logic goes here...
        System.out.println("Hello " + greeting);
        return 0;
    }
}

Run with Dependencies

$ ./app.java
[jbang] Resolving dependencies...
[jbang] info.picocli:picocli:jar:4.5.0
Done
[jbang] Dependencies resolved
[jbang] Building jar...
Hello World

Cached Run

$ ./app.java --help
Usage: app [-hV] <greeting>
app made with jbang
      <greeting>   The greeting to print
  -h, --help       Show this help message and exit.
  -V, --version    Print version information and exit.

Editing

The JBang Way

The Simplest Way

jbang edit app.java
[jbang] You requested to open default editor but no default
editor configured.

jbang can download and configure a visual studio code (VSCodium)
with Java support to use

Do you want to

(1) Download and run VSCodium
(2) Use 'code'
(3) Use 'eclipse'
(4) Use 'idea'
(0) Cancel

Anywhere

Direct IDE Support

IntelliJ intellij

Eclipse and Visual Studio Code too!

Debugging

The JBang Way

$ jbang --debug app.java
Listening for transport dt_socket at address: 4004

What just happened?

The JBang Way

In 5 min or less…​

We started creating, then edited, ran and debugged Java

  • Without java or javac

  • Witout mvn or gradle

  • No vscode, eclipse, intellij Install

  • Just jbang

Exploring…​

The JBang Way

[background

One liner scripts

$ cat 5letterwords.txt | jbang -c \
  'lines().filter(s->s.contains("dog")).forEach(p->println(p))'

Microservices w/Quarkus

$ jbang init -t qrest myservice.java
$ ./myservice.java
./myservice.java
[jbang] Resolving dependencies...
[jbang] Artifacts used for dependency management:
         io.quarkus:quarkus-bom:pom:3.8.1
[jbang] io.quarkus:quarkus-resteasy-reactive
Done
[jbang] Dependencies resolved
[jbang] Building jar...
[jbang] Post build with io.quarkus.launcher.JBangIntegration
May 04, 2022 9:30:43 PM org.jboss.threads.Version <clinit>
INFO: JBoss Threads version 3.2.0.Final
May 04, 2022 9:30:44 PM io.quarkus.deployment.QuarkusAugmentor run
INFO: Quarkus augmentation completed in 999ms
__  ____  __  _____   ___  __ ____  ______
 --/ __ \/ / / / _ | / _ \/ //_/ / / / __/
 -/ /_/ / /_/ / __ |/ , _/ ,< / /_/ /\ \
--\___\_\____/_/ |_/_/|_/_/|_|\____/___/
2022-05-04 21:30:45,453 INFO  [io.quarkus] (main) Quarkus 2.8.0.Final on JVM started in 0.839s. Listening on: http://0.0.0.0:8080
2022-05-04 21:30:45,488 INFO  [io.quarkus] (main) Profile prod activated.
2022-05-04 21:30:45,488 INFO  [io.quarkus] (main) Installed features: [cdi, resteasy]

myservice.java

///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS io.quarkus:quarkus-bom:${quarkus.version:3.8.0}@pom
//DEPS io.quarkus:quarkus-resteasy
//JAVAC_OPTIONS -parameters
//FILES resources/index.html=index.html
//SOURCES **.java

import io.quarkus.runtime.Quarkus;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;

@Path("/hello")
@ApplicationScoped
public class myservice {
    @GET
    public String sayHello() {
        return "Hello from Quarkus with jbang.dev";
    }
}

Run All The Things

$ jbang -c "Hello"
$ jbang app.java
$ jbang demo.jsh
$ jbang app.jar
$ jbang org.jreleaser:jreleaser:1.0.0
$ jbang https://github.com/jbangdev/jbang/../examples/inetTest.java
$ jbang https://jbang.dev

JBang AppStore

faker.jsh Example

//DEPS com.github.javafaker:javafaker:1.0.2

import com.github.javafaker.Faker;

Faker faker = new Faker();
$ jbang -s faker@jbangdev -c \
  'Stream.generate(faker.name()::fullName).filter(s->s.contains("Angie")).forEach(s -> println("Awesome " + s))'

Install All The Things

$ jbang app install -n myapp https://.../a.jar
$ jbang app install quarkus@quarkusio
$ quarkus
quarkus

Quarkus CLI version 2.8.2.Final

Create Quarkus projects with Maven, Gradle, or JBang.
Manage extensions and source registries.

Create: quarkus create
Iterate: quarkus dev
Build and test: quarkus build

Find more information at https://quarkus.io
If you have questions, check https://github.com/quarkusio/quarkus/discussions


Usage: quarkus [-ehv] [--verbose] [-D=<String=String>]... [COMMAND]
Options:

Conclusion

  • JBang is the best way to Get started with Java

  • JBang let you write anything; from one-liners…​

  • …​to full-fledged Java microservices

  • JBang lets you run and install Java apps

  • JBang has an appstore

JBang is Java

Hvad med Enterprise Java?

  • Quarkus demo

Myte #4: Java er Svært at Bruge?

Conclusion?

mythbusted

Pause

Hands-on

Hands-on beyond basics

Q&A og Afslutning

  • Java forbliver relevant, effektiv, moderne og brugervenlig

  • Det er helt i orden at udforske andet, men…​

  • Undervurder ikke Java’s potentiale ;)