Limited size queue
The Java Collections Queue implementations will either grow without limit, or block if it grows beyond a given size, like the LinkedBlockingDeque. However, what if you need a non-blocking queue which drops its oldest elements? The Apache Commons CircularFifoQueue covers that. The snippet below shows typical use, with a queue size of two, and where the first element of three is dropped.
To install the Apache Commons 4.0 library on Debian / Ubuntu:
The relevant files will be located at:
Often, a queue is populated on one thread, and consumed by another. In this case, the access methods have to be synchronized, as seen in this example. Both offer() and poll() methods are non-blocking, and null is returned if the queue is empty.
Finally, how does this queue work with Streams? In a single-thread context, there shouldn’t be a problem. However, when multithreaded it gets more tricky. The example below fails since the two threads operate on the queue concurrently, and a NoSuchElementException is often thrown. The ConcurrentLinkedQueue is thread-safe, but unbounded. Furthermore, its documentation states that “the size method is NOT a constant-time operation. Because of the asynchronous nature of these queues, determining the current number of elements requires a traversal of the elements, and so may report inaccurate results if this collection is modified during traversal”. Which means we’re back to square one.
There are a few work-arounds, mentioned in this discussion. One trick is to use the Stream.generate() method, which will loop indefinilty, and synchronize on the queue within. The problem is, that this will never stop, which might be okey depending on your application. However, you’d have to run this on a spearate thread. Alternativly, use the limit() method or a stream terminating operation (e.g. findFirst()).
Also worth mentioning, is the Google Guava implementation EvictingQueue. However, it it also not thread-safe.
Here’s the full listing with all test methods.
Sequential vs. Parallel Streams
The Java 8 Streams API offers functional-style operations, and a simple way to execute such operations in parallel. To jump right into an example, the following two test methods show the difference between sequential and parallel execution of the the println() method over each of the elements of the stream.
As is expected, the default sequential execution will print the elements of the stream, which in this example are integers from 1 to 14, in natural order. By using the parallel() method to create a parallel stream and call the same print method, the only noticeable difference is that they are printed out of order.
To see how the parallel stream behaves, the last test applies a different method to each of the elements of the stream. In this example, the time spent by the work() method on each element is linearly proportional to its value. That is, for the element of value 1 it spends 100ms, for 2 its 200 ms and so on. The “work” it does, is simply to sleep for intervals of 100 ms, and the rest of the code is dedicated to printing and formatting the table below. However, it serves the purpose of demonstrating how parallel execution behaves, and how it relates to the underlying CPU(s).
In the result table, each element of the stream is represented by a row. Each row shows the value of the element, the time-slots the work() method was executing, and to the right the time in milliseconds when work started and finished. Each 100 ms slot is represented by a hash. As can be seen, the first row was element 9, thus it marked off nine slots, and the starting time was at 6 ms, and finish at 909 ms.
Furthermore, since this was run on a machine with four CPU cores, the stream will execute four calls in parallel. This can be seen by both the hashes and the start times of the first four rows. Next, when element 2 (fourth row) finishes at 207 ms, a new element is immediately started (element 3, fifth row).
In this example, the total number of 100 ms “units of work” can be found by the formula for the triangular number where n = 14, or 14 * (14 + 1) / 2 = 105. Meaning that, sequential execution would have taken 10.5 seconds, while four parallel CPUs managed in 3 seconds.
In the second table below, the same code is executed on a dual core CPU, and it is clear that now only two methods execute in parallel. That will of course lead to a longer overall runtime, of about 5.4 seconds for this example. This could lead to a discussion on task and scheduling optimisation, however it goes beyond this article, and what is possible with the simple parallel Stream construct.
The full code list is here.
TrayIcon Example
Since Java 6, adding a system tray icon has been straight forward. The two main classes involved are SystemTray and TrayIcon. Various OS might render and operate the icon differently. Typically, there is a status message on hover, a short-cut action on left click, and possibly a menu on right click. The TrayIcon supports all this. In the example code below, an 16x16 pixel PNG is used, and auto-scaled up to about 24 pixels, which is what I’ve configured by XFCE panel.
Here’s the full example class listing.
A simple stupid calculator
This post includes the UI (Swing) for a very simple calculator. There’s not much to say about the code, except for the rather stupid way it handles the calculator operation itself: Using a JavaScript engine! The ScriptEngineManager and the internal NashornScriptEngineFactory JavaScript implementation have been around since Java 6 and 8 receptively. It makes it easy to execute a string as snippet of code, as seen below.
Here the model for the display of the calculator is just a plain string. That string is then evaluated as a line of JavaScript, and the output is returned and put back into the “model”.
In terms of the calculator functionality, this implementation is very simple, but therfore also limited. A more common way of implementing this would be through some object expression representation which can be evaluated. However, the Script Engine implementation has the benefit of supporting functionality which is not even implemented in the UI, like brackets or other operators like power-to (^). It works nicely has a prototype and quick mock, so maybe not so stupid after all.
To be continued…
For the full source of this first version, see here.
Tutorialspoint - compile and run code online
Over at Tutorialspoint.com they have created a superb well of study material and tools. Most impressive are the online compiler and runtime terminals, dubbed Coding Ground, for a large selection of popular and obscure languages and tools. Here’s an example Java project, based on the previous article on word counting. Click Compile followed by Execute and the output from the snippet will show in the terminal. The data file “words” is included in the project. (Note that these terminal seems to run best in Chrome based browsers, and fails to load in Firefox).
Also worth checking out is their long list of tutorials for everything from Java; other programming languages; to sports and “soft skills”. Especially with the programming tutorials, their embedded online compiler & terminal feels very slick, as seen below.
My personal site fades in comparison, however, my goal is not to offer complete university courses. Remember Java will remain focused on exploration and examples of interesting aspects of the Java language.
Word count
Here’s another neat streams snippet, which in three lines handles what would take at least two loops in pre-Java 8 code. The task at hand is to count the number of occurrences of each unique word in a file. Given the content shown below, this Bash command line would solve it.
File content:
Shell output:
The Java code follows a similar flow as seen in the pipes above: Read the file, split each line by space, and flatten the result from all lines into a single stream. Finally, the collect() function is used with the groupingBy() helper, to map each token (or word) in the stream (the identity) to its count.
The Java map will contain the following key-value pairs. Here, the words are also accidentally sorted alphabetically. However, the order is not guaranteed by collect() function, since it returns a HashMap.
The full listing:
Fun with IO Streams
With Java 8, file IO became a pleasure to work with. It was a drastic break from the old verbose syntax and awkward ((line = in.readLine()) != null) and try/try/close idioms. With the new Stream based methods and lambda functions, the IO API becomes more similar to Python in ease of use.
In the code snippet below, all the lines of a file is read, sorted, and printed.
The following lines do the same, but break up the in-line method invocations and returned objects, to more clearly see what’s going on.
Traversing the directory hierarchy is similarly easy and compact:
Finally, here’s an idea for an assertFileEquals() method. It takes two file names, one which is the expected “golden” file which would contain the output from the test. (The example file names below are to make sure the test passes).
Finally, here’s the full test file listing.
Hello Junit Test!
Unit testing can sometimes be like washing the dishes: You know it should be done, that you’ll have to do it eventually, but it can always be postponed. On the other hand, executing your code through unit tests is a great way to verify that it works as expected, in a short amount of time and with little code overhead. Furthermore, writing unit tests is a convenient way to execute any kind of code easily, especially from within a modern IDE, where it is typically easier to run a single test method than a full executable. Many of the examples on this site will use unit tests as the driver.
Test Method
The “Hello World” minimal example of a Junit 4 test method can be seen in the first example below. All it takes, is a method (of any name) annotated with the @Test annotation. Typically, a test method will assert something against expected values, albeit in the examples below this is ineffectual.
Setup and teardown
The anatomy of a test case class is as seen in the following example. Again, the method names are not relevant, and only the annotations indicate at what point they will be executed. All the annotations can appear on multiple methods, and the only additional requirements are that all annotated methods have to be public; and that the before and after class methods have to be static.
Order of execution
The final example below adds some flesh to the body of each of the methods, and illustrates a few basic principles of how the different methods are used.
- The annotations indicate the order: BeforeClass, Before, Test, After, AfterClass.
- BeforeClass and AfterClass methods are run once, while Before and After methods are executed for every Test method.
- Since the Class level methods are static, any global fields they use also have to be static.
- The class is re-constructed for every single Test method. This will reset all global fields, as seen in the output below.
- The order between Test methods is typically chronological as they appear in the file, however, it is good practice not to rely on this. Or rather, Test methods should not depend on each other.
The test case above gives the following output. Notice the static a counter, and the global non-static b counter which is reset.