Like many other concurrent collections, the ArrayBlockingQueue sports a weakly-consistent iterator. However, the ArrayBlockingQueue always has a maximum capacity, the length of the underlying array. In this newsletter we explore what happens to pending iterators when we wrap around the circular a... Full Article
We sometimes are forced by the Java language to declare variables that we never use, attracting the ire of the javac compiler. Since Java 22 we have a way to declare these as "unnamed" by using an underscore. Full Article
How many times have we seen programmers call System.gc() to "help the garbage collector"? Unfortunately far too often, with potentially terrible performance implications. In this newsletter we explore the explicit and the diagnostic GC and how we can force a GC, even if explicit GCs are disabled. Full Article
Java 22 preview allows us to write code before the call to super(). There are restrictions. We are not allowed to refer to "this" in any way. We thus cannot set fields before calling the superclass constructor. But what if the superclass constructor calls our methods? In this newsletter we explor... Full Article
Classes java.util.Random and java.util.SplittableRandom didn't used to have a common ancestor, making it difficult to write methods that take either. This was finally fixed in Java 17. Let's have a look at some random Java topics together. Full Article
A few years ago, the second oldest man in our village Chorafakia wrote a book about the history of our area. Only catch - it was in Cretan Greek. I tried to read it, but couldn't. Google Translate shrugged at the strange Cretan dialect. Then ChatGPT 4.0 came along, and we can interact with it dir... Full Article
What causes opportunities to disappear? Is it #1 the market has lost interest in what we are selling (Java is dead). Or is it #2 we have personally become irrelevant (AI writes better code)? Or could it be something else? Join me as we read about my recent dumb mistakes :-) Full Article
The printf() method in Java borrows heavily from C, including the alternate flag #. But %s works a bit differently in Java. In this newsletter we explore this a bit more deeply. Full Article
Virtual threads should not be used for CPU intensive tasks. The recommended approach is to continue using parallel streams for processing large data sets. However, we should be careful when invoking a parallel stream from a virtual thread. In this newsletter we propose a "safety valve" that can p... Full Article
In this guest article by Kirk Pepperdine, we learn about how P99 latency is affected by garbage collection stop-the-world events. Full Article
We can construct our TreeSet with our own Comparator, however, we need to be careful that it conforms to the specification. The Comparator needs to be consistent with equals() and hashCode() of the elements, otherwise we might end up with a TreeSet with non-symmetric equals() behaviour. Full Article
Javadoc specifies the details of our methods using special tags such as @param and @return. After Java 5, we did not see new standard Javadoc tags for 13 years. The hope was that annotations would replace the chaos of doclets. But tags have not disappeared. In this newsletter, we examine several ... Full Article
Reflection returns the modifiers of class elements as an unqualified int bitset. Unfortunately some of the bits have a different meaning depending on their context. For example, a method can have their transient bit set, even though that does not make sense for a method. In Java 20, we now have a... Full Article
JEP 254 replaced the char[] in our Strings with byte[]. How much memory does this save in our Strings? In this newsletter we show how we can determine this from a heap dump file. Full Article
BigInteger has clever algorithms for multiplying large numbers. Unfortunately multiply() is single-threaded. Until now. In this newsletter I describe how the new parallelMultiply() method works and also how we can all contribute to the OpenJDK. Full Article
JEP 290 introduced the ObjectInputFilter, which we can use to filter objects returned from an ObjectInputStream. We examine three ways of making filters, through subclassing, with factory methods and with text patterns, and then show some interesting edge cases. Full Article
Some Map implementations allow null keys and values. This leads to funky behaviour when calling putIfAbsent() and the compute functions. In this newsletter we look a bit more closely at the issues at hand when allowing nulls in maps. Full Article
Virtual threads can deadlock, just like platform threads. Depending on what state they are in, this might be quite challenging to analyze. In this newsletter we explore some tricks on how to find and solve them. Full Article
As from this month, Project Loom is part of the mainstream OpenJDK as a preview feature. Expect fantastical results, as bloggers around the world kick the tyres of this fantastic technology. In this newsletter we show how we can have over 36 billion parked virtual threads in just 4 gigabytes of m... Full Article
The enhanced switch is cool. Pattern Matching for switch is super cool (they even timed the JEP number to be exactly 420 - or was that fate?). But what happens when we use "break" inside the case statement? Let's find out. Full Article
Locking on Integer objects has always been a bad idea. And we now have a way to find such bad code with a runtime switch DiagnoseSyncOnValueBasedClasses. Full Article
Sealed classes show us which subclasses they permitted. Unfortunately there is no way to do this recursively. In this newsletter we show how to navigate the sealed class hierarchy and write a ClassSpliterator that can then create a Stream of classes. Full Article
Java has support for parallelism baked into the JDK. We have parallel streams, parallel sort and CompletableFutures, all using the same common ForkJoinPool. In this newsletter we explore how to measure the effectiveness of our parallelism. Full Article
LinkedHashSet is a set that can also maintain order. To make this thread-safe, we can wrap it with Collections.synchronizedSet(). However, this is not a good option, because iteration would still be fast-fail. And what's the point of a thread-safe LinkedHashSet that we cannot iterate over? In thi... Full Article
Streams can make our code more readable, and therefore more maintainable. However, there is some overhead in setting up the stream, a cost that might become pronounced when the stream is empty. In this newsletter we will consider an idea of the EmptyStream to reduce that cost. Full Article
One of the most convenient ways of constructing complex Strings is with String.format(). It used to be excessively slow, but in Java 17 is about 3x faster. In this newsletter we discover what the difference is and where it will help you. Also when you should use format() instead of the plain Stri... Full Article
Should we write "public abstract static class" or "public static abstract class"? And should fields be "final static private" or "private static final"? In this newsletter we explore the canonical order of modifiers in Java. Full Article
CountDownLatch is easy to understand, but can be hard to use, especially the await() method that throws InterruptedException. In this newsletter we show how we can create our own synchronizer based on the AbstractQueuedSynchronizer. Full Article
"Would you like to play with me?" - Summer holidays are a good time to relax and whip out a board game or two. In this newsletter we explore a children's favourite - snakes and ladders, with a simulation written in Java. Full Article
When is it safe for a CopyOnWriteArrayList to accept the result from a toArray() method? In the past, the only thing that mattered was that the type was Object[]. But this was changed in 2020 to only accept the array if the source was a java.util.ArrayList. Full Article
If we have a List
How consistent is weakly-consistent iteration? And which collections return weakly-consistent iterators? How do we know? Join us as we explore what weakly-consistent means with concrete examples. Full Article
MethodHandles annotate the invoke() methods with @PolymorphicSignature. In this newsletter we see how this can help to avoid unnecessary object creation. Full Article
Today is the 20th anniversary of The Java Specialists' Newsletter. Time to sit back, relax, grab a coffee and wax lyrically about what makes Java so great (you) and how we can find great mentors in life. Full Article
Each PrintStream uses about 25kb of memory. This might seem reasonable if we only have System.out and System.err. But what happens if we try create millions? And why do they use so much memory? Full Article
Java 8 Streams were the first time that Java deliberately split utility classes into multiple versions to be used for Object, int, long and double. This design was also applied to Iterator, which now has specialized types for these primites in the form of the PrimitiveIterator. In this newsletter... Full Article
A nice puzzle to brighten your day - how can we make the Iterator think that the List has not been changed? Full Article
Biased locking has made unnecessary mutexes cheap for over a decade. However, it is disabled by default in Java 15, slated for removal. From Java 15 onwards we should be more diligent to avoid synchronized in places where we do not need it. Full Article
In our next puzzle, we up the ante a bit. We prevent GC during the test() method by storing a strong reference to all our Vectors. Cock and bull story, or are we struggling to identity our biases? Full Article
For today's puzzle, we are getting elements from Vector, sequentially and in parallel. But why is the performance so much worse in Java 15-ea+28? Full Article
The Java ReentrantReadWriteLock can never ever upgrade a read lock to a write lock. Kotlin's extension function ReentrantReadWriteLock.write() cheats a bit by letting go of the read lock before upgrading, thus opening the door for race conditions. A better solution is StampedLock, which has a met... Full Article
How much memory was wasted when an additional boolean field was added to java.lang.String in Java 13? None at all. This article explains why. Full Article
In Java 2, the computational time complexity of String#hashCode() became linear, as it used every character to calculate the hash. Java 3 cached the hash code, so that it would not need to be recalculated every time we called hashCode(), except in the case that the hash code was zero. Java 13 fi... Full Article
Java 14 Records (JEP359) reduce the boiler plate for simple POJOs. In this newsletter we look at what special magic is used to serialize and deserialize these new records. Full Article
In our previous newsletter we enhanced Java 8 Streams by decorating them with an EnhancedStream class. The code had a lot of repetition, which often leads to bugs if written by hand. In this newsletter we use a dynamic proxy to create an EnhancedStream. The resulting code is shorter and more c... Full Article
Java 8 Streams have a rather narrow-minded view of what makes objects distinct. In this newsletter, we enhance Streams to allow a more flexible approach for deciding uniqueness. Full Article
Class.getMethods() returns all the public methods in this class and the classes in its ancestry. However, we cannot necessarily call these methods, for example if they are declared in a private inner class or a lambda. In this newsletter we attempt to find all truly public methods. Full Article
In a previous newsletter, we looked at how we could dynamically add new enums and also rewire affected switch statements. Due to improvements in Java security, our old approach needs to be updated for Java 12. Full Article
Java 11 added the HttpClient to give us a better way to send HTTP requests. It supports asynchronous and synchronous mode. HTTP2 comes out of the box. The threading is a bit funky though and Professor Cay Horstmann explores how things work underneath the covers. Full Article
When are Strings deduplicated? How can we find out whether they are of any benefit in our application? How much does it cost in terms of CPU? We try to show you how we can get this from the deduplication statistics provided by the JVM. Full Article
The compareTo() function has three rules. Break any one of them and you might get an exception when you sort. In this newsletter we explore what these rules are and how they can affect sorting. Full Article
In today's puzzle, we want to sort a list of persons. It works in some versions of Java, but not in others. You need to figure out why. Full Article
The Java Development Kit is filled with great examples of how design patterns can be used to make the Java code easier to maintain. But what is the performance impact of all this indirection and additional object creation? In this newsletter we explore how the compiler makes well-factored Java ... Full Article
In our previous newsletter, we showed 14 typical questions that interviewers ask to find out if we know threading. Here are our model answers. Use them with caution. The interviewer is probably reading my newsletter. Full Article
Asking detailed threading questions during an interview is like asking a football player to prove that he can sing well. Not necessarily relevant to their job description. And yet we see this commonly for Java jobs. In this newsletter we consider more than a dozen real questions that technical... Full Article
Our lives are so busy, we sometimes forget to stop and smell the roses. Let's take a moment to look back at how far we have come in the last 12 months. Full Article
Anonymous inner classes can be used effectively in Java 8 Streams to create tuples. See how this can improve our refactoring of old procedural code into the functional paradigm. Full Article
A well known exploit with maps is to create a lot of Strings as keys that all have the same hash code. In this newsletter we see how easily that can be done and what Java 8+ HashMap does to protect itself. Full Article
ConcurrentLinkedQueue's size() method is not very useful in a multi-threaded environment, because it counts the number of elements in the queue, rather than relying on a "hot field" to store the size. The result might be completely incorrect, or in strange situations, never return. Full Article
Is the Java Ecosystem still safe and robust or should we move to a different language? Maybe Go or Python? In this newsletter we look at whether Java is still a solid choice. Full Article
How would the plain Java code look for our try-with-resource constructs? Watch how 4 lines of code are expanded into 39 LOC and 170 bytecodes. We also look at how Java 9 has reduced this slightly. Full Article
Sorting a stream is easy. But what if we want the opposite: shuffling? We can shuffle a List with Collections.shuffle(List). But how can we apply that to a Stream? In this newsletter we show how with Collectors.collectingAndThen(). Full Article
Java 7 gave us a brilliant new class called Phaser, which we can use to coordinate actions between threads. It replaces both CountDownLatch and CyclicBarrier, which are easier to understand, but harder to use. Full Article
Apparently Full GC is done in parallel in the Java 10 G1 collector. Or is it? In this newsletter we set out to discover the truth by dumping the GC CPU usage with the new Unified JVM Logging. Full Article
Local variable type inference is finally here, but dangers lurk. We might encourage overly long methods and lose the benefits of interface abstraction. Full Article
We now look at why the best-case scenario for a getMethod() call is O(n), not O(1) as we would expect. We also discover that the throughput of getMethod() has doubled in Java 9. Full Article
What is the best-case computational time complexity for finding a method inside a class via reflection? In this newsletter we do not answer that question. Instead, we look at the GoF Builder and wonder whether anyone has ever used it in Java. Full Article
We build a simple custom Spliterator to allow us to stream over dates to find how many times the 1st of January was on a Monday. Full Article
Since Java 5, we have been able to create collections that would check at runtime that the objects added were of the correct type. But very few Java programmers know about it. The benefit we get in debugging ease is huge, as exceptions are thrown earlier. Full Article
Java 9 has changed the way that new programmers can be introduced to Java. No more "public static void main(String[] args)", but instead a beautiful jshell REPL that lets us experiment with Java features without understanding the subtleties of "static". Full Article
Java 9 is more strict about what system internal classes we can use. So how can we use @Contended in Java 9? This article shows you how. Full Article
Java 9 now offers immutable lists, sets and maps. We look at how to create them and also how to do simple set operations like union and intersection. Full Article
Just like inner classes, lambdas might also suffer from memory issues, but to a lesser extent. In this puzzle you need to figure out which lambdas are affected. Full Article
The LinkedHashMap has an interesting feature, where we can order elements in "access order", rather than the default "insertion order". This allows us to build a light-weight LRU cache. Full Article
Surprisingly, the compound arithmetic expression contains a cast that can produce some interesting side effects. In this newsletter we explore this and other edge cases in the Java Language Specification. Full Article
My mother is a trained physiotherapist. Ergonomics and physical health has always interested me, even though like most of us, I struggle with laziness. As Java programmers, we need to keep in shape if we want to work for a long time, both mentally and physically. In this newsletter, I share 4 ... Full Article
For our 16th anniversary edition, we have produced three short video tutorials on how to build your own CircularArrayList in Java, based on the AbstractList. Full Article
Most programmers had a blind spot with the statement "arr[size++] = e;" We somehow think that size will be updated after the assignment. In this newsletter we look at this basic concurrency bug and also present a solution in the form of the Java 8 StampedLock. Full Article
In the previous newsletter, we sent out a threading puzzle for you to solve. Here are some hints to help you figure out what is going on. Full Article
"Friends don't let friends write low-level concurrency by themselves." -@karianna. Here is your chance to participate in a global code review puzzle to figure out what's going on in some synchronized code. Full Article
We humans are rather good at figuring out what is meant from context. Computers are terrible. They do exactly what we tell them to. Fun ensues when we feed them wrong number formatting information. Full Article
List has a new method sort(Comparator). This is handy, as it allows implementations to specialize how to sort their internal data structures. Vector only synchronizes once per list, not once per element. ArrayList avoids copying the array unnecessarily. CopyOnWriteArrayList works. Full Article
Java 8 introduced the java.util.Optional class, based on the famous Guava class by the same name. It was said that we should hardly ever call get(). In this newsletter we offer a short tutorial that demonstrates coding examples of alternatives to get(). Full Article
Java 6 introduced a mechanism to store ASCII characters inside byte[] instead of a char[]. This feature was removed again in Java 7. However, it is coming back in Java 9, except this time round, compaction is enabled by default and byte[] is always used. Full Article
BigInteger has new algorithms for multiplying and dividing large numbers that have a better computational complexity than previous versions of Java. A further improvement would be to parallelize multiply() with Fork/Join. Full Article
Java 8 HashMap has been optimized to avoid denial of service attacks with many distinct keys containing identical hash codes. Unfortunately performance might degrade if you use your own keys. In this newsletter we show a tool that you can use to inspect your HashMap and view the key distributio... Full Article
Most of the time our code fails because of bugs in our code. Rarely, however, bugs in the JVM ecosystem cause our systems to fail. These are insanely difficult to diagnose in production systems. In this newsletter we look at two different such race conditions between our code and the JVM. Full Article
Lambdas are often described as anonymous inner classes without the boilerplate code. However, lambdas are more powerful. Firstly, a lambda does not always result in a new object. Secondly, "this" refers to the outer object. Thirdly, a lambda object can implement multiple interfaces. In this ... Full Article
Even though standard Java is not real-time, we often use it in time-sensitive applications. Since GC events are often the reason for latency outliers, such code seeks to avoid allocation. In this newsletter we look at some tools to add to your unit tests to check your allocation limits. Full Article
In this newsletter, Heinz answers the question that he gets asked most: "Why Crete?" "Because I can" could be one answer, but the reality is a bit deeper than that. Full Article
Java 7 quietly changed the structure of String. Instead of an offset and a count, the String now only contained a char[]. This had some harmful effects for those expecting substring() would always share the underlying char[]. Full Article
ThreadLocals should in most cases be avoided. They can solve some tough problems, but can introduce some nasty memory leaks, especially if the ThreadLocal class or value refer to our own classes, not a system class. In this newsletter we show some mechanisms that help under OpenJDK. Full Article
ExecutorService allows us to submit either Callable or Runnable. Internally, this is converted to a FutureTask, without the possibility of extracting the original task. In this newsletter we look at how we can dig out the information using reflection. Full Article
In this newsletter, Heinz talks about some characteristics that are useful if you want to become a successful champion Java programmer. Full Article
How can you discover all the places in your program where threads are being constructed? In this newsletter we create our own little SecurityManager to keep an eye on thread creation. Full Article
Whenever a class implements an interface, all the implemented methods have to be public. In this newsletter we look at a trick that we can use to make them private. Full Article
In his latest book, Maurice Naftalin takes us on a journey of discovery as we learn with him how Lambdas and Streams work in Java 8. Full Article
Blocking methods should not be called from within parallel streams in Java 8, otherwise the shared threads in the common ForkJoinPool will become inactive. In this newsletter we look at a technique to maintain a certain liveliness in the pool, even when some threads are blocked. Full Article
The JavaDocs for method Object.hashCode() seems to suggest that the value is somehow related to memory location. However, in this newsletter we discover that there are several different algorithms and that Java 8 has new defaults to give better threading result if we call hashCode a lot. Full Article
Lambdas in Java took a long time in coming, due to the considerable engineering effort put into incorporating them into the Java Language. Unfortunately checked exceptions are not managed as seamlessly as they should. Full Article
Whenever we have thread pools in our system, we need to make their size configurable. In this follow-up, we continue looking at some issues with the common fork/join pool that is used in Java 8. Full Article
Java 8 magically makes all our code run in parallel. If you believe that, I've got a tower in Paris that I'm trying to sell. Really good price. In this newsletter we look at how the parallism is determined and how we can influence it. Full Article
The LinkedHashMap has a little known feature that can return elements in least recently accessed order, rather than insertion order. In this newsletter we use this to construct a "Recently Used File" list. Full Article
One of the techniques we use to ensure that a non-threadsafe class can still be used by multiple threads is to give each thread its own instance. We call this "thread confinement". In this newsletter we look at some of the issues that can happen when this instance leaks. Full Article
Heavily contended concurrent constructs may benefit from a small pause after a CAS failure, but this may lead to worse performance if we do more work in between each update attempt. In this follow-up newsletter, we show how adding CPU consumption can change our performance characteristics. Full Article
What is faster? Synchronized or Atomic compare-and-set? In this newsletter we look at some surprising results when we run Java on the new i7 chip. Full Article
Software engineers need to have a good understanding of mathematics. In this newsletter, we review a book written by a geek and aimed at the geek who wants to discover interesting facts about maths. Full Article
Java 8 includes a new synchronization mechanism called StampedLock. It differentiates between exclusive and non-exclusive locks, similar to the ReentrantReadWriteLock. However, it also allows for optimistic reads, which is not supported by the ReentrantReadWriteLock. In this newsletter, we loo... Full Article
CompletionService queues finished tasks, making it easier to retrieve Futures in order of completion. But it lacks some basic functionality, such as a count of how many tasks have been submitted. Full Article
When a thread is interrupted, we need to be careful to not create a livelock in our code by re-interrupting without returning from the method. Full Article
Maps and Sets in Java have some similarities. In this newsletter we show a nice little trick for converting a map class into a set. Full Article
We continue our discussion on Unicode by looking at how we can compare text that uses diacritical marks or special characters such as the German Umlaut. Full Article
In this newsletter we investigate what can go wrong when we call methods from constructors, showing examples from the JDK, Glassfish, Spring Framework and some other well known frameworks.. Full Article
Unicode is the most important computing industry standard for representation and handling of text, no matter which of the world's writing systems is used. This newsletter discusses some selected features of Unicode, and how they might be dealt with in Java. Full Article
How can you set a field at point of declaration if its constructor throws a checked exception? Full Article
The trend of marking parameters and local variables as "final" does not really enhance your code, nor does it make it more secure. Full Article
We present a new type of ExecutorService that allows users to "stripe" their execution in such a way that all tasks belonging to one stripe are executed in-order. Full Article
Rule Based Programming, a declarative programming paradigm, is based on logical patterns to select data and associate it with processing instructions. This is a more indirect method than the sequential execution steps of an imperative programming language. Full Article
Ben Evans and Martijn Verburg explain to us in their new book what it takes to be a well-grounded Java developer. The book contains a section on the new Java 7 features and also vital techniques that we use for producing robust and performant systems. Full Article
It is possible to use the break statement to jump out to the end of a labelled scope, resulting in some strange looking code, almost like the GOTO statement in C. Full Article
In this newsletter, it is up to you to figure out how we improved the performance of our previous Fibonacci newsletter by 25%. Full Article
The new Java 7 Fork/Join Framework allows us to define our algorithms using recursion and then to easily parallelize them. In this newsletter we describe how that works using a fast Fibonacci algorithm that uses the sum of the squares rather than brute force. We also present a faster algorithm ... Full Article
Every Java programmer I have met knows that they should know more about concurrency. But it is a topic that is quite hard to learn. In this newsletter I give some tips on how you can become proficient in concurrency. Full Article
Surreptitious: stealthy, furtive, well hidden, covert. In this newsletter we will show two Java puzzles written by Wouter Coekaerts that require a surreptitious solution. You cannot do anything to upset the security manager. Full Article
What is the largest double that could in theory be produced by Math.random()? In this newsletter, we look at ways to calculate this based on the 48-bit random generator available in standard Java. We also prove why in a single-threaded program, (int)(Random.nextDouble() + 1) can never be rounde... Full Article
In this newsletter we try to calculate the meaning of life, with surprising results. Full Article
Java 7 removes the Swing Event Dispatch Thread (EDT) hack that allowed us to specify an uncaught exception handler for the EDT using a system property sun.awt.exception.handler. Full Article
In this newsletter, we present a little performance puzzler, written by Kirk Pepperdine. What is happening with this system? There is only one explanation and it can be discovered by just looking at the stack trace. Full Article
Did you know that it possible to "try" to synchronize a monitor? In this newsletter we demonstrate how this can be used to avoid deadlocks and to keep the wine coming. Full Article
In this newsletter we measure the memory requirements of various types of hash maps available in Java. Maps usually need to be threadsafe, but non-blocking is not always the most important requirement. Full Article
A quick follow-up to the previous newsletter, to show how the ThisEscape class is compiled, causing the "this" pointer to leak. Full Article
We should never allow references to our objects to escape before all the final fields have been set, otherwise we can cause race conditions. In this newsletter we explore how this is possible to do. Full Article
The garbage collector can cause our program to slow down at inappropriate times. In this newsletter we look at how we can delay the GC to never run and thus produce reliable results. Then, instead of actually collecting the dead objects, we simply shut down and start again. Full Article
In this newsletter we discuss why we unfortunately will not be able to use the try-with-resource mechanism to automatically unlock in Java 7. Full Article
In this newsletter we explore my favourite new Java 7 feature "try-with-resource" and see how we can use this mechanism to automatically unlock Java 5 locks. Full Article
It is almost Christmas time, which gives us an excuse to invest in all sorts of toys. I found that the most ridiculously priced ones are those that promise to have an added benefit besides fun. "Educational", "Good for hand-eye coordination", etc. In this Java newsletter we look at one of thes... Full Article
In this newsletter, we explore a question of how to call a method interleaved from two threads. We show the merits of lock-free busy wait, versus explicit locking. We also discuss an "unbreakable hard spin" that can cause the JVM to hang up. Full Article
Many years ago, when hordes of C++ programmers ventured to the greener pastures of Java, some strange myths were introduced into the language. It was said that a "try" was cheaper than an "if" - when nothing went wrong. Full Article
Most of the northern hemisphere is on holiday, so here is a quick quiz for those poor souls left behind manning the email desk. How can we prevent a ConcurrentModificationException in the iterator? Full Article
In his latest book, Jim Waldo describes several Java features that he believes make Java "good". A nice easy read, and I even learned a few new things from it. Full Article
A common approach to ensuring serialization consistency in thread safe classes such as Vector, Hashtable or Throwable is to include a synchronized writeObject() method. This can result in a deadlock when the object graph contain a cyclic dependency and we serialize from two threads. Whilst unli... Full Article
What has a larger serializable size, ArrayList or LinkedList? In this newsletter we examine what the difference is and also why Vector is a poor candidate for a list in a serializable class. Full Article
In this newsletter, we describe how we can generate remote screen shots as compressed, scaled JPGs to build a more efficient remote control mechanism. Full Article
In this newsletter, we show how the Generator described in our previous issue can be used to create virtual proxy classes statically, that is, by generating code instead of using dynamic proxies. Full Article
In this newsletter, we have a look at how we can create new classes in memory and then inject them into any class loader. This will form the basis of a system to generate virtual proxies statically. Full Article
Escape analysis can make your code run 110 times faster - if you are a really really bad programmer to begin with :-) In this newsletter we look at some of the places where escape analysis can potentially help us. Full Article
Generics can be used to further improve the WalkingCollection, shown in our previous newsletter. Full Article
We look at how we could internalize the iteration into a collection by introducing a Processor interface that is applied to each element. This allows us to manage concurrency from within the collection. Full Article
After almost nine years of silence, we come back to bring the logging series to an end, looking at best practices and what performance measurements to log. Full Article
Concurrency is easier when we work with immutable objects. In this newsletter, we define another concurrency law, The Law of the Xerox Copier, which explains how we can work with immutable objects by returning copies from methods that would ordinarily modify the state. Full Article
De-Serialization creates objects without calling constructors. We can use the same mechanism to create objects at will, without ever calling their constructors. Full Article
In this newsletter, we reveal the answer to the puzzle from last month and explain the reasons why the first class sometimes fails and why the second always succeeds. Remember this for your next job interview ... Full Article
In this newsletter we show you a puzzle, where a simple request causes memory to be released, that otherwise could not. Solution will be shown in the next newsletter. Full Article
The DateFormat produces some seemingly unpredictable results parsing the date 2009-01-28-09:11:12 as "Sun Nov 30 22:07:51 CET 2008". In this newsletter we examine why and also show how DateFormat reacts to concurrent access. Full Article
One of the hardest exceptions to get rid of in a system is th ConcurrentModificationException, which typically occurs when a thread modifies a collection whilst another is busy iterating. In this newsletter we show how we can fail on the modifying, rather than the iterating thread. Full Article
It is well known that implementing a non-trivial finalize() method can cause GC and performance issues, plus some subtle concurrency bugs. In this newsletter, we show how we can find all objects with a non-trivial finalize() method, even if they are not currently eligible for finalization. Full Article
In this newsletter, we show two approaches for listening to bytes on sockets. The first uses the Delegator from our previous newsletter, whereas the second uses AspectJ to intercept the call to Socket.getInput/OutputStream. We also write an MBean to publish this information in JConsole. Full Article
In this newsletter we show the reflection plumbing needed for writing a socket monitor that sniffs all the bytes being sent or received over all the Java sockets. The Delegator is used to invoke corresponding methods through some elegant guesswork. Full Article
In this newsletter we answer the question: "How do we force all subclasses to contain a public no-args constructor?" The Annotation Processing Tool allows us to check conditions like this at compile time, rather than only at runtime. Full Article
Java's serialization mechanism is optimized for immutable objects. Writing objects without resetting the stream causes a memory leak. Writing a changed object twice results in only the first state being written. However, resetting the stream also loses the optimization stored in the stream. Full Article
In this newsletter we examine what happens when a ReadWriteLock is swamped with too many reader or writer threads. If we are not careful, we can cause starvation of the minority in some versions of Java. Full Article
Prior to Java 1.4, ThreadLocals caused thread contention, rendering them useless for performant code. In the new design, each thread contains its own ThreadLocalMap, thus improving throughput. However, we still face the possibility of memory leaks due to values not being cleared out of the Thre... Full Article
Joshua Bloch has at long last published an updated version of Effective Java. An essential guide for professional Java programmers who are interested in producing high quality code, this book is also very readable. In this newsletter we describe some of the nuggets found in the book. Full Article
In this article, we look at exception handling in Java. We start with the history of exceptions, looking back at the precursor of Java, a language called Oak. We see reasons why Thread.stop() should not be used and discover the mystery of the RuntimeException name. We then look at some best pract... Full Article
The developers of the Java language tried their best to stop us from constructing our own enum instances. However, for testing purposes, it can be useful to temporarily add new enum instances to the system. In this newsletter we show how we can do this using the classes in sun.reflect. In addi... Full Article
Imagine a very stubborn viking father insisting that his equally stubborn child eat its lutefisk before going to sleep. In real life one of the "threads" eventually will give up, but in Java, the threads become deadlocked, with neither giving an inch. In this newsletter we discover how we can s... Full Article
We all expect faster hardware to make our code execute faster and better. In this newsletter we examine why this is not always true. Sometimes the code breaks on faster servers or executes slower than on worse hardware. Full Article
In this newsletter, we reveal some of the polymorphism mysteries in the JDK. The HotSpot Server Compiler can distinguish between mono-morphism, bi-morphism and poly-morphism. The bi-morphism is a special case which executes faster than poly-morphism. Mono-morphism can be inlined by the compile... Full Article
Late binding is supposed to be a bottleneck in applications - this was one of the criticisms of early Java. The HotSpot Compiler is however rather good at inlining methods that are being called through polymorphism, provided that we do not have very many implementation subclasses. Full Article
The Law of Cretan Driving looks at what happens when we keep on breaking the rules. Eventually, we might experience a lot of pain when we migrate to a new architecture or Java Virtual Machine. Even if we decide not to obey them, we need to know what they are. In this newsletter, we point you t... Full Article
In good Dilbert style, we want to avoid having Pointy-Haired-Bosses (PHBs) in our code. Commonly called micromanagers, they can make a system work extremely inefficiently. My prediction is that in the next few years, as the number of cores increases per CPU, lock contention is going to be the bi... Full Article
Timers in Java have suffered from the typical Command Pattern characteristics. Exceptions could stop the timer altogether and even with the new ScheduledPoolExecutor, a task that fails is cancelled. In this newsletter we explore how we could reschedule periodic tasks automatically. Full Article
In this newsletter, we look at how we can read from the console input stream, timing out if we do not get a response by some timeout. Full Article
Corruption has a habit of creeping into system that do not have adequate controls over their threads. In this law, we look at how we can detect data races and some ideas to avoid and fix them. Full Article
In this fifth law of concurrency, we look at a deadly law where a field value is written early. Full Article
In this fourth law of concurrency, we look at the problem with visibility of shared variable updates. Quite often, "clever" code that tries to avoid locking in order to remove contention, makes assumptions that may result in serious errors. Full Article
Learn how to write correct concurrent code by understanding the Secrets of Concurrency. This is the third part of a series of laws that help explain how we should be writing concurrent code in Java. In this section, we look at why we should avoid creating unnecessary threads, even if they are n... Full Article
Recent versions of Swing do a good job of mimicking the underlying platform, with a few caveats. For example, the JSlider only snaps onto the correct tick once you let go of the mouse. Here I present a fix for this problem with a non-intrusive one-liner that we can add to the application code. Full Article
Learn how to write correct concurrent code by understanding the Secrets of Concurrency. This is the second part of a series of laws that help explain how we should be writing concurrent code in Java. We look at how to debug a concurrent program by knowing what every thread in the system is doing. Full Article
Learn how to write correct concurrent code by understanding the Secrets of Concurrency. This is the first part of a series of laws that help explain how we should be writing concurrent code in Java. Full Article
The Tristate Checkbox is widely used to represent an undetermined state of a check box. In this newsletter, we present a new version of this popular control, retrofitted to Java 5 and 6. Full Article
Experienced Java programmers will love the Java Puzzlers book by Josh Bloch and Neal Gafter, both well known Java personalities. In this newsletter, we look at two of the puzzles as a teazer for the book. Full Article
Google Web Toolkit (GWT) allows ordinary Java Programmers to produce highly responsive web user interfaces, without needing to become experts in JavaScript. Here we demonstrate a little maths game for practicing your arithmetic. Included is an Easter egg. Full Article
Memory usage of Java objects has been a mystery for many years. In this newsletter, we use the new instrumentation API to predict more accurately how much memory an object uses. Based on earlier newsletters, but revised for Java 5 and 6. Full Article
Enums are implemented as constant flyweights. You cannot construct them. You cannot clone them. You cannot make copies with serialization. But here is a way we can make new ones in Java 5. Full Article
Java Generics and Collections is the "companion book" to The Java Specialists' Newsletter. A well written book that explains generics really nicely, including some difficult concepts. In addition, they cover all the new collection classes up to Java 6 Mustang. Full Article
Mustang introduced a ServiceLoader than can be used to load JDBC drivers (amongst others) simply by including a jar file in your classpath. In this newsletter, we look at how we can use this mechanism to define and load our own services. Full Article
Java 6 has support for JDBC 4, which, amongst other things, gives you better feedback of what went wrong with your database query. In this newsletter we demonstrate how this can be used. Full Article
A common idiom for logging is to create a logger in each class that is based on the class name. The name of the class is then duplicated in the class, both in the class definition and in the logger field definition, since the class is for some reason not available from a static context. Read ho... Full Article
In this newsletter, we look at a technique of how we can replace an existing database driver with our own one. This could be used to migrate an application to a new database where you only have the compiled classes. Or it could be used to insert a monitoring JDBC connection that measures the le... Full Article
With Java 5, we can measure CPU cycles per thread. Here is a small program that runs several CPU intensive tasks in separate threads and then compares the elapsed time to the total CPU time of the threads. The factor should give you some indication of the CPU based acceleration that the multi c... Full Article
As developers we often hear that performance often comes at the price of good design. However when we have our performance tuning hats on, we often find that good design is essential to help achieve good performance. In this article we will explore one example of where a good design choice has be... Full Article
When we query the database using EJB3, the Query object returns an untyped collection. In this newsletter we look at several approaches for safely converting this to a typed collection. Full Article
Sometimes it is useful to have a look at what the threads are doing in a light weight fashion in order to discover tricky bugs and bottlenecks. Ideally this should not disturb the performance of the running system. In addition, it should be universally usable and cost nothing. Have a look at h... Full Article
In this newsletter, we show how simple it is to send emails from Java. This should obviously not be used for sending unsolicited emails, but will nevertheless illustrate why we are flooded with SPAM. Full Article
Java level monitor deadlocks used to be hard to find. Then along came JDK 1.4 and showed them in CTRL+Break. In JDK 5, we saw the addition of the ThreadMXBean, which made it possible to continually monitor an application for deadlocks. However, the limitation was that the ThreadMXBean only wor... Full Article
One of the tricks that Java allows us to employ is to change the control flow of the application using exceptions. This is generally strongly discouraged, since it makes the code hard to decipher. In addition, exceptions are notoriously bad at performance. Here is a trick used in RIFE to make ... Full Article
In this Java Specialists' Newsletter, we look at a simple Java program that solves SuDoKu puzzles. Full Article
Java 5 adds a new way of casting that does not show compiler warnings or errors. Yet another way to shoot yourself in the foot? Full Article
When we make proxies that wrap objects, we have to remember to write an appropriate equals() method. Instead of comparing on object level, we need to either compare on interface level or use a workaround to achieve the comparisons on the object level, described in this newsletter. Full Article
We review Java Concurrency in Practice by Brian Goetz. Brian's book is the most readable on the topic of concurrency in Java, and deals with this difficult subject with a wonderful hands-on approach. It is interesting, useful, and relevant to the problems facing Java developers today. Full Article
In this newsletter we look at the difference in performance between cloning and copying an array of bytes. Beware of the Microbenchmark! We also show how misleading such a test can be, but explain why the cloning is so much slower for small arrays. Full Article
The Strategy Pattern is elegant in its simplicity. With this pattern, we should try to convert intrinsic state to extrinsic, to allow sharing of strategy objects. It gets tricky when each strategy object needs a different set of information in order to do its work. In this newsletter, we look ... Full Article
Sometimes you need to download files using HTTP from a machine that you cannot run a browser on. In this simple Java program we show you how this is done. We include information of your progress for those who are impatient, and look at how the volatile keyword can be used. Full Article
Someone asked me yesterday what the maximum inheritance depth is in Java. I guessed a value of 65535, but for practical purposes, not more than 5. When I asked performance guru Kirk Pepperdine to estimate, he shot back with 63. In this newsletter, we look at the limitations in the JVM and exam... Full Article
What do you do when an object cannot be properly constructed? In this newsletter, we look at a few options that are used and discuss what would be best. Based on the experiences of writing the Sun Certified Programmer for Java 5 exam. Full Article
The book "Wicked Cool Java" contains a myriad of interesting libraries, both from the JDK and various open source projects. In this review, we look at two of these, the java.util.Scanner and javax.sql.WebRowSet classes. Full Article
A simple database viewer written in Java Swing that reads the metadata and shows you all the tables and contents of the tables, written in under 100 lines of Java code, including comments. Full Article
Sometimes frameworks use reflection to call methods. Depending how they find the correct method to call, we may end up with IllegalAccessExceptions. The naive approach of clazz.getMethod(name) is not correct when we send instances of non-public classes. Full Article
Don't Repeat Yourself. The mantra of the good Java programmer. But database code often leads to this antipattern. Here is a neat simple solution from the Jakarta Commons DbUtils project. Full Article
A few weeks ago, I tried to demonstrate the effects of old vs. new generation GC. The results surprised me and reemphasized how important GC is to your overall program performance. Full Article
When we change libraries, we need to do a full recompile of our code, in case any constants were inlined by the compiler. Find out which constants are inlined in this latest newsletter. Full Article
A problem that I encountered when I first started using enums was how to serialize them to some persistent store. My initial approach was to write the ordinal to the database. In this newsletter, I explore some ideas of a more robust approach. It will also show you some applications of Java ge... Full Article
This book is a fantastic introduction to Design Patterns, probably the best available. In this newsletter, I look at some of the winning formulae used in the book, and explain why they work. I also give some tips of where I disagree with the book and some additional information that will be use... Full Article
ArrayList is faster than LinkedList, except when you remove an element from the middle of the list. Or is it? Full Article
Java does not use the "goto" statement, although it is a reserved word. We do have something similar though: labeled breaks. Full Article
Instead of auto-generating our hashCode() and equals() methods, why not use the strategy pattern to do this for us? In this newsletter, we examine different approaches and their benefits. Full Article
The object adapter pattern is similar in structure to the proxy pattern. This means that we can use the dynamic proxy mechanism in Java to also implement a dynamic object adaptor. Full Article
Enumeration was the interface in Java 1.0 that has now been superceded by Iterator. It is still in widespread use. In this newsletter we look at how we can use Enumeration with the new for-in statement. Full Article
Our earlier solution to multi-line cells in JTable did not work in Java 1.4. We show a new version that does. Full Article
Java 5 has some interesting performance optimizations than can make our code faster without our intervention. We look at some of the new features. Full Article
Swing is famous for its "refresh bug", where the application stops refreshing the screen. This happens when the Event Dispatch Thread (EDT) is blocked, either temporarily by a long operation or permanently because of a deadlock. In the newsletter we look at a technique for sounding the alarm. Full Article
Java 5 introduced the Iterable interface, used by the enhanced "for" statement to iterate. Collection extends Iterable, but we can also write our own classes that implement it. This way we can use the enhanced "for" statement to iterate over them. Examples would be ResultSet and InputStream. Full Article
To optimize autoboxing, Java caches boxed integers in the range -128 to 127. We examine what happens if this cache were to get corrupted. Full Article
A follow-up to explain that the previous code was not the "refresh bug", but rather an issue with the static initializer starting a thread and that thread calling a static method. Full Article
Swing uses several locks. When several threads work with the GUI at the same time, it is not always easy to determine the order of the locks. This can result in deadlocks, the famous "refresh bug". Full Article
How can you become an excellent Java programmer? Is it an inherent trait or something you can learn? Can you learn Java if you are already over 30? Over 40? Over 60? In this newsletter I give some tips on how to become a Java programming expert. Hint: It's not as easy as it looks. But it's... Full Article
In Swing, we can make GUIs be oriented either from left to right, as most countries do, or from right to left, as you would find in Arabic and Hebrew. Full Article
Soft and weak references allow us to control how long objects stay live if they do not have strong references to them. Weak references can help us avoid memory leaks by breaking circular dependencies. Soft references can help us cache objects, recreating them when running low on memory. Full Article
In this newsletter, we have Amotz Anner show us how we can map objects to XML files using the new Java 5 annotations. Full Article
Final fields could not be set with reflection in Java 1.1. In Java 1.2 they changed it so that we could set final fields. We again couldn't in Java 1.3 and 1.4. Since Java 5, we can again set final fields. Full Article
Do generics make the code easier or harder to read? Anything new can be challenging on the eyes, but time will tell whether generics will be as popular as we expect. Full Article
The java.util.Properties class can load and store the properties in an XML file. We furthermore periodically check whether the file has changed and if so, reload the properties. Full Article
Fields can either be initialized where they are declared or in the constructor. Some programmers set them twice. We have a look at how final fields avoid this. Full Article
Deadlocks between synchronized monitors are impossible to resolve in Java. In this newsletter we look at a new MXBean that can detect deadlocks between threads and use it to warn us. Full Article
Since Java 5, we have a JVM system thread constantly monitoring our memory usage. If we exceed our specified threshold, it will send us a notification. We can use this to get an early warning of possible trouble. Full Article
We use the java.awt.Robot to control machines remotely with Java, typing keys, moving the mouse and sending back screenshots. This can help instructors assist remote students. Full Article
We look at the new Java 5 features: Generics, autoboxing and the for-in statement. It should make our code more maintainable without sacrificing performance. Full Article
Java 5 introduced the UncaughtExceptionHandler. We can set it globally or per thread. This helps us to manage uncaught exceptions better. Full Article
Object streams maintain caches on the input and output. This helps with avoiding StackOverflowError when we have circular references. It also saves bandwidth if we transmit the same objects several times. However, this can also cause a memory leak. Full Article
A handy class shipped in the JDK is sun.reflect.Reflection. It allows us to find out which class called our method. Note that this class might become unavailable in future versions of Java. Full Article
Follow-up to show another approach that works even better for initializing fields prior to the call to super(). Full Article
We cannot execute any code before calling the superclass constructor. Or can we? Read more to find out. Full Article
One of my favourite software development books, this one takes a good hard look at how to be a programmer in the real world. Surprisingly thin for a book with this much substance, I refer to the ideas in here all the time. The pragmatic bunch have built an entire industry around their software ... Full Article
We have a look at how to build a simple webservice with Java. Full Article
Two easy Java puzzles to test your understanding of try-finally. Full Article
Another small puzzle to test your knowledge of Java. Full Article
The ordinary Swing JCheckBox has only two states. We present a new component that is based on the old JCheckBox, but which has three states. Full Article
When an exception occurs in Swing code, it is typically printed to the console, assuming we have one. On some systems the Swing thread is then stopped. In this newsletter we present a way that we can intercept the exception and display a warning dialog. Full Article
We have heard that we can only have one public class per .java file. But that is not entirely true. We could, in theory, have many public static inner classes inside one public class. Full Article
Instead of coding the toString() method repeatedly by hand, we present several approaches to generate the String automatically. Full Article
Our old MemoryCounter needed to be updated for Java 1.4. In previous versions of Java, each primitive field used at least 4 bytes, even a boolean. This changed in Java 1.4, where boolean and byte use a 1 byte, short and char use 2 bytes, int and float use 4 and long and double use 8. Full Article
In the early days of Java, the Sun Microsystems engineers still had the freedom to write hilarious comments into their code. Full Article
A common pattern is the Java Monitor Pattern. All public methods are synchronized. Private methods would assume that the lock is already held. How can we verify this? In this newsletter we show how we can assert that we hold the lock inside the private methods. Full Article
Instead of programmatically setting the wait cursor, we can also let the java.awt.EventQueue do the heavy lifting for us. Nathan Arthur explains how. Full Article
Instead of using Rapid Application Development (RAD) tools for building GUIs, we can use GoF factory methods to create our user interfaces with code. Full Article
LinkedHashMap gives us a map that retains the order in which elements were inserted. This can help us maintain a dictionary of key-value pairs in the same order as they were read in. Full Article
We learn how we can download images from within Java and then display them in a JFrame. Full Article
Overloading of methods refers to multiple methods with the same name, but different parameter types. As convenient as this feature is, we should use it sparingly. This newsletter explains why. Full Article
We have a look at the creation cost of multi-dimensional arrays in Java. Full Article
Multi-dimensional arrays in Java are simply arrays of arrays. This can have consequences in CPU and memory performance. Full Article
Quick update on the results of the last survey. Only 15.53% knew the correct answer! Full Article
We look at the difference in bytecode between using ints and bytes. We also compare a += b and the longer a = a + b. They are not equivalent. Full Article
Java compilers convert Strings appended with + to StringBuffer. The generated bytecode is compiler specific, with javac and the Eclipse compiler producing slightly different results. Full Article
A typical first computer language used to be BASIC. It had a bad reputation for producing spaghetti code, due to the GOTO statement. We show how switch-case and exceptions in Java can look like BASIC. Full Article
In this book, Jack outlines the process used to make Java systems run faster. He gives lots of tips on how to find your bottlenecks and then also gives specific tricks to make your code just that bit faster. A must-have for Java programmers who care about the speed of their programs. Full Article
Coding Swing can be tricky. There are a lot of strange edge cases. One of the harder things to get right are the wait cursors, specifically in conjunction with modal dialogs. We will learn how to set the wait cursor on the parent window/frame of a modal dialog. Full Article
Before running a microbenchmark, it can be instructive to examine the code using a tool javap. This shows us the bytecode of the compiled class. Full Article
Stack traces give us a clue of which method called us, giving us a form of caller ID. Full Article
Java 1.4 changed inner classes slighty to set the link to the outer object prior to calling super(). This avoids some hard to explain NullPointerExceptions. Full Article
Inner classes have magic handles to the outer object and provide synthetic methods to acces private data. This can result in some hard-to-understand bugs. Full Article
The Singleton pattern allows for a single instance to be shared throughout the program. The question we will answer is how to initialize this. Full Article
For years, programmers have spread the misinformation that it was necessary to set local variables to null to avoid memory leaks. Fortunately Java is smart enough to do that without our help. Full Article
In this follow-up to our earlier newsletter on "When arguments get out of hand...", we look at the constant pool in Java classes and how this can be affected by how we compile our class. Full Article
We turn the dial to full blast and find out how many parameters a method may contain. Wholly impractical, but fun. Full Article
By specifying our own RMISocketFactory, we can monitor the number of bytes that are transmitted over RMI. Full Article
A personal note of thanks to my father, who inspired me to "keep on writing". Full Article
Starting threads is easy. Shutting them down again in an orderly fashion is not. In this newsletter we explore how to use interrupts to indicate to a thread that it should cooperatively shut down. Full Article
A long time ago, James Gosling wrote Oak, which was later renamed to Java. Some of the quirky Java restrictions, for example only one public class per file, can be traced back to Oak. This newsletter looks at the Oak 0.2 specification. Full Article
The "remainder function" is a form of division. "Division" is the most expensive CPU operation. HotSpot can transform "remainder" to a cheaper "multiply" operation. When benchmarking, we need to make sure that the divisor is not constant. Full Article
One of the most significant changes in JDK 1.4 is regarding how the HashMap works internally. Instead of the remainder function, it now uses bit masking to assign keys to buckets. This change has implications on how we write our hashCode() method. Full Article
In Java 1.4, they added some cool new features. First off, toString() in collections was improved to avoid a StackOverflowError, secondly the RandomAccess interface was introduced and lastly, the JavaDocs were improved to also contain specifications of what unchecked exceptions to expect. Full Article
Singleton is one of the most recognizable design pattern from the Gang of Four book. We read how David Jones applies it to J2EE. Full Article
Import statements can get out of date quickly as we refactor our code. In this newsletter, our guest author Dr. Cay S. Horstmann shows us how we can clean up our import statements. Full Article
Source control systems give us insight into how a method has changed over time. It is usually a bad idea to comment out code, especially without adequate comments why. It confuses the person maintaining the code. Full Article
Another use of JavaDoc is to use the engine to find where comments are missing from our code. Full Article
How much do your customers love you? How should you give and receive advice? In this excellent book, we learn why it is so important to understand your customer. I use the principles daily in my work with code reviews, performance tuning and dealing with customers or clients. Full Article
Instead of writing and reading blobs as large byte[], we should rather stream the data using ResultSet.getBytes(). Full Article
We found a gem in Java 1.3, where a simple typo resulted in a strange static initializer method. Full Article
In this newsletter we have a look at how we can render a JTextArea in a JTable cell. Full Article
In our first book review, we look at an interesting book that talks about implementing numerical methods in Java. Although not primarily a Java book, it gives us some insight as to the performance of Java versus other languages like C or Smalltalk. Full Article
In Java we can use OS signals directly for detecting when a program is being closed. This can be used to write our own shutdown hook or put in whatever feature we need. Full Article
Java has some interesting ways in which we can invert a boolean value. We compare the speed of various approaches. Full Article
Swing uses the Composite design pattern for components. This means that we can place components on each other, creating new types of widgets. An example would be a JButton that also contains a JCheckBox. Full Article
When iterating over a heterogeneous collection, one way to differentiate between object types is with instanceof. Another way is to create a special visitor object that can be applied to the objects in the collection. Full Article
In this, our most misunderstood newsletter, I wax lyrically about the poor quality of comments in code. Often the comments are not in sync with what the code does. Trust them at your own risk. Full Article
In this newsletter, we modify the class Object to secretly count how many of each class are constructed. Full Article
A few questions came up in our previous newsletter, so here is a follow-up with answers. Full Article
One of the challenges Java programmers had in the early days was to get the classpath right. In this newsletter, Sydney Redelinghuys presents some ideas on how to make sure that all the entries point to actual files. Full Article
Java supports unicode in variable and method names, although we generally recommend using ASCII characters. Here we have a look at how to do it. Full Article
The JavaDoc tool can do more than just generate HTML documentation for our Java classes. We can also write our own "Doclets" to scan the source code in our project. In this newsletter we look at how we can (ab)use JavaDoc to look for classes with non-private fields. Full Article
Prior to Java 5, we had to jump through all sorts of hoops to get something like generics. In this newsletter we use "dynamic decorators" to produce type-safe iterators dynamically. Full Article
Checked exceptions are a strange design that can make Java frustrating to use. In this article we wrap it with an unchecked exception, but delegate the printing methods to the wrapped exception. Full Article
One way to protect ourselves from badly constructed objects is to throw an exception from the constructor. However, the object can be resurrected if the class is non-final by using the finalize() method. Full Article
When I first started using Java in 1997, I needed very large hash tables for matching records as quickly as possible. We ran into trouble when some of the keys were mutable and ended up disappearing from the table, and then reappearing again later. Full Article
We learn how to build a simple, yet usable, cross-platform registry editor using standard Java. Full Article
In this newsletter, we learn how to do network multicasting in Java using the Datagram class. Full Article
ArrayList can become slow when used as a FIFO queue. Whenever an element is removed from the head, the other elements need to be moved one space to the left. This is an O(n) operation and slows down the remove(0) operation the longer the list becomes. In this newsletter we describe a CircularA... Full Article
Packages should have versions numbers embedded in the Jar file's manifest. Our guest author Herman Lintvelt shows us how. Full Article
No, this is not our "final" newsletter, but rather a newsletter about the "final" keyword. Full Article
If we were to use a List as a Queue, which would be better: ArrayList or LinkedList? Turns out that it depends on the length of the list. In this newsletter we try write a self-tuning queue, which swaps over to a suitable implementation based on the number of current elements. Full Article
Prior to Java NIO, we needed one thread per socket. In this newsletter we show how we can use timeouts on the sockets to simulate something like non-blocking IO. Full Article
In this newsletter, Dr Christoph Jung amazes us by showing how we can build a minimalist application server by playing around with class loaders. Full Article
In Java all methods are virtual, meaning that the most derived method is always called. In earlier versions of Java, it was possible to trick the JVM by replacing the superclass with another wheere the method is defined as "private". Full Article
In this newsletter, we serialize Java objects into a byte[] and then write that into a PreparedStatement with setBytes(). Full Article
We keep a list of created Frame instances handy, so that we can find them again when we create Dialogs. This prevents ownerless modal Dialogs from causing issues. Full Article
Classes loaded by different ClassLoaders are considered distinct, even when they have the exact same name and bytecode. Full Article
A quick follow-up to our newsletter on abusing exceptions to simulate the switch construct, looking at the performance in comparison to other approaches. Full Article
The try-catch construct can be used for program flow control. In this newsletter we abuse it to simulate the switch statement. Full Article
In the days before BlockingQueue was added to Java, we had to write our own. This newsletter describes an approach using synchronized and wait()/notify(). Full Article
We all know WeakHashMap, which has WeakReferences to the keys and strong references to the values. In this class we instead have SoftReferences to the keys. This means that entries will typically be removed once we get low on memory, rather when there are no more references to the keys. Full Article
Some crazy antics as we modify the contents of the char[] embedded within Strings. Of little practical value, except to gain some understanding of how things work under the covers. Full Article
The previous newsletter had a dependency that stopped us serializing the components. The code worked when compiled with JBuilder 2, but not when compiled with the JDK 1.3. Full Article
Thousands of classes implement the Serializable interface, meaning we can write them over an ObjectOutputStream. Amongst these is java.awt.Component, the superclass of all GUI classes in AWT and Swing. We can thus serialize JTable, JLabel, even JFrame. Full Article
In Swing, we sometimes need to set the focus to the second component. This newsletter describes how to do it. Full Article
System.exit() does not immediately shut down the Java Virtual Machine. Instead, it first runs our shutdown hooks, albeit in an undefined order. Once they are done, the JVM stops for real. Full Article
Layout managers in AWT/Swing can be frustrating to use. After trying various combinations, my colleague gave up and asked me for help. Instead of battling with GridBagLayout, we wrote our own LayoutManager. It was surprisingly simple and very effective. Full Article
Usually in Java, polymorphism is done depth-first. This is the reason why in Java 5, classes implementing Comparable cannot be further specialized to another Comparable type (compareTo takes an Object). In this newsletter we look at how we can change this to breadth-first polymorphism. Full Article
Java was based on ideas taken from C/C++, but the designers of the language tightened up the language significantly. In C/C++, a zero (0) means false and non-zero (e.g. 1) means true. In this newsletter, we examine how we should be comparing booleans. Full Article
In this newsletter, we learn how we can create our own EventQueue and then use that to intercept all the events that arrive in AWT/Swing. Full Article
Did you know that it is possible to define inner classes inside interfaces? This little trick allows us to create method objects inside an interface. Full Article
Dynamic proxies can help us reduce the amount of code we have to write. In this newsletter, our guest author, Dr Christoph Jung, gives us a short tutorial on how the dynamic proxies work. Full Article
We look at some tricks on how we can track where things are happening in our code, which can then be used for producing more detailed logging. Full Article
In this newsletter we look at how we can write a TeeOutputStream that works similarly to the unix "tee" utility and pipes the output to two different OutputStreams. We can then reassign System.out to be written to a file and to the old System.out. Full Article
Anonymous inner classes allow us to call super class methods inside its initializer block. We can use this to add values to a collection at point of creation, for example: new Vector(3) {{ add("Heinz"); add("John"); add("Anton"); }}); Full Article
Java deadlocks can be tricky to discover. In this very first Java Specialists' Newsletter, we look at how to diagnose such an error and some techniques for solving it. Full Article
Get: every new article, exclusive invites to live webinars, our top-10 articles ever, access to expert tutorials & more!
Java Champion, author of the Javaspecialists Newsletter, conference speaking regular... About Heinz
We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations.
We can help make your Java application run faster and trouble-shoot concurrency and performance bugs...
We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations. Find Out More