Going Through “Functional Programming in Java”

I am starting to go through “Functional Programming in Java” by Venkat Subramaniam. I need to learn more about the stuff that is in JDK 8. We are still on JDK 6 where I work, but I think we will go to JDK 7 soon.

I think a lot of the new features in JDK 8 are similar to stuff that has been in Groovy for a long time.

There is an interesting paragraph in the Foreword by Brian Goetz:

The Java 8 design was heavily influenced by the core principles of functional programming: functions as values, immutability, and statelessness. We didn’t do this because functional programming is trendy or cool; we did this because programs that are expressed as stateless transformations on immutable data, rather than as modification of mutable data structures, tend to be easier to read and maintain and less error-prone, and to parallelize more gracefully.

You’re welcome.

2016-02-22 Update

I bought Living Clojure by Carin Meier, and I am working through the second half. It seems like a nice language and a nice book. I hope to use it professionally in the future.

I also like Groovy. As Dick Wall would say, I am all about the Groovy, man. I also made some progress on the Groovy Mail Server. I made some progress on authentication using SASL. I using SASL classes in the JDK, but I had to implement some Callback handler code myself. I had some help from Stack Overflow. In general I like Java the language, but sometimes I feel like the API designers like to make things more complex than necessary. Interfaces, extensions, listeners, factories, handlers, the knee bone instantiated the thigh bone, etc, etc, etc.

One thing I found out today is that when calling static methods on a class in the Groovy shell, you need to include the full package name for the class. I prefer the shell over the console, but I may have to switch. I wish the shell could run any Groovy code as-is. After finding out about setting interpeterMode to true in the shell, I thought the shell would run everything fine. Oh well.

I also made some small changes. I was not catching a possible exception, and the code was not closing connections. When I logged into the server it had almost maxed out.

You’re welcome.

Changing Immutable Objects

Recently someone at work someone sent me a link to an article saying that getters and setters are evil by a guy named Yego256. He has a few other interesting posts about immutable objects here and here. They can be added to the list I made of pages about immutable objects here.

Hopefully Grails 3 will utilize immutability.

It takes a shift in mindset to start using immutable objects. Plus, in Java (and Groovy) a lot of web frameworks don’t utilize them, so people are not too familiar with them.

One issue some developers have is: Many things in the world are mutable. How can you make “changes” to immutable objects?

One answer is that you can use the values you don’t want to change to populate a new immutable object, and your variable/field name points to a new immutable object.

(If you can think of a better way to explain this, let me know. It’s kind of confusing to say that an immutable object is referenced by a “variable name”.)

I will demonstrate this with Groovy (using the annotations EqualsAndHashCode, Immutable and ToString). I made a class to model a state in the USA. States do not change their names, abbreviations or year they joined the union. But many of them have changed their capital cities. So we will make an object, and change its capital city while keeping everything else the same.

Here is our class:

Now let’s look at using it in a Groovy shell. The first capital of Illinois was a town called Kaskaskia, which no longer exists. Then it moved to Vandalia (which does still exist) and finally to Springfield.

I will try to change a few fields to prove the objects are immutable, and I will call hashCode() to show that we are dealing with different objects.

So we used the existing values to make new objects. The JVM used the same variable name (“il”) to refer to different immutable objects.

Here is the code without the output:

2015-06-06_14.23.56 update: I now realize that in order to prove the objects were truly different objects, I should have called System.identityHashCode(il) instead.

You’re welcome.

Another Post on Automatic Getters and Setters

Recently I was looking at the Groovy section on DZone, and there was an article called Evil: Getters and Setters Where They’re Not Required (original here). He reiterates a lot of what I have been saying in my posts about why I am making the Groovy Validators.

I doubt that he and I are the only two that have noticed this issue. I have heard/read a lot of people complain about the verbosity of getters and setters (like we can get in Eclipse), and how much cleaner it is to use a language that will generate them for you (like Groovy and Ruby). Yet it is odd that so many times people gloss over the fact that these blind, automatic getters and setters essentially leave your variables wide open for just about anything. It seems like people hate verbosity more than they like data integrity.

Granted, I am a bit out of practice with Ruby, so it is possible that there is some sort of validation in the non-Rails Ruby space. And this is purely anecdotal. I just thought it was interesting.

UPDATE: I am making some progress on using the validation annotations with immutable objects. Hopefully Mr LaForge hasn’t closed that bug yet, and announcing my validators will bring me fame and fortune.

Notes From Austin JUG 2014-05-27

Here are the notes that I took at the May 27, 2014 meeting of the Austin JUG. There was only one presentation: Craig Walls on Spring Boot. He used quite a bit of Groovy during this presentation. You can find Craig Walls on Twitter and Github.

As always, the notes are presented pretty much as I wrote them.

Criticism of Spring: Lots of config
He says that Boot is “how we do Spring in 2014”
He goes over the evolution of Spring configuration.
Now you can make an app with no configuration.
Spring 4 can use Ruby config. Can I use Groovy?

Spring 4:
Takes away  boilerplate configuration
Heavily opinionated
Can run with Groovy at the command line
Can build to JAR or WAR

Spring Boot CLI: run Groovy apps from command line
Starts embedded Tomcat or Jetty
Heavily employs Spring Boot autoconfig

creates beans as needed,
resolves beans as needed (CLI)
adds imports (CLI)

Pre-baked POM files
Add a dependency in Maven or Gradle
Makes dependencies available

The Actuator:
Reasonable error pages
Endpoints for runtime metrics and info:
/beans: all beans
/env: Configuration properties
/trace: recent requests
/dump: thread details
/metrics: application metrics, gauge tells you how long it took for each request
/autoconfig: auto-configuration explanation
/info: by default has little, look it up. You can put something here
/health: this gives a few indicators, that your DB and services you call are running

He installed CLI
rest_hi returns “hi”

spring run app.groovy

That could be a tweet
Spring’s website is using Spring Boot
This could be good for Groovy


Spring will add the imports to Groovy compiler
He will use Thymeleaf (sp?) for UI
He will use H2 database

There is a Gradle spring-boot plugin

It would be great if the guy behind me would stop yawning

Spring Tool Suite has Boot Support

To secure actuators: Add Spring Security starter to your classpath
default: user/password

You can put stuff in application.properties or application.yaml
Go to Spring.io
Look at the Getting Started Guides, most of them use Spring Boot
Spring Boot requires Spring 4.0


Notes From Austin JUG 2014-04-22

Here are the notes that I took at the April 22, 2014 meeting of the Austin JUG. There were some lightning talks about Java 8. The main presentation was about GPU acceleration on the JVM.

As always, the notes are presented pretty much as I wrote them.

Nashorn: Javascript engine in JDK 8, javascript 5.1
Compiles javascript to bytecode
2x to 10x performance improvement, JSR 292, invoke dynamic
Scripting, command-line tools
Avatar.js is the competitor to Node.js
jjs is the interpreter that comes with JDK

NORM!!! (Norm Richards of the Austin Clojure group gave a talk)
jdeps is a new tool

Date/Time library
A pretty good one now. JodaTime
These objects are immutable
Time and Date APIs are pretty similar

Rob on JavaFX
JDK has a web browser inside it
Netbeans: It can convert inner classes to lambda expressions
Brian Williams raps ‘gin and juice’

GPU and Java 8
Gary Frost
Sumatra: GPU Acceleration of Java
GPUs are ideal for compute intensive, parallel tasks
Ideally nested loops where each pass through loop is independent of others

A kernel is a function

Aparapi was the next step
It was more natural, hid details of converting to OpenCL
It will execute code in a thread pool if you don’t have a GPU

Java 8 offers new APIs for dealing with ‘streams’ of data

For data parallel algorithms, we can request a parallel form of execution

HSA Foundation: GPU vendors

Aparapi could only use arrays of ints
HSA Sumatra can send Java objects to GPU
Sending stuff back and forth from CPU to GPU is the big challenge

Look at Sumatra and GRAAL OpenJDK repos

Not everything should go on GPU
Look for islands of parallel in sea of sequential


ActiveJDBC Presentation At Austin Groovy and Grails Group

I gave a presentation on ActiveJDBC last week at the Austin Groovy and Grails Group (@AustinGGUG on Twitter).

I gave two presentations before the main one.

I talked about the validation annotations I made for POGOs.

I talked about making a Gradle app that you can run from the Groovy shell, since that was how I was going to interface with ActiveJDBC.

The “main event” was the ActiveJDBC talk. Many of the people there knew about ORMs, either through Hibernate or GORM. I spent some time basically walking though some of the pages on the ActiveJDBC website to show the capabilities of ActiveJDBC. Some of the hightlights were the Getting Started page,  getters and settersrelationships, transactions, validators, optimistic locking, and some of the ways ActiveJDBC adheres to the ActiveRecord pattern, and the ways you can override the defaults.

All you need to do to get started is to extend the ActiveJDBC Model class, and you are good to go:

This magic works because of instrumentation, which honestly I had not heard of before I tried to get it to work with Groovy. My understanding is that instrumentation adds byte code to a Java class after it has been compiled. I think it is mostly used by profiling tools.

ActiveJDBC gives directions on how to do this with Ant and Maven. I had to do some digging to get it to work with Gradle. I was able to do it with help from some code used by the Griffon ActiveJDBC plugin and some code in Griffon itself.

I added a method called addURLIfNotPresent, which adds files to the classpath of a classloader:

This is called at the end of the compileGroovy step, thanks to the doLast() method:

I made a Grails app that had a few tables, and I had a Gradle app that used ActiveJDBC that pointed to the same database. I would make changes in one, and view them in the other, and go back and forth.

I also covered using Groovy metaprogramming to make ActiveJDBC more idiomatic in Groovy. ActiveJDBC does not provide getters and setters out of the box.

Here is how you would get the “name” field from a record in the People table:

Here is how you would set the name field:

The docs state you could write your own setter like this:

I showed how to use Groovy metaprogramming to do this automatically. I wrote something that will look at a model class, get a list of its fields, make getters and setters, and also make extra fields for particular data types (findBy$FIELD for varchar, findWhere$FIELDGreaterThan, findWhere$FIELDLessThan, findWhere$FIELDBetween for numbers). There are a lot of print statements for the presentation audience.

Some more complex queries were still kind of awkward in ActiveJDBC. To find the books written by authors from Scotland, you need to do this:

I just get the feeling there should be a cleaner way to do that.

You can find the code on github.

Validating Groovy Properties

A lot of Groovy developers rave about Groovy properties and automatically generated getters and setters, and how much better they are than Java beans.

Here is a Java bean:

Here is the same class written in Groovy:

The fields are made private by default in Groovy. A no-argument constructor is generated for you behind the scenes, as are getters and setters. So instead of

You could just write

That is nice, but there is one problem I always had with that: There is no validation on your setters. It is no different than having your fields public. What if I want my integer field to be between 10 and 100? What if I want my String to be at least 4 characters? In Groovy you could write your own setter, but that gets old fast. Grails has some constraints. Why not do something similar for Groovy?

There are a few projects out there for Java that use javax.validation.constraints.* annotations, like Hibernate Validator. I tried that, but I could not get it to work in Groovy. So I decided to do a little metaprogramming and write some annotations and try it myself.

Here is my integer annotation:

Using “Integer.MAX_VALUE” caused a compile error, so I decided to bite the bullet and hard-code it. Here is my String annotation:

All the integer annotation does is set minimum and maximum values, while the String annotation just looks at length.

Here is the class to process the annotations:

Here is the Book class with the annotations:

There is a static block that calls the class to process the annotations. I tried to use AST transformations, but after a while I just decided to do it in a static block.

The only catch is that you might want to set an integer field as a def type. If you leave it as “int”, the no-arg constructor will set it to 0. That is fine if that is your minimum value. I want the minimum to be 30. Having the field “def” allows for null values.

This works with the no-arg constructor as well as the map constructor. I have not tried it with the TupleConstructor annotation. I do not plan on adding a @Null annotation; AnnotationProcessor.process only processes one annotation per field, and I want to keep things simple.

I will add long, double and float. I don’t know what I will do about dates, since dates were overhauled in JDK 8. I might add some regex stuff to the String annotation.

The code is on github here. Let me know what you think.



Back In Austin

I am back from assignment in Boise.

I did go to a couple of meetings of Java Tech Boise (Twitter stream here). They had one meeting on Grails, and the next was a Grails hack night.

I explained my “user project“, making some small apps that have tests, security and they seemed to like the idea. I have not touched it much since I went out there, but I plan on getting back to it.

Going Back And Forth From Javadoc and Scaladoc

I looked at the Akka framework while going through Venkat’s book. One things I did not like about Akka is that it does not take too long until you work with Scala APIs besides Akka. Many of them do not have javadocs. So you have to read scaladoc to use them. It is not that hard, but it just seems like every time I look at scaladoc I have to learn it from scratch again.

So in this post I will try to explain scaladoc for Java developers.

Look at the javadoc for the Akka class UntypedActor, and then the scaladoc for UntypedActor. In the javadoc, we can see that akka.actor.UntypedActor inherits from java.lang.Object. In Scala, it inherits from scala.Any, which seems to be the Scala equivalent of java.lang.Object.

The Java class implements the akka.actor.Actor interface. The Scala class implements from the trait akka.actor.Actor. I do not know how a trait is different from a class or an interface. In the scaladoc, Actor and Any are pointed out at the same place in the scaladoc. In the javadoc, the interface and the parent class are in different spots in the file.

The first method in the javadoc is getContext(), which returns an UntypedActorContext. The methods are in a table, and the return values are all on the left side of the table.

getContext is not the first method listed in the scaladoc. I do not know exactly what “Type Members” are. The getContext() method is listed in the “Concrete Value Members” section. The section for getContext() is listed like this:

The javadoc has this: 

The difference is that in scaladoc the return value is listed after the name of the function. I am not too clear what “def” means.

Let’s look at a method that takes an argument. Let’s look at “onReceive”. This method is abstract.

Here is the method in the javadoc:

Here is the method in the scaladoc:

I think that “Unit” in Scala is like returning void in Java. In both cases, the methods take a parameter named “message”. In the javadoc, we see the parameter’s type and then its name. In the scaladoc, we see the parameter’s name, and then its type.

Lastly, I will look at a method that takes a couple of parameters for review. The method is preRestart().

Here is the method in javadoc:

Here is the method in scaladoc:

Every time I mention Scala on this blog, I mention that I do not like it. I thought I should mention it in this post just for consistency.