Calling a Superclass’ Method

A user on #java asked how one might invoke a method of a superclass recently, and received some general answers that more or less were right, but weren’t technically correct.

Maldivia pointed out that you would use method handles, which is sort of the gist of the (incorrect) answers given. The attempt was made to invoke the method via getDeclaredMethod(), which does not work.

The way to do it is to use MethodHandles.lookup() to get, well, a MethodHandles.Lookup object, which provides a way to get methods in the context of a class.

First, you’d get a MethodType reference, that refers to the _return value_ of the method. Then, you’d use findSpecial() – as one likely possibility – to find a method by name in a given class.

With that, you’d be able to invoke() the method.

Here’s code showing a superclass – Drink – and a main() in a subclass, Coffee, that has a bad call (the suggestion from the channel, tried and failing) and a good call, based on Maldivia’s suggestion, that actually does invoke Drink.toString() even when called from the context of a Coffee instance.

This is not expected to be held as an example of “what you should do” – for one thing, calling superclass’ methods outside of explicit access from a subclass is terrible design, in most cases, and for another, this is an example designed to run and not run properly or exhaustively. It’s simply a starting point.

import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;

class Drink {
    public String toString() {
        return "This is a Drink!";
    }

}

public class Coffee extends Drink {
    public String toString() {
        return "This is a Coffee!";
    }

    static void badCall(Coffee coffee) throws Throwable {
        var method = coffee
                .getClass()
                .getSuperclass()
                .getDeclaredMethod("toString", null);
        System.out.println(method);
        System.out.println(method.invoke(coffee, null));
        System.out.println(coffee);
    }

    static void goodCall(Coffee coffee) throws Throwable {
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        MethodType type = MethodType.methodType(String.class);
        var m = lookup.findSpecial(coffee
                        .getClass()
                        .getSuperclass(),
                "toString",
                type,
                coffee.getClass()
        );
        System.out.println(m);
        System.out.println(m.invoke(coffee));
    }

    public static void main(String[] args) throws Throwable {
        Coffee coffee = new Coffee();
        badCall(coffee);
        goodCall(coffee);
    }
}

Java Multiline Properties

A channel member asked if there was a way to do multiline properties in Java, and if so, how was leading whitespace handled?

The answers are, respectively, “yes,” and “pretty much as you’d hope it was.”

The multiline character for Java properties is, as one might expect from every other programming language’s usage, the \ character, and the Properties.load() method will trim all leading whitespace from the property value. Here’s a sample:

// This is Example.java
package example;

class Example {
  public static void main(String[] args) {
// sorry for the gross formatting here, page width! try(var in=Example
.class
.getResourceAsStream("/foo.properties")) { var properties=new Properties(); properties.load(in); System.out.println(properties.getProperty("foo")); } } }

And the properties file, foo.properties, which should be visible in the classpath at the root:

# this is /foo.properties
# note how "multiline" is indented more than the rest
foo = this \
  is \
  a \
    multiline \
  property

If this is run and the classpath is set properly, the output should be this is a multiline property. You can embed newlines with \n as desired as well, if you need those in the output.

We’ve officially moved to Libera.chat.

It’s official: ##java has moved to libera.chat, and along the way changed its name from ##java to #java.

We tried not to do this, we really did. But with a gap in trust between IRC channels and IRC staff, it was bound to happen.

So what did happen?

Well, we’ve been trying to refer people to the channel blog (this site!) regularly so they could keep up with what was going on, on a
fairly regular basis. We had already moved the bot to the Libera.chat
network, because of the gap in trust, but we tried to not violate the
intent on Freenode to directly advertise a “competing network.” But these notices were fairly rare, maybe five a day.

But around the time of one of the notices, a user pointed out the migration fairly explicitly, in support of another user’s question. This was entirely innocent of ill will, mind: one user on the channel supporting another.

A few hours later, one of the IRC staff changed the channel topic and removed access for the entire set of ops, claiming the channel was abandoned and had no controls in place. The ops who were in the channel (and watching, I might add) immediately protested, because this was an entirely unwarranted action almost literally out of nowhere.

To the staff’s “credit,” they offered to restore access once the ops protested the incursion. But… remember that gap in trust?

That gap in trust was because the ops were concerned that an arbitrary decision might be made concerning the channel, and that’s exactly what happened. The staff even used the innocent user supporting another user, as part of an active conversation, as justification. “This is spam!,” was the claim, “and the ops aren’t asserting control!” — and neither claim was true.

We now have access back for ##java on Freenode. However, we’ve set the channel to be moderated (i.e., +m), to prevent possible spam; if you want to be able to talk in ##java on Freenode, you’ll need to message an op to get it.

But the channel has moved to Libera.chat (again, see ##java), along with the most invested and active of its users, as well as the bot. If you want what Freenode ##java used to be, you should migrate.

(And if you really want to, you can still join ##java – it’ll redirect to #java.)

Announcement about Migration Away From Freenode

This is an account from one op, based on casual observation. It is offered without lots of logs, and hopefully without emotion; your mileage and understanding may differ, but this view seems to be pretty consistent with what we know, so chances are it’s close to true if not factually true.

So what happened to Freenode to make us consider migration?

Basically, an ircop sold the domain for freenode to a VPN provider, who then added ads to the website against the staff policy, and then…

The VPN provider (Andrew Lee) claimed that he owned Freenode itself (as opposed to just the domain) and threatened to sue the staff (which, as a set of volunteers, didn’t have money or organization to fight this) so he basically horned his way in… and the staff quit.

So he replaced them with 4chan ops, and changed a lot of longstanding freenode policies along the way. Among them were considerations for speech considered harmful (such as hate speech towards religions or specific people groups or other protected classes.) 4chan isn’t exactly a haven for values that Freenode ##java considers important; choosing stewards from 4chan doesn’t inspire confidence.

Here’s a tweet that mentions some of this. Also see the “WTF FAQ,” a page kept up by an op on a similar programming channel.

It’s fair to argue that free speech includes speech that some consider aggressive, but Freenode policy was made to reduce social friction, and had done so fairly successfully. Changing those rules without specific stimuli feels like a harbinger of a migration to more harmful practices, an IRC server where channels are subject to behavior against which there is no official defense at the network level.

Thus, Freenode’s core values are changing, literally, and that’s not necessarily a desired condition.

The new owner has done very little to engender trust during the transition, including what started the transition. When you start off with “Hey, I own the domain, so that means I own the service, right?,” that sends all kinds of messages to the community that you don’t want the community to hear.

What’s more, the new staff is incredibly defensive about owning the network, to the point where they’re forcibly taking over channels that don’t appreciate the possibility of being taken over. This hasn’t affected ##java or the directly-associated channels yet, but it has affected some of the channels that are implicitly associated.

So What Are We Gonna Do About It?

Well… we’re going to move the channel to a new network. We never really had any other recourse outside of the good graces and intent of Freenode staff, and that has always worked, because everyone’s been pretty benevolent. But with a wholesale change in staff, it’s hard to predict what the new staff’s intent is or how responsive they’ll be, and what we do know indicates a lot of defensive posturing and not a lot of effort to engender trust.

What we‘re doing is “moving away from Freenode,” to an alternative server. There are a few main candidates: EFNet (which has a #java already), Undernet (which … also has a #java), DALNet (which not only already has a #java, but underwent its own political chaos a few years ago and is under autocratic control), OFTC (which hosts the OpenJDK channel, among many others), and Libera.chat, which was created largely by the outgoing Freenode staff as a response to Andrew Lee taking over.

Of these, the latter seems the most palatable. So that’s literally what we’re doing: we’re moving to a new server.

This is not an act of defiance or even active defense; it’s just a move that seems wisest based on the level of trust we have for the new staff and organization behind Freenode. It’s done mostly to protect the idea behind ##java and its associated channels, and it’s done without malice.

We’re going to maintain a presence on Freenode as long as we’re able to, but the “main effort” for community development will be on the new server.

OpenJDK 11 on Fedora

Interesting in running the current version of Java (and its compiler) on your Fedora instance? It’s easy:

sudo dnf install java-11-openjdk-devel
sudo alternatives --config java # select Java 11
sudo alternatives --config javac # if necessary, select java 11

Note that this is still labeled as the “early access” version as of this writing – but the early access version is virtually identical to the released version.

The JavaChannel Podcast, Episode XVII (17)

The XVIIth podcast is live! … one wonders why the Roman Empire didn’t last much longer, doesn’t one. One also wonders how long one can refer to oneself in the whatever-person this is. (It’s… second-person? No, folks, it’s “third person.” English grammer fumbling and lesson over.)
In this podcast, we chase a few things: the discussion topic centers back around on Python vs. Java, and why one might encounter one over the other in certain situations.
We also jump down the gullets of a lot of varied topics, only some of which are Java, but most are at least sort-of relevant:

  • Expanded switch statements in java! … Stuff we can look forward to in Java 12. Java’s looking more and more like Kotlin all the time.
  • Hibernate with Kotlin – powered by Spring Boot describes, of all things, using Kotlin, Hibernate, and Spring Boot together. (The summary has a good laundry list of things to pay attention to.)
  • Another Java Enhancement Proposal: the Java Thread Sanitizer. It would provide a dynamic data race detector implementation for Java and native JNI code utilizing ThreadSanitizer in OpenJDK with interpreter and C1 support… and while it’s great that tools like this might exist, it’s fantastic that they’re apparently rarely needed if they show up twenty years after Java’s release.
  • The Left Hand of Equals is not strictly java related, but still interesting. It mostly centers around what it means for one object to be equal to another. I wonder if the channel blog should have recommended LINKS as well as books….
  • TomEE: Running with Systemd is a pretty fair walkthrough, and should be applicable to other app servers as well… that is, if appservers are still relevant in the world where microservice containers do be existin, mon.
  • https://brilliant.org/ is a kinda neat site for math and logic skills. If you use it, don’t forget to take the question surveys, because that’s how it’ll improve.
  • How to Be a Person Who Can Make a Damn Decision is the first of at least two annoying links for Andrew – this one says it’s “how to be a person who can” but actually mostly documents people being those kinds of people. We also have the resurgence of the podcast drinking game; take a shot whenever game theory is mentioned. However, the article doesn’t really have a lot of takeaways, apart from pointing out that the ability to make a decision quickly is probably a worthwhile skill to have.
  • OpenPDF 1.2.1 has been released. Joe didn’t even know about this library. No idea how useful it is; this release doesn’t look like a big one from the surface, but still: the more libraries out there, the merrier, right? (Unless they’re logging libraries.)
  • 7 Scientific Benefits of Reading Printed Books is the second annoying link for Andrew. It goes over some, uh, tenuous reasons print books are worth reading, some of which were taken exception to. Joe thought it was worth thinking about when e-books are ALL the rage for programming topics…
  • Other tangential topics:
    • https://hmijailblog.blogspot.com/2018/08/you-could-have-invented-lmax-disruptor.html I hated reading this, so I stopped.
    • https://perens.com/2018/08/22/new-intel-microcode-license-restriction-is-not-acceptable/ Apparently Intel was saying not to publish benchmarks, which is kinda gross. However, worth noting is that after the initial scraping of this article, Intel backed down and changed the police. Way to go, Bruce Perens!

The JavaChannel Podcast, vol 16

It’s only been six months, so it’s finally time for a new podcast. This one doesn’t even pretend to go over the mountains of killer content from ##java since the last podcast – it focuses on some of the more recent links, and that’s it. Well, apart from talking about the Java ecosystem a bit, especially in contrast with Python, an upstart language that’s making a lot of headway lately thanks to a giant upsurge in data science applications.

(A bit of irony: the very first paragraph in the podcast says it’s only been “four months” when it’s actually been six. Yikes.)

But there are some interesting links, and here are the ones the podcast focused on!

This was written with the new editor plugin for WordPress, called “Gutenberg.” It’s a lot like Medium.com’s editor. It’s effective for writing… unless you have any actual features you want in the text.

Gradle Properties

Gradle supports properties in builds just like Maven does, but the actual documentation and examples are harder to come by. This article will show you something that actually works.
In Maven, you typically have a dependencyManagement section that declares the dependencies with versions; I typically put the versions in a properties block so that they’re all located in a nice, handy, easy-to-manage place. See https://github.com/jottinger/ml/blob/master/pom.xml for a simple example; it’s not consistent with the property usage, but the idea should be clear. I have my versions all coalesced into an easy place to update them, and the changes propagate through the entire project.
Gradle examples rarely do anything like this. Therefore, for your edification, here’s a simple example:
gradle.properties:

aws_sdk_version=1.11.377
kotlin_version=1.2.50

build.gradle:

buildscript {
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
  }
}
apply plugin: 'java'
apply plugin: 'kotlin'
repositories {
    mavenCentral()
    jcenter()
}
dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
    compile "com.amazonaws:aws-java-sdk:$aws_sdk_version"
}
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
    kotlinOptions {
        jvmTarget = "1.8"
        javaParameters = true
    }
}

You can use a constraints block in the dependencies to do the same thing as dependencyManagement in Maven; that would look like this:

dependencies {
    constraints {
        implementation "com.amazonaws:aws-java-sdk:$aws_sdk_version"
    }
}

This would allow submodules (or this module) to use a simpler dependency declaration, leaving off the version, just like Maven can do:

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
    compile "com.amazonaws:aws-java-sdk"
}

If you don’t want to use gradle.properties, that’s doable too (as pointed out by channel member matsurago) – you can put it in the buildscript block, as so:

buildscript {
  ext.aws_sdk_version="1.11.377"
}

Article on java.time

Channel denizen (yes, that’s what we call people in the ##java channel, “denizens”) yawkat has published “An introduction to java.time,” an article to try to clear up some of the confusion around the time API in Java: things like LocalTime, OffsetTime, and the like. If you’re still using Date, this article is for you. Includes handy ways to convert between the time types, and is likely to grow further at need.

JavaChannel’s Interesting Links podcast, episode 15

Welcome to the fifteenth ##java podcast. Your hosts are Joseph Ottinger, dreamreal on the IRC channel, and Andrew Lombardi (kinabalu on IRC) from Mystic Coders.
As always, this podcast is basically interesting content pulled from various sources, and funneled through the ##java IRC channel on freenode. You can find the show notes at the channel’s website, at javachannel.org; you can find all of the podcasts using the tag (or even “category”) “podcast”, and each podcast is tagged with its own identifier, too, so you can find this one by searching for the tag “podcast-15”.
Discussion today centered around specifications: any good ones out there? What would good specifications look like?

  1. A few podcasts ago (podcast 11) we mentioned “resilience4j” – well, there’s also retry4j on github. It’s another library that offers retry semantics. retry4j’s semantics are really clean; maybe it’s me (dreamreal), but it seems more in line with what I’d expect a retry library to look like.

  2. From Youtube, we have a video showing how to use Graal in the JVM. Graal exposes JVMTI internals – which means that theoretically you could write a replacement for the just-in-time compiler, and change some fundamental ways of how Java works. Twitter is using Graal today, and the presenter says that it works fantastically; it’s also slotted to become standard in the next few revisions of Java, so we’ll have it probably next month or so.

  3. From the channel blog itself, user yawkat posted a way to cache HTTP results regardless of response with OkHttp. Why is this important? Well, if you’re testing a crawler, it’s handy to not slam the target server – even on results that should give things like “not found.” It’s written in Kotlin; the Java code would be trivial (and maybe we should post it as well just for the sake of example) but it’s still pretty handy.

  4. There’s also a Java Enhancement Proposal to allow launching single-source-code files like “java File.java”, and it automatically invokes javac; also with support for shebang, so we could be looking at Java scripting before too long. Some people already do this with scripts; they have something that pipes Java source into a temporary file, compiles it, and runs it, but this would be more standardized.

  5. We’ve seen a few posts about Hibernate on the channel lately, including some about projections (where an object isn’t represented as such in the data model but is constructed on-the-fly). Vlad Mihalcea actually had an appropriate post about caching such projections.

  6. We also have seen references lately to Project Sumatra – GPU enablement for the JVM, which seems abandoned – and then there’s this from the valhalla developer’s list: there IS a GPU exploitation thing being worked on. Who knows, we might see highly-GPU-enabled JVMs or libraries innate for Java before long.

  7. DZone has an article called “Java Phasers Made Simple” – basically a set of limited-scope locks. It’s really well done although quite long; hard for it to go into detail without being fairly long, though, so that’s okay. Worthwhile read.