New Regex Features in Java 9

I recently received my complimentary copy of the book “Java 9 Regular Expressions” from Anubhava Srivastava published by Packt. The book is a good tutorial and introduction to anyone who wants to learn what regular expressions are and start from scratch. Those who know how to use regex the book may still be interesting to reiterate the knowledge and to deepen into a more complex features like zero length assertions, back references and alikes.

In this article I will focus on the regular expression features that are specific to Java 9 and were not available in earlier version of the JDK. There is not many, though.

Java 9 Regular Expression Module

The JDK in Java 9 is split up into modules. One could rightfully expect that there is a new module for the regular expression handling packages and classes. Actually there is none. The module java.base is the default module on which all other modules depend on by default and thus the classes of the exported packages are always available in Java applications. The regular expression package java.util.regex is exported by this module. This makes the development a bit simpler: there is no need to explicitly ‘require’ a module if we want to use regular expressions in our code. It seems that regular expressions are so essential to Java that it got included in the base module.

Regular Expression Classes

The package java.util.regex contains the classes

  • MatchResult
  • Matcher
  • Pattern and
  • PatternSyntaxException

The only class that has changed API is Matcher.

Changes in class Matcher

The class Matcher adds five new methods. Four of those are overloaded version of already existing methods. These are:

  • appendReplacement
  • appendTail​
  • replaceAll​
  • replaceFirst​
  • results​

The first four exists in earlier versions and there is only change in the types of the arguments (after all that is what overloading means).

appendReplacement/Tail

In case of appendReplacement and appendTail the only difference is that the argument can also be a StringBuilder and not only StringBuffer. Considering that StringBuilder introduced in Java 1.5 something like 13 years ago nobody should say that this is an inconsiderate act.

It is interesting though how the currently online version of the API JDK documents the behaviour of appendReplacement for StringBuilder argument. The older, StringBuffer argumented method explicitly documents that the replacement string may contain named references that will be replaced by the corresponding group. The StringBuilder argumented version misses this. The documentation seems like copy/paste and then edited. The text replaces “buffer” to “builder” and alike and the text documenting the named reference feature is deleted.

I tried the functionality using Java 9 build160 and the outcome is the same for these two method versions. This should not be a surprise since the source code of the two methods is the same, a simple copy/paste in the JDK with the exception of the argument type.

Seems that you can use

    @Test
    public void testAppendReplacement() {

        Pattern p = Pattern.compile("cat(?<plural>z?s?)");
        //Pattern p = Pattern.compile("cat(z?s?)");
        Matcher m = p.matcher("one catz two cats in the yard");
        StringBuilder sb = new StringBuilder();
        while (m.find()) {
            m.appendReplacement(sb, "dog${plural}");
            //m.appendReplacement(sb, "dog$001");
        }
        m.appendTail(sb);
        String result = sb.toString();
        assertEquals("one dogz two dogs in the yard", result);
    }

both the commented lines or the line above each. The documentation, however speaks only about the numbered references.

replaceAll/First

This is also an “old” method that replaces matched groups with some new strings. The only difference between the old version and the new is how the replacement string is provided. In the old version the string was given as a String calculated before the method was invoked. In the new version the string is provided as a Function<MatchResult,String>. This function is invoked for each match result and the replacement string can be calculated on the fly.

Knowing that the class Function was introduced only 3 years ago in Java 8 the new use of it in regular expressions may be a little slap-dash. Or, perhaps … may be we should see this as a hint that ten years from now, when the class Fuction will be 13 years old, we will still have Java 9?

Lets dig a bit deeper into these two methods. (Actually only to replaceAll because replaceFirst is the same except that it replaces only the first matched group.) I tried to create some not absolutely intricate examples when such a use could be valuable.

The first sample is from the JDK documentation:

    @Test
    public void demoReplaceAllFunction() {
        Pattern pattern = Pattern.compile("dog");
        Matcher matcher = pattern.matcher("zzzdogzzzdogzzz");
        String result = matcher.replaceAll(mr -> mr.group().toUpperCase());
        assertEquals("zzzDOGzzzDOGzzz", result);
    }

It is not too complex and shows the functionality. The use of a lambda expression is absolutely adequate. I can not imagine a simpler way to uppercase the constant string literal “dog”. Perhaps only writing “DOG”. Okay I am just kidding. But really this example is too simple. It is okay for the documentation where anything more complex would distract the reader from the functionality of the documented method. Really: do not expect less intricate examples in a JavaDoc. It describes how to use the API and not why the API was created an designed that way.

But here and now we will look at some more complex examples. We want to replace in a string the # characters with the numbers 1, 2, 3 and so on. The string contains numbered items and in case we insert a new one into the string we do not want to renumber manually. Sometimes we group two items, in which case we write ## and then we just want to skip a serial number for the next #. Since we have a unit test the code describes the functionality better than I can put it into words:

    @Test
    public void countSampleReplaceAllFunction() {
        AtomicInteger counter = new AtomicInteger(0);
        Pattern pattern = Pattern.compile("#+");
        Matcher matcher = pattern.matcher("# first item\n" +
                "# second item\n" +
                "## third and fourth\n" +
                "## item 5 and 6\n" +
                "# item 7");
        String result = matcher.replaceAll(mr -> "" + counter.addAndGet(mr.group().length()));
        assertEquals("1 first item\n" +
                "2 second item\n" +
                "4 third and fourth\n" +
                "6 item 5 and 6\n" +
                "7 item 7", result);
    }

The lambda expression passed to replaceAll gets the counter and calculates the next value. If we used one # then it increases it by 1 if we used two, then it adds two to the counter and so on. Because a lambda expression can not change the value of a variable in the surrounding environment (the variable has to be effectively final) the counter can not be an int or Integer variable. We need an object that holds an int value and can be changed. AtomicInteger is exactly that even if we do not use the atomic feature of it.

The next example goes even further and does some mathematical calculation. It replaces any floating point formatted number in the string to the sine value of it. That way it corrects our sentence since sin(pi) is not even close to pi, which can not be precisely expressed here. It is rather close to zero:

    @Test
    public void calculateSampleReplaceAllFunction() {
        Pattern pattern = Pattern.compile("\\d+(?:\\.\\d+)?(?:[Ee][+-]?\\d{1,2})?");
        Matcher matcher = pattern.matcher("The sin(pi) is 3.1415926");
        String result = matcher.replaceAll(mr -> "" + (Math.sin(Double.parseDouble(mr.group()))));
        assertEquals("The sin(pi) is 5.3589793170057245E-8", result);
    }

We will also play around a bit with this calculation for the demonstration of the last method in our list, which is a brand new one in the Matcher class.

Stream results()

The new method results() returns a stream of the matching results. To be more precise it returns a Stream of MatchResult objects. In the example below we use it to collect any floating point formatted number from the string and print their sine value comma separated:

    @Test
    public void resultsTest() {
        Pattern pattern = Pattern.compile("\\d+(?:\\.\\d+)?(?:[Ee][+-]?\\d{1,2})?");
        Matcher matcher = pattern.matcher("Pi is around 3.1415926 and not 3.2 even in Indiana");
        String result = String.join(",",
                matcher
                        .results()
                        .map(mr -> "" + (Math.sin(Double.parseDouble(mr.group()))))
                        .collect(Collectors.toList()));
        assertEquals("5.3589793170057245E-8,-0.058374143427580086", result);
    }

Summary

The new regular expression methods introduced in the Java 9 JDK are not essentially different from what was already available. They are neat and handy and in some situation they may ease programming. There is nothing that could have not been introduced in earlier version. This is just the way of Java to make such changes to the JDK slow and well thought. After all that is why we love Java, don’t we?

The whole code copy paste from the IDE can be found and downloaded from the following gist

What is private in Java 9?

When doing interviews I experience that most of the candidates do not know what private modifier in Java really means. They know something about it that is enough for every day coding, but far from complete. It is not a problem. Knowing enough is, well… enough. But it is still interesting to know some of the inner working of Java. In some rare cases it may shed light on some details. If nothing else then it is entertaining .orElse(whyDoYouReadIt) ?


By the way: mentioning interviews is a good opportunity to write rants even if the statements and implications related to my person are, in my view, false. After all, my person is not important and distancing myself from the fact that it criticizes me I find that article interesting and the conclusions about the interviews are important and actually totally in line with my opinion.

This article is to describe some of the Java facts hopefully in a bit more readable way than reading the language standard.

So what is private?

private is an access modifier in Java. If you have a private member (method, field, inner or nested class or a nested interface) of a class it can only be used by code, which is in the same class. The interesting question is: what happens when there are more than one classes that the private method is in? How can it be in more than one class? In case there is a class that contains another class and there is a private method inside the inner/nested class then it is inside the inner/nested class and also in the top level class.

Can a private method inside an enclosed class called from the outer class? Can a code inside an enclosed class call a private method in the outer class? The answer is yes in both cases. The sample code

package javax0.package1;

class TopLevelClass {

  void topMethod(){
    NestedClass nc = new NestedClass();
    nc.method();
  }
  
  private int z;

  interface NestedInterface {
    default void method(){
      TopLevelClass tlc = new TopLevelClass();
      tlc.z++;
    }
  }

  static class NestedClass {
    private int k;

    private void method() {
      TopLevelClass tlc = new TopLevelClass();
      k = tlc.z;
    }
  }
}

clearly shows this situation: the nested class NestedClass and the nested interface NestedInterface both contain code that can access the outer class contained private field z. Similarly the top level class code can call the private method inside the nested class. The fact that this sample code does not actually perform anything reasonable is not important in this case.

If we compile this single source file we get three class files:

  1. TopLevelClass$NestedClass.class
  2. TopLevelClass$NestedInterface.class
  3. TopLevelClass.class

That is because the JVM does not know what is top level and what is nested. The JVM does not know anything about nested and top level classes. For JVM a class is just a class. A top level class if you insist. That is mainly because the Java language 1.0 did not have nested and inner classes and the JVM was designed according to that. When inner and nested classes were introduced in Java 1.1 the compilation was modified only instead of the JVM so that the inner and nested classes remained a language feature but not handled by the JVM directly.

How can the top level class access a private method in another class that was nested in the source code, but when it is compiled it is just another “top level” class. They are on the same level. If the accessibility were changed to public then we could also access it from other classes, but we can not. The compiler will not allow any other code in other classes to access the private method and even if we did some trick to overcome the compiler the generated class fill will make the JVM to throw an exception. Private in Java is private.

What really happens is that the compiler generates special getter and setter methods to get access to the field z.

Such a bridge method is created for every private field or method that is accessed from a different class inside the same top level class. If the private whatever is not accessed from the enclosing class then the method is not generated. If the field is only read then only the getter is generated, if it is only set from outside then only the setter is generated.

This is also an interesting failure believing that a private field (or whatever) is accessible only from within the same object. That is the usual way we use these members when we program, but if the code has a reference of another instance of the same type then through that reference we can access the private fields of the other object just as good as we can access “our own” fields. Is this a rare case? You may think because you rarely program it. But in reality it is extremely frequent: the IDE usually generated the code for us and that is why some developer does not think about that. Without this it would hardly be possible to code the equals(Object other) method of classes.

What about Java 9?

So far there is nothing specific to Java 9 in this article and these days every Java article should be about Java 9 (or 10 already?).

If we look at access control generally then we have to talk about JPMS, and there are many great articles about that. codeFx has a good list of articles about it. Stephen Colebourne has nice articles.

Soon you will be able even to buy books about Java module systems from different publishers. I am in a lucky position that I can already read one in draft from Packt as a reviewer and I love it. But JPMS does not change “private” on this level. Still there will be nested classes and inner classes and bridge methods exactly the same way as before.

The little difference is that Java 9 now has private methods inside interfaces. This means that now we should be prepared to have syntethic bridge methods not only in inner and nested classes, but also in interfaces.

Takeaway …

Sometimes the simplest things are not as simple as they seem. After all the whole IT technology, science, engineering is nothing else but a bunch of zeroes and ones. It is just that we have a lot of them. Really a lot. If there was something new to you in this article then it should tell you that there are areas in the Java language and in the JVM that you may be interested to examine a bit more. For example:

  • What is the difference between a nested and an inner class?
  • Can you have a nested interface inside a class and similarly can you have an inner interface inside a class?
  • What about classes or interfaces inside an interface? Can you have an inner class in an interface? How about a nested class?
  • Can you write a code using reflection that list all the methods a class has? Will it list the synthetic methods? What modifiers will it have?
  • When you compile an inner class it will have the compiled name Outer$Inner.class, which is a legitimate name. But what happens if there is a Outer$Inner.java source file? Figure it out!
  • The generated synthetic methods also have legitim names. What happens if you define a method with that name? Is it Java specification or implementation specific what you see?
  • How deep can you nest inner and nested classes and/or interfaces? Can a nested class contain an inner class? Can an inner class contain a nested class?
  • What is your guess, why there is no symbolic name in the JDK for the synthetic modifier? Why can the actual modifier value be the same as the value for volatile fields?
  • Can you have a static field, class or method inside a nested class?

The answer to those questions and the knowledge is not practical, I know. I have never ever seen any code or project where knowing that an inner class can not have a static field was giving any advantage. On the other hand thinking about these, getting the answers may give you some joy, like solving crosswords if that is your taste and a knowledge that still may be useful aiding to the understanding the technology in a way that we do not recognize. In some situation one person just finds a bug faster than other because she “feels” the technology. That is when you can not tell what was whispering the solution to your ears but something, knowledge like the above did. But it will only if you love to dig into those fine bits of the technology.

Last a trick question, even less practical than those above just for entertainment, if you like:

Puzzle

We know that it is not possible to have a static field inside an inner (not nested) class. Is it still possible to have a compiled class file generated by the Java compiler from an inner class that has a static method?

Process Handling in Java 9

Managing operating system processes in Java was a daunting task all times. The reason for that is the poor tooling and poor API that are available. To be honest that is not without reason: Java was not meant for the purpose. If you wanted to manage OS processes, you had the shell, perl script whatever you wanted. For larger applications that faced tasks that are more complex, you were supposed to program the issue in C or C++.

When you really had to manage processes from Java you had to create operating system dependent code. It was possible, you could query some environment variables and then you could implement different behavior depending on the operating system. This approach works until Java 8 but it has several drawbacks. Testing costs more, development is more complex. As Java became more and more nature and widespread the demand for this type of applications arose. We can clearly see for example that the question https://stackoverflow.com/questions/6356340/killing-a-process-using-java put up on StackOverflow in 2011 had more than hundred thousand of views. Some application and thus some developers need a solution for this problem, which is really a solution and not a workaround.

In this case providing an API in the JDK is a solution. It will not make process-handling OS independent. The operating systems differ and process handling is an area very much tied to the OS. The system dependent part of the code is however, moves to the JDK run time and Java development team tests it and not the applications separately. It eases the burden of testing on their side. In addition, the development becomes cheaper as the API is already there and we do not need to program it separately for BSD, OSX, Linux and Windows not to mention OpenVMS. Finally, the application may run faster. Again an example. If we needed the list of the running processes then we had to start an external process that dumps the list of the processes to the standard output. The output of this process had to be captured and analyzed as string. Now, with the advent of Java 9 we will have a simple call for that, which is implemented invoking the appropriate operating system call and it does not need the execution of a separate process, nor the parsing of a string output for an information that was already there just not available in Java.
To read about all the details of process handling of Java 9 you can read the documentation currently available on the URL http://download.java.net/java/jdk9/docs/api/overview-summary.html or you can soon read the book Mastering Java 9 from Packt https://www.packtpub.com/application-development/mastering-java-9 in which I wrote the chapter about process handling. In this article I will talk about some issues why we need the new class ProcessHandle It may not be that evident for some developers who are not that much experienced with operating system processes and how the operating system works.

ProcessHandle

In short an instance of ProcessHandle represents an operating system process. All operating systems identify alive processes using PIDs which is a TLA abbreviating Process Identifier. These are small (or not that small) integer numbers. Some operating system could use something else, like names, or some cryptic strings but they do not. There is no benefit and it happens that all of them use numbers to identify processes.

When we program in OO manner we abstract the problem so that it better explains the problem we model. There is a rule however, that we should not make our model more abstract than the problem itself. That just introduces unnecessary complexity to the application increasing cost. In this case it seems to be obvious (or rather oblivious) to use int to identify a process. If the operating system does not do it more abstract then why should we? Just because in Java everything is an object? (Btw: not true.)

The reason for that is there is no one to one match between PIDs and ProcessHandle instances. Let’s re-read the first two sentences of this section:

“… ProcessHandle represents an operating system process. All operating systems identify alive processes using PIDs …”

There is that little word “alive” in the second sentence and believe me that makes a difference. Being alive is very different from being dead, although we do not have firsthand direct comparison. A ProcessHandle instance may keep a reference to a process that is already wiped off from memory. Imagine the situation that you look at the list of the processes on Linux issuing the ‘ps –ef’ command and then you see that Tomcat is eating the CPU and consumes ever increasing memory most likely because the application you deployed has a bug looping. You decide to kill the process so you look at the pid displayed and issue the command ‘kill -9 666’ if the pid happens to be 666. By that time, the process has eaten up all the memory it could have from the OS and because you did not configure any swap file on the machine, the JVM disappears without trace. The kill process will complain that there is no process for the defined pid. It may also happen that the operating system has already started a totally different process that happen to have that pid. Has it ever happened? Now you shake your head and that is, because it has never happened in your practice. On Linux by default he maximum number that can be a pid is 32768. When will that ever wrap around? Actually not a long time, but usually not so far so that the pid is reused between issuing the ‘ps’ and ‘kill’ commands. And what happens if a small embedded system sets the /proc/sys/kernel/pid_max smaller. Say much smaller, like 16 that fits to four bits? It may not be a big problem when you issue the command interactively because you are there and if the system crashes you can restarts the process or the whole system if needed. You can do the corrective action if you made a “mistake”. Java application are not that intelligent and we should not have the chance even in an embedded system to kill a process we did not want to.

process handling based on pid

To handle that situation Java has the interface ProcessHandle. Instead of pids we have ProcessHandles. If we need the ProcessHandle of the currently running process (the JVM) then we can call the static method ProcessHandle::current (note that I used the nice Java 8 method handle notation). You can get the pid of the current process calling getPid() on that instance of ProcessHandle but after a while you will not do it. It is just an old habit wanting the pid of a process. You do not need it, when you have the handle.

When you have a process handle, say processHandle you can get a Stream calling processHandle.children(). This will list the immediate offspring processes. If you want a “transitive closure”, so you want to list not only the children but also the children of children and so on you have to call processHandle.descendants(). But what if you are really greedy and want to get a hand(le) on all processes. Then you should call the static method ProcessHandle::allProcesses.
Streams are famous for being populated lazy creating the next element only when needed. In case of process list it would lead to interesting results, therefore in this case the dataset backing the stream of processes is a snapshot created when one of the children(), descendants() or allProcesses() was called.
Now we have a handle to a process. What can we do with it?

We can processHandle.destroy() it and we can also call processHandle.destroyForcibly(). That is what everybody was wanting, as per the cited stack overflow article. We can also check if the process the handle is assigned to is still alive calling processHandle.isAlive(). You can also get access to the parent process handle calling processHandle.parent(). Note that not all processes have parent process. One of them never had and any other process may be orphan when the parent process has terminated. For this reason, the return value of this method is Optional. Java 9 has new features in the Optional class we well, but that is a different story, here we focus on the processes.

If the process is still alive but we want to wait for the termination of the process, we can do it in a modern, asynchronous way. We can get a CompletableFuture from the process handle calling processHandle.onExit() that will complete when the process terminates. Java 9 has new features in the CompletableFuture class as well, but that is a different story, here we focus on the processes. Do I repeat myself?

There is an interface inside the interface ProcessHandle called Info. We can get an instance of the information from the process handle calling processHandle.info(). Through this instance we can get access to the arguments as an optional string array, to the command line as an optional string, to the command as a string and to the user the process belongs to also as an optional string. We can also get information about when the process was started and also about the total CPU usage in form of optional Instant and optional Duration. These new classes were introduced in Java 8 and Java 9 has new features … Okay it starts to be boring.

Summary

What can we do with all these features? In the book I mention I created a simple process controlling application. A similar one I had to create around 2006 in perl. It starts processes as described in a configuration file and if any of them fails it restarts. But this is only one example. There are other scenarios where process handling can be handy. You want to fill in forms and convert them to PDF. To do that you start some word processor with command line parameters to do that. The tasks are queueing and they are started one after the other to keep reasonable performance you convert at most a configurable n document in n processes. If a process takes too long you kill it, send a message about it to the person who started the request to your conversion server and schedule it to run during the night or some less busy period.

We can develop such programs in Java without using external shell, python or perl scripts, and it simply makes the project simpler and cheaper.

Who needs Java modules after all ?

Oleg Selajev asked on twitter


Jigsaw questions for 1000. I as an X want JPMS modules. What is X if it’s not a platform developer?

My answer is that X is a human being (minus platform developers, because that was a condition). We all need module system to have safer code resulting in more reliable systems resulting in better performance in the business resulting in better economy resulting in human happiness. Perhaps I went a bit too far with the conclusions but the point is that module system is needed by everyone in the industry whether they’re aware of it or not. You will get it. First of all we should start with the ob(li)vious answer to the question.

Nicolai Parlog said: Every library developer whose types are not all public.

Very true. As a library developer I want to design my libraries so that I separate the API. I wan to separate the public interface from the implementation. This is what we, programmers call “encapsulation”. This is soooo good to encapsulate. We love to do it! We do it, because it is hilarious! We love it!

On the second thought though we do it because it is a tool to create reliable bug free (he he he) software.

It helps the code developers who use my code that encapsulates the internal state and implementation to write better code. It is a bit like raising children. I as parent disallow certain things that they would do. Eat lots of chocolate, stay up late and so on. And this is for their own good, even though they do not see or understand it at the moment. Later, of course, when they grow up and become parents themselves they will understand and do the same. It is not much different with library developers and library using programmers, except, perhaps, that programmers never grow up.

Similarly I as a library developer need JPMS for the sake of the developers who are going to use my code. My library will not be better or worse just because I encapsulate. (Side note: it will be better, but not because of the lessened number of bugs in it.) I can easily get the implication that I as a library developer want JPMS the least. Who cares if you, dear programmer, shoot off your testicles using my library? It is your responsibility to call only the public API and not some frequently modified internal class and method. Or is it?

Not really. It is also my responsibility to create a library that is easy to use and hard to make mistakes using it. This is what we call usability. This is where JPMS module system comes into the picture. Without JPMS I can document what packages are public and which are implementation specific. The contract between me and the users of the library is that they will not use the privates of my library and for this well behaviour I will keep the public part of the library stable so that they do not need to change their code from release to release. (Btw. has anyone ever realized how literally bloody this name, jPMS is? What the fly? PMS, really? Not to mention seeing currently all the cramps related to it: nomen est omen. It was not a lucky baptism.)

Let’s get back on our rail: why do we need module system for that? Developers are disciplined (he he he) people and they do not want to harm themselves. They should not and they will not use internal code of the library. That is not good for them on the long run and they are well aware of that. The catch is the long run thingy. In the long run we are all dead. There will be a point during the development, typically a few days before release date, when some of the internal APIs of a library just seem lucrative to be used. In some weird way those internal calls are just exactly what you need. You know that you are not supposed to use them, and there is a good, well-mannered solution, but that needs more time to develop. It is just that with the release date approaching you do not have the time to follow that pattern. Not to mention feeling proud about the “I can do that”, “how well I know these tools” thoughts, instead of feeling shame tampering with the parts of the library that are private.

That is where Java Module System comes into the picture. You will not be able to do shortcuts. You will sigh remembering the good old days when Java was open to the whole world whatever there was on the classloader (not to mention FORTRAN programming, am I right or just the contrary I am right?) but you will follow the rules, because it just will not work otherwise.

You think that you are not vulnerable to such vanity as using the internal parts of a library. Here is a test: did you recognize that I used the expression “internal APIs of a library”? If not, then feel ashamed but don’t admit it. No need. Java Module System will help to forget things that do not exist, like internal API. Nonsense. API is public. There is no such thing as internal API. The resulting code will be better, easier to maintain, less prone to library upgrades and thus cheaper at the bottom line.

In the long run, when we are all dead our offspring will create better code and having module level encapsulation will be an obvious thing, just like world peace will be that time.

So I need Java Module System, you need it, and everybody else needs it for a better world and for the sake of world peace.

Disclaimer: The author of the article no speaks English as naive language 😉

Hacking the IntegerCache in Java 9

Five years ago I published an article in Hungarian about how to alter the IntegerCahe in the JDK. Doing that is essentially hacking the Java run-time and there is no practical advantage unless while you develop the hacking code you get a better understanding how reflection works and how the Integer class is implemented.

The Integer class has a private nested class named IntegerCache that contains Integer objects for the int values -127 to 128. When the code has to box an int to Integer and the value is within this range then the run-time uses the cache instead of creating new Integer object. This is done for speed optimization reasons bearing in mind that the int values in programs are many times in this range (think about array indexing).

The side effect of this is that many times using the identity operator to compare two Integer objects may work so long as long the value is in the range. This is typically during unit test. In operational mode, when some of the values get bigger than 128 the code fails.

Hacking the IntegerCache using reflection may also lead to mysterious side effects and note that this is something that has its effect on the whole JVM. If a servlet redefines the small Integer cached values then all other servlets running in the same Tomcat under the same JVM will suffer.

There are other articles about it on the net from Lukas Eder

Add Some Entropy to Your JVM

and on the excellent blog site Sitepoint:

https://www.sitepoint.com/10-things-you-didnt-know-about-java/

Now that I started to play around with Java 9 early access version it came to my mind if I can do the same hacking with the new version of Java. Before starting that let’s refresh what we did with Java 8.

Lukas in his article displays a sample code, I copy here:

import java.lang.reflect.Field;
import java.util.Random;
 
public class Entropy {
  public static void main(String[] args) 
  throws Exception {
 
    // Extract the IntegerCache through reflection
    Class<?> clazz = Class.forName(
      "java.lang.Integer$IntegerCache");
    Field field = clazz.getDeclaredField("cache");
    field.setAccessible(true);
    Integer[] cache = (Integer[]) field.get(clazz);
 
    // Rewrite the Integer cache
    for (int i = 0; i < cache.length; i++) {
      cache[i] = new Integer(
        new Random().nextInt(cache.length));
    }
 
    // Prove randomness
    for (int i = 0; i < 10; i++) {
      System.out.println((Integer) i);
    }
  }
}

The code gets access to the IntegerCache via reflection and then fills the cache with random values. Naughty.

We can try to execute the same code in Java 9. Do not expect much fun though. Java 9 is more serious when somebody tries to violate it.

Exception in thread "main" java.lang.reflect.InaccessibleObjectException:
  Unable to make field static final java.lang.Integer[]
  java.lang.Integer$IntegerCache.cache
  accessible: module java.base does not "opens java.lang" to unnamed module @1bc6a36e

We get an exception that did not exist in Java 8. It says that object is not accessible because the module java.base, which is the part of the run-time of the JDK that is automatically imported by each Java program does not ‘opens’ (sic) the module to the unnamed module. It is thrown from the line where we try to set the field accessible.

The object we could easily access in Java 8 is not accessible any more, because the module system protects it. A code can only access fields, methods, and other things using reflection only if the class is in the same module, or if the module opens the package for reflective access for the world or for the module that needs the access. This is done in the module-info.java module definition file, like

module myModule {
    exports com.javax0.module.demo;
    opens com.javax0.module.demo;
}

The module java.base does not open itself for reflective access for us and especially not for the unnamed module, which is the code that we run. If we create a module for our code and name it then the error message will contain the name of that module.

Can we open the module programmatically? There is an addOpens method in the java.lang.reflect.Module module. Will it work?

Bad news for the hackers that it will not. It can only open a package in a module to another module if that package is already opened for the module calling this method. That way modules can pass on to other modules the right that they already have to access some packages in a reflective way but can not open things that are not open.

But the same time it is a good news. Java 9 is not so easily hackable like Java 8 was. At least this little hole is closed. It seems that Java starts to be professional grade and not to be a toy. Soon the time will come when we can migrate serious programs from RPG and COBOL to Java. (Sorry for the joke.)

UPDATE

After the article was republished on DZONE Peter Runge pointed out that the module system in this case still can be neglected using sun.misc.Unsafe class. Based on his suggestion the whole hack is here:

public class IntegerHack {

    public static void main(String[] args)
            throws Exception {
        // Extract the IntegerCache through reflection
        Class usf = Class.forName("sun.misc.Unsafe");
        Field unsafeField = usf.getDeclaredField("theUnsafe");
        unsafeField.setAccessible(true);
        sun.misc.Unsafe unsafe = (sun.misc.Unsafe)unsafeField.get(null);
        Class<?> clazz = Class.forName("java.lang.Integer$IntegerCache");
        Field field = clazz.getDeclaredField("cache");
        Integer[] cache = (Integer[])unsafe.getObject(unsafe.staticFieldBase(field), unsafe.staticFieldOffset(field));
        // Rewrite the Integer cache
        for (int i = 0; i < cache.length; i++) {
            cache[i] = new Integer(
                    new Random().nextInt(cache.length));
        }

        // Prove randomness
        for (int i = 0; i < 10; i++) {
            System.out.println((Integer) i);
        }
    }
}

How object initialization works

You may got used to my habit writing about something special, non trivial Java feature or usage. This time it will be a little different. At least for the start. This is a video tutorial about object initialization. We have an interface. Then we have an abstract class that implements the interface and then a concrete class that extends the abstract class. They do nothing except writing some strings to the console when they are executed so we can see what order they are executed. They have static initializer blocks, wherever it possible, non static initializer blocks and constructors.

BTW: can you tell, and be honest to yourself: is it allowed to have a static initializer block inside an interface? If you know java very well, but you can not answer that question with absolute certainty it will not hurt to watch this 9 minute tutorial.

And also stay tuned for the second part, when we get back to real javax0 style and let the hell loose.

While you wait for the second tutorial here is a puzzle:

How is it possible to have an instance of the Concrete class even though calling new Concrete() throws
Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class com.javax0.classinit.Concrete

If you could or could not find the answer to the puzzle watch the second part of the tutorial:

The source code is available from https://github.com/javax0-tutorials/object-initialization.

Java 9 by Example, My New Book

Sometime during the summer, I decided to write a book on Java programming after being suggested to do so by Packt. Java is a market leader and the number one programming language in the enterprise programming arena, and learning it is a good option for novice programmers. I recommend it to be learned as a main language after you got your fingers burnt with languages that have a simpler ecosystem, such as Python, Delphy, VisualBasic, and so on. Many advocate the death of Java but I do not share their opinion. There may be more modern and fancier languages, but for enterprise computing Java is still there and will be there, at least for the next 20 years. If you learn Java now, you learn an actively developing, stable, and reliable environment and tool, and you gain significant knowledge that you can convert to “jobs” in the coming decades.

An overview of the book

While designing the book, I decided to address those readers who already have some programming experience and want to learn Java as a main language, but apart from that, the book starts with the basics. Java 9 is especially good to get started since it has a REPL interpreter that compiles the Java code you type in, so you can try the features interactively. Throughout the book, you will see sample programs, first simple ones and then more complex examples, that are explained in detail. We focus not only on the language features, such as module support, functional programming, lambda expressions, and reactive interfaces, but also on programming style and program design. Continuously tutoring and coaching junior developers in my everyday work, I have gathered some experience on what is important and yet easily overlooked by beginners, and I have focused on these issues in the book.

The examples include sorting algorithms, explaining bubble and quick short, a game called Mastermind, a sample e-Commerce application, and a simple accounting application. The game, Mastermind, is followed in three chapters: the basic algorithm, a massively parallel algorithm (which is not trivial for this problem), and a web application where you can finally see the colors on the screen.

Finishing the book, the reader will have a comprehensive view of the language and will gain a stable basic knowledge to study further in the special directions he or she chooses.

Java 9 by Example Book Cover

How to get the book

This book is currently work in progress at the moment. You can however get an early access eBook from the Packt Website at https://www.packtpub.com/application-development/java-9-programming-example. Here you can see pre-reviewed drafts of the chapters as they are written, giving you access to content as early as possible. To know more about Early Access click on the below link. https://www.packtpub.com/books/info/packt/early-access