- From Parks Computing, a short word of advice in “On Recruiting” for the movers and shakers (and those who want to be movers and shakers): “The quality of your company’s software will never exceed the quality of your company’s software developers.”
- DZone is back with a few interesting posts: “OpenJDK – Is Now the Time?” starts by wondering is OpenJDK is reaching critical mass to the point where it should be considered instead of the standard Oracle JDK. It’s an odd post.
- It points out that if Google had used OpenJDK instead of Oracle’s libraries, the lawsuit might not have happened (Editor’s note: it might have!). This is a good point.
- It says that the deployment options might open up, with standard package management instead of a custom update process specific to Java. This is also a good point.
- It points out that OpenJDK’s performance and scalability is the same as the Oracle JDK. This is… not a good point. The codebases are the same (they’re routinely synchronized: code in one will be in the other eventually.) Oracle’s JDK is effectively OpenJDK with some closed-source libraries, so Oracle’s JVM can write JPEGs natively (and some other features like that.)
- It also points out community improvements to OpenJDK – “As open source developer’s continue to provide insight into the source code, it is likely that OpenJDK could begin to outperform the version released by Oracle.” Um… since the codebases are the same, that’s not likely to happen much at all.
- From ##java, cheeser had a beautiful expression of reference equivalence. Someone was asking about how two references (
AandB) pointing to the same object work – cheeser said, “If B is your *name*, A would be a nickname. Both of them mean you so anything said to either name or nickname both go to you.“ - “Fix PATH environment variable for IntelliJ IDEA on Mac OS X” describes a way for OSX users to provide the OS’s PATH to the popular IDE. It turns out that programs installed via
brewaren’t necessarily available to IDEA unless you start IDEA from the shell – which few do. It’s easy to fix; this post shows you how. - Another from DZone – they’re on fire! – Per-Ã…ke Minborg posted “Overview of Java’s Escape Analysis“, which discusses what escape analysis is (it’s a way of determining the visibility of an object) and what it means for performance. (If an object isn’t used outside of a method or a block, it can be allocated on the stack rather than on the JVM heap – and as fast as the heap can be in Java, the stack is much faster.)
- Pippo is a new, very small microframework based on services. The example looks … easy enough; take a look, see what you think.
- Yet one more from DZone: Exceptions in Java: You’re (Probably) Doing It Wrong advocates the use of
RuntimeExceptionto get rid of those peskythrowsclauses and forcedtry/catchblocks in your Java code. It’s an argument Spring advocates, and checked exceptions aren’t part of languages like Scala… but I personally find the over-reliance on unchecked exceptions to be terrible. The core argument against check exceptions from the article: “The old argument is that (the use of checked exceptions) “forces†developers to handle exceptions properly. Anyone on a real code base knows that this does not happen, and Exceptions are routinely ignored, or printed out and then ignored. This isn’t some sign of a terrible developer; it is such a common occurrence that it is a sign that checked Exceptions are broken.” Except no, it’s such a common occurrence that it’s a sign that developers are terrible. This article was so terrible that I’ll probably write up a better response as soon as I get some time.
Interesting Links, 5 Feb 2016
- “O Java EE 7 Application Servers, Where Art Thou?” is a humorously-titled summary of the state of Java EE 7 deployment options, covering the full and web profiles for Java EE 7. It’s the sort of thing one wants to know, honestly: great job, Antonio.
- From Stack Overflow, “How to get started with Akka streams?” is a Scala question, not a Java one, but Akka has a Java implementation as well. The first answer (accepted, upvoted) is a fantastic explanation. I may port it to pure Java just for example’s sake…
- From our friends at DZone, Orson Charts 1.5 is Open Source announces that Orson Charts 1.5 has been released, and it’s available under the GPLv3 (a commercial license is available for people who don’t want the restrictions of the GPL). It’s a 3D charting library, not a 2D charting library, and they say if you need 2D charts, you should use JFreeChart – Orson Charts looks great on first impressions, though. (It’s worth noting that apparently both Orson Charts and JFreeChart were from the same author.)
- More from DZone: Application Security for Java Developers is a summary of security concerns. It’s really more of a short “have you thought of this?” post – useful, but not very deep.
The case of EnumSet
A few days ago ##java happened to discuss sets and bit patterns and things like that, I happened to mention EnumSet and that I find it useful. The rest of the gang wanted to know how it actually measures up, so this is a short evaluation of how EnumSet stacks up for some operations. We are going to look at a few different things.
EnumSet classes
There are two different versions of EnumSet:
* RegularEnumSet when the enum has less than 64 values
* JumboEnumSet used when the enum has more than 64 values
Looking at the code, it is easy to see that RegularEnumSet stores the bit pattern in one long and that JumboEnumSet uses a long[]. This of course means that JumboEnumSets are quite a lot more expensive, both in memory usage and cpu usage (at least one extra level of memory access).
Memory usage
I created a little program to just hold one million Sets with a few values in each of them.
Note: the enumproject.zip was built by your editor, not your author – any problems with it are the fault of dreamreal and not ernimril. Note that the project is mostly for source reference and not actually running the benchmark.
List<Set<Token>> tokens = new ArrayList<> ();
for (int i = 0; i < 1_000_000; i++) {
Set<Token> s = new HashSet<> ();
s.add (Token.LF);
s.add (Token.CR);
s.add (Token.CRLF);
tokens.add (s);
}
Heap memory usage for this program was about 250 MB according to JVisualVM.
Changing the new HashSet<> (); into EnumSet.noneOf (Token.class); we instead get 70 MB of heap memory usage.
Using the SmallEnum instead causes the HashSet to still use about 250MB, but drops the EnumSet usage down to 39 MB. I find it quite nice to save that much memory.
CPU performance
I constructed two simple tests, shown below, that calls a few methods on a Set that is either EnumSet or HashSet, depending on run. The enums have a few Sets that contain different allocations of the enum and the isX-methods only do return xSet.contains(this);
@Benchmark
public void testRegular() throws InterruptedException {
SmallEnum s = SmallEnum.A;
boolean isA = s.isA ();
boolean isB = s.isB ();
boolean isC = s.isC ();
boolean res = isA | isB | isC;
}
@Benchmark
public void testJumbo() throws InterruptedException {
Token t = Token.WHITESPACE;
boolean isWhitespace = t.isWhitespace ();
boolean isIdentifier = t.isIdentifier ();
boolean isKeyword = t.isKeyword ();
boolean isLiteral = t.isLiteral ();
boolean isSeparator = t.isSeparator ();
boolean isOperator = t.isOperator ();
boolean isBitOrShiftOperator = t.isBitOrShiftOperator ();
boolean res =
isWhitespace | isIdentifier | isKeyword | isLiteral |
isSeparator | isOperator | isBitOrShiftOperator;
}
I did the benchmarking using jmh in order to find out how fast this is.
Using HashSet:
Benchmark Mode Cnt Score Error Units
EnumSetBenchmark.testJumbo thrpt 20 46787074.985 ± 2373288.078 ops/s
EnumSetBenchmark.testRegular thrpt 20 124474882.016 ± 2165015.166 ops/s
Using EnumSet:
Benchmark Mode Cnt Score Error Units
EnumSetBenchmark.testJumbo thrpt 20 112456096.790 ± 320582.588 ops/s
EnumSetBenchmark.testRegular thrpt 20 563668720.636 ± 594323.541 ops/s
This is of course quite a silly test and one can argue that it does not do very much useful, but it still gives us quite a good indication that performance gains are there. Using EnumSet is 2.4 times faster for jumbo enums, but 4.5 times faster for small (regular) enums for this kind of operation.
I do not claim that your usage will notice the same speedup, but it might be worth checking out.
Final thoughts
Does it really matter if you use EnumSet or Set? In most cases: no, the enum will only be one field and not part of memory usage or cpu consumption, but depending on your use case it can be a nice memory saver while also being faster. I recommend that you use it.
ZeroTurnaround's Developer Productivity Report
ZeroTurnaround has issued their latest developer productivity survey – if enough people take it, they’re giving money to Devoxx4Kids.
It’s an interesting survey, done very well – probably the best execution of such a survey as I’ve ever seen (and I’ve seen a lot). Check it out, let’s get Devoxx4Kids that donation (and/or join ourselves).
Interesting Links, 1 Feb 2016
Editor’s note before we get to the links: I’ve been trying to keep the links’ length down to a manageable four or five, so the frequency’s been higher than I might otherwise have desired (roughly every two or three days). I’m going to try a longer list of interesting links, and move the frequency down – we’ll see if that’s useful and palatable. The problem is that ##java (and the Java community overall) just has a lot of interesting, relevant content that’s worth keeping! (Keep it up, guys. “Too much interesting stuff” is a good problem to have.)
- WildFly 10 has been released. This is the latest version of the open source (community-supported) JBoss Application Server; it’s fully Java EE 7, and requires Java 8. Very cool stuff, congratulations to the WildFly team.
- Neo4J has released milestone 1 of their object/graph mapping library’s second version. (Read it with me: “Neo4J has released OGM 2.0 m1.” Much simpler that way.) It sounds promising, especially since they seem to have straightened out the connection process to Neo4J instances such that both embedded and remote instances have similar capabilities.
- “Implied Readability” uses readability as a term to address transitive dependencies in Java 9, more or less, and shows how a module can export visibility of a dependency to other modules. As stated: Java 9, not Java 8, so it’s a new feature – but it looks a little like how OSGi exports visibility rules. It might be really relevant as time goes on and Java 9 gets closer. (It’s based off of information in “Programming with Modularity and Project Jigsaw. A Tutorial Using the Latest Early Access Build” published on InfoQ, so there may be more interesting stuff in that article.)
- “How we accidentally doubled our JDBC traffic with Hibernate” discusses an obvious issue (doubling JDBC traffic!), found when Hibernate logging was set to
WARN– because Hibernate then re-executes every query in order to show the warnings associated with the query in question. The warnings can be useful, to be sure, but be wary! - PNG encoding from Java’s ImageIO can be slow, according to one ##java op. He said that he used ObjectPlanet‘s PngEncoder and got much better performance.
- As an update to the process by which one can examine request headers (mentioned in “Interesting Links, 22 Jan 2016“) a ##java user mentioned RequestBin, which allows you to build a URL and issue requests against it, to examine the actual traffic data.
- Moving to a Plugin-Free Web – by Oracle – says it point blank: “Oracle plans to deprecate the Java browser plugin in JDK 9. This technology will be removed from the Oracle JDK and JRE in a future Java SE release.” This makes sense – browsers are ignoring the java plugin (and should). If you’re still doing applets, stop. Oracle has spoken, and the technology is going away. (Now if we could get Oracle to get rid of
Vectorsomehow…) - ZeroTurnaround – who gave the world JRebel – posted Java 8 Streams cheat sheet, which offers a one-page example of a lot of useful, relevant information around streams for handy, quick reference. I looked for a DZone Refcard on streams for a point of comparison, but they didn’t have one that I saw on first scan – which is surprising, since the Refcardz are actually done really well, in general.
Interesting Links, 27 Jan 2016
- Mutation Testing: Watching the Watchmen talks about the need for mutation testing, in addition to addressing the desire for unit testing. His point is: unit testing is good – do it. But it’s often not enough, and he promises to go more into mutation testing as an enhancement in future posts.
- JOOQ has published If Java Were Designed Today: The Synchronizable Interface, discussing what could have been designed as opposed to what we got with the
synchronizedkeyword – aSynchronizableinterface, that could have been used for specific situations a lot like we useIterablein more recent Java coding. - The Double Colon Operator in Java 8 discusses, of all things, the double colon operator in Java 8 (surprise!), which is a shorthand way to refer to a method reference. You find this used very often when working with streams, because the shorthand is so useful.
- RedPen 1.4 has been released (back in October 2015, but I didn’t know about the project until it showed up on homebrew.) RedPen is a proofreading tool for technical documents, NOT for programming, and as such won’t be very useful for most readers of JavaChannel.org, but it’s still pretty interesting. For some reason, it complained a lot about the content of this post…
Interesting Links, 25 Jan 2016
- From ##java itself, Hot deploy to Jboss from Intellij using deployment scanner documents a problem someone had while trying to deploy from IDEA into JBoss, and discusses how to get it working. Of particular note: “The Intellij deployment options for ‘upload external changes’ (turn it on!) and ‘preserve file timestamps’ (turn it off!) have given me particular grief in the past; if you find that Intellij doesn’t seem to be picking up changes and uploading them, look at the former.”
- J2ObjC 1.0 has been released. From the project website: “J2ObjC is an open-source command-line tool from Google that translates Java source code to Objective-C for the iOS (iPhone/iPad) platform. This tool enables Java source to be part of an iOS application’s build, as no editing of the generated files is necessary.” The UI for each platform is still written in code for that platform, but this might make porting code to iOS easier for Java coders.
- A user on ##java posted a link to a free app he’d written for iOS devices: Trident. It’s an app that interacts with Gitlab (and Github, in early preview form), with a primary focus on discussing issues, pull requests, and files from a mobile device. This isn’t an endorsement (your author doesn’t have an iOS device) but it might be worth watching.
- We’ve seen a lot of JavaFX questions lately – mostly they’re from a small cluster of users (therefore: a few JavaFX users, each with a lot of questions, and yes, this is anecdata.) Gluon maintains SceneBuilder, which, well, builds scenes for JavaFX, and just had a new release, version 8.1.0 of Scene Builder.
- Feature Flags are a way to release features to specific users. Turns out there’s a hub dedicated to the method, including a reference to multiple libraries that enable limited releases in wide-area deployments. (The hub itself looks like it’s provided by the authors of Launch Darkly, but that’s okay.) It’s not a new idea, I think, but it’s written up pretty well here and it’s nice to have a hub for the capability.
Interesting Links, 22 January 2016
- Every so often you need to see exactly what headers your HTTP-based application is working with. One way to look at the HTTP headers is to use an HTTP proxy: possibilities in this space include Fiddler, Charles Proxy, and Paros Proxy (with Paros’ website being the Sourceforge project site, which isn’t very confidence-inspiring). There are certainly others (feel free to send them to me, if you’ve used one you like!). You can also use Wireshark if you need to examine all network traffic, but for HTTP Wireshark’s a bit of overkill.
- Picking correct Java executors for background tasks, by ZeroTurnaround (makers of JRebel), goes into how (and why) you would choose specific
Executors. Good reading, spoken as one who more or less usesExecutors.newFixedThreadPool(int)by default. - Use JUnit’s expected exceptions sparingly, from the JOOQ blog, talks about a feature I love from TestNG: the ability to expect exceptions from a test, as opposed to a
try/catchblock that usesfail()to fail the test if an exception isn’t thrown. The JOOQ people argue against using expected exceptions, and if you’re using JUnit, they’re right. TestNG, of course, has a better alternative as usual. - Auditing with JPA, Hibernate, and Spring Data JPA discusses writing audit data with basic JPA (which looks like a pain, relying on JPA lifecycle events) and both Hibernate Envers and Spring Data JPA. Spring Data JPA and JPA have difficulty auditing removals; Spring Data JPA has integration with Spring Security; Hibernate Envers is probably the least intrusive, but doesn’t have Spring Security integration.
Expected Exceptions from JUnit
Use JUnit’s expected exceptions sparingly, from the JOOQ blog, says not to use JUnit‘s “expected exceptions” feature. (Or, more accurately, to use it “sparingly.”) It’s good advice, but it’s also largely limited to JUnit (with one main exception).
What they’re addressing is the transition from this pattern:
@Test
public void testValueOfIntInvalid() {
try {
ubyte((UByte.MIN_VALUE) - 1);
fail();
}
catch (NumberFormatException e) {}
}
To this pattern:
@Test(expected = NumberFormatException.class)
public void testValueOfShortInvalidCase1() {
ubyte((short) ((UByte.MIN_VALUE) - 1));
}
They have four reasons that this doesn’t actually get you anything:
- We’re not really gaining anything in terms of number of lines of code
- We’ll have to refactor it back anyway
- The single method call is not the unit
- Annotations are always a bad choice for control flow structuring
Of these, “The single method call is not the unit” is by far the strongest point.
We’re not really gaining anything in terms of number of lines of code
It’s a matter of opinion, but we generally are gaining something in terms of the code. The refactored test has one line of actual code: ubyte((short) ((UByte.MIN_VALUE) - 1));. Everything around it is window dressing. The original test has the try/catch code, which adds a lot of noise – and discards the “error condition,” which is the actual metric for success (it fails the test if there’s no error.)
Is this a big deal? … No, it’s not. But it’s also not a point worth making.
We’ll have to refactor it back anyway
Here’s where JUnit itself messes things up. The authors actually have a really good point, if you’re locked into JUnit:
In the annotation-driven approach, all I can do is test for the exception type. I cannot make any assumptions about the exception message for instance, in case I do want to add further tests, later on. Consider this:
try { ubyte((UByte.MIN_VALUE) - 1); fail("Reason for failing"); } catch (NumberFormatException e) { assertEquals("some message", e.getMessage()); assertNull(e.getCause()); ... }
Ah, JUnit. JOOQ is making the assertion (see what I did there?) that they can’t examine Reason for failing or some message with the annotation.
They’re right… if you’re locked into JUnit. TestNG can, of course, look at the message and validate it. If the message doesn’t fit the regex, then the test fails, just as expected (and desired).
@Test(expectedExceptions={NumberFormatException.class},
expectedExceptionsMessageRegExp="Reason for failing")
public void testThings() {
...
The single method call is not the unit
Here’s what JOOQ says:
The unit test was called
testValueOfIntInvalid(). So, the semantic “unit†being tested is that of theUBytetype’svalueOf()behaviour in the event of invalid input in general. Not for a single value, such asUByte.MIN_VALUE - 1.
They’re running yet again into a limitation of JUnit. The actual point they’re making is correct, but TestNG provides a @DataProvider mechanism, where you’d actually give the test a signature of testValueOfIntInvalid(int) and pass in a set of integers. That means you can test a range and corner cases, with a single appropriate test.
People have written a data-provider-like feature for JUnit (see junit-dataprovider) – which only highlights how JUnit is affecting the choices made by the JOOQ team.
Annotations are always a bad choice for control flow structuring
Hard to argue with this one: Java has excellent control flow, even if it’s verbose at times. However, the annotation is direct enough (with TestNG, at least) that you aren’t really violating control flow: you’re saying “this is a test, it has these execution rules, and this is how you measure success.” With JUnit, you don’t have the same control.
JUnit.next
According to JOOQ, the next generation of JUnit (junit-lambda) fixes things a little, by offering a lambda solution to exceptions:
Exception e = expectThrows(NumberFormatException.class, () ->
ubyte((UByte.MIN_VALUE) - 1));
assertEquals("abc", e.getMessage());
That’s admirable, but they’re still behind TestNG by a few generations – and there’s still no data factory mechanism.
In Conclusion
Their closing statement is actually really good:
Annotations were abused for a lot of logic, mostly in the JavaEE and Spring environments, which were all too eager to move XML configuration back into Java code. This has gone the wrong way, and the example provided here clearly shows that there is almost always a better way to write out control flow logic explicitly both using object orientation or functional programming, than by using annotations.
It’s worth noting that the statement was actually driven by a lack of features in JUnit (when compared to TestNG) but the point remains.
Interesting Links, 20 Jan 2016
Sorry for the change of date format, folks. Some interesting links that came up include:
- Don’t tell me what to make, tell me how to make it, by David Whiting, talks about using Java 8’s
Supplierto help clean up construction of objects. Actually pretty useful stuff – it’s a common pattern to use no-argument constructors with mutable objects, andSupplier<t>might help us use immutable objects more often. - Arrays of Wisdom of the Ancients, by Alexei Shipilev, takes on the question of
Collection.toArray(new T[0])orCollection.toArray(new T[size])in a long, well-written (and well-reasoned) post. It takes a long time to get to the point (Collection.toArray(new T[0])wins, and has for “five years now”) but it also walks through the reasoning for the conclusion, and is fascinating reading. - The Java Security Manager: Why and How, by Nicolas Fränkel, shows a use of reflection to change a reference to a
Characterto a reference to aStringand talks a bit about how to set up your security manager to be useful in addressing potentially malicious code. - Testing persistence with Arquillian on TomEE describes an end-to-end test for persistence with Arquillian. This is different from an embedded unit test for persistence in that Arquillian can actually start up an application server (TomEE in this case) and run the test there – which serves as a better integration test than a custom persistence configuration for the testing scope.
- Neo4J published Graph Databases for Beginners: ACID vs. BASE Explained, explaining the two consistency models for transactions typically found in storage systems. ACID is typically trumpeted as a strength for relational databases, and stands for “Atomic, Consistent, Isolated, and Durable” transactions, and BASE stands for “Basic Availability, Soft-State, and Eventually Consistent” transactions. BASE is a strength of NoSQL datastores.
- Jihed Amine Maaref posted Setup a docker environment for Liferay with MySQL inside a VirtualBox VM, which walks through a Docker configuration. It’s not so much that Liferay (an open source portal) and MySQL are fascinating (although they’re useful, I guess, especially Liferay), but the walkthrough is a good read, including explanations of how and why along the way.
- ByteBuddy 1.0 has been released. ByteBuddy is a code generation library for Java – which can be used to build mocks, interceptors, or just plain classes out of thin air. Cheesy name and logo, but it seems worthwhile.
If you have interesting links that you’ve run across, please send them my way! It’s worth noting that Petri Kainulainen noted some of the same links as being interesting – check out Petri’s stuff for more focus on testing.