Posts

Showing posts with the label updated

Updated Biography

Peter Lawrey is an Australian/British software engineer and entrepreneur best known for work on ultra-low-latency Java systems and for leading the open-source OpenHFT libraries. He is the founder and chief executive of Chronicle Software, a London-based company whose technology is used in trading and market-infrastructure workloads. Lawrey is also a recognised Java community figure: he was named a Java Champion in 2015, has been described by conference organisers as having provided the most answers for the Java and JVM tags on Stack Overflow, and writes the long-running Vanilla Java blog. ( Chronicle Software , javachampions.org , qconnewyork.com , blog.vanillajava.blog ) Career Lawrey founded and leads Chronicle Software, which builds enabling technology for event-driven trading and market-data platforms. The company states that its software underpins systems at several tier-one banks; a 2024 press announcement similarly described Chronicle as supplying "8 of the t...

Java Arrays, Wat!

Java arrays are a fundamental component of the language, yet they can exhibit behaviours that surprise even seasoned developers. This article delves into some of these quirks, providing clarity and practical insights for Java developers. Is it an Array or Not? Consider the following declaration: Serializable [] array2 = new Serializable [ 9 ]; Serializable array = array ; Cloneable [][] arrayA = new Serializable [ 9 ][]; Cloneable [] arrayB = arrayA ; Cloneable arrayC = arrayA ; At first glance, one might question whether array is an array or a scalar. In reality, array is a scalar reference that points to an array. This behaviour is consistent across Java’s type system. For instance: Object o = new Object [ 9 ]; Here, you can assign an array to an Object variable because arrays are also objects in Java. Additionally, arrays are Serializable and Cloneable , so they can be assigned to a Serializable or Cloneable reference...

Some Common Java Gotchas and How to Avoid Them

Advanced Java Questions These questions delve into Java’s more intricate behaviours and are often too advanced for typical interviews, as they might be discouraging for candidates. However, they are excellent for deepening your understanding of Java’s core workings in your own time. Myth 1: System.exit(0) Prevents finally Block Execution Consider the following code: System . setSecurityManager ( new SecurityManager () { @Override public void checkExit ( int status ) { throw new ThreadDeath (); } }); try { System . exit ( 0 ); } finally { System . out . println ( "In the finally block" ); } This code will output: In the finally block Explanation : The System.exit(0) call triggers the checkExit method in the custom SecurityManager . By throwing a ThreadDeath exception instead of terminating, the finally block is allowed to execute, explaining the "In the finally block" output. Since Th...

Why Math.round(0.499999999999999917) rounds to 1 on Java 6

Overview There are two types of error representation error and arithmetic rounding error which are common in floating point calculations. These two error combine in this simple example, Math.round(0.499999999999999917) rounds to 1 in Java 6. Representation error Floating point is a base 2 format, which means all number are represented as a sum of powers of 2. e.g. 6.25 is 2^2 + 2^1 + 2^-2. However, even simple numbers like 0.1 cannot be represented exactly. This becomes obvious when converting to BigDecimal as it will preserve the value actually represented without rounding. new BigDecimal(0.1)= 0.1000000000000000055511151231257827021181583404541015625 BigDecimal.valueOf(0.1)= 0.1 Using the constructor obtains the value actually represented, using valueOf gives the same rounded value you would see if you printed the double When a number is parsed, it is rounded to the closest represented value. This means that there is a number slightly less than 0.5 which will be rounde...

Special non-exceptions.

Overview There are a couple of Throwables which have surprising properties. Throwable can be extended When extending Throwable it is checked by the compiler, through is not an Exception. public static void main(String... args) throws MyThrowable { throw new MyThrowable(); // will not compile unless MyThrowable is handled. } class MyThrowable extends Throwable { } This prints out the MyThrowable with a stack trace as expected. The slient Error A throwable which extends ThreadDeath is silent as it is deadly. ;) public static void main(String... args) { throw new MyThrowable(); } class MyThrowable extends ThreadDeath { } When this runs, no error/exception is printed, the thread just exits. This is because the error/exception is printed by ThreadGroup.uncaughtException() which ignores instanceof ThreadDeath by default. The ThreadDeath error is used by Thread.stop() and although this method is deprecated, the ThreadDeath error is not deprecated and even describes itself ...

StringBuffer is dead, long live StringBuffer

Overview StringBuilder was introduced seven years ago as a replacement for StringBuffer where you didn't need thread safety. From the Javadoc for StringBuilder This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations. StringBuffer is dead? So you might believe that StringBuffer is basically dead because it has very few uses which cannot be replaced by StringBuilder and those are neatly wrapped by classes like StringWriter. However, if the JDK is anything to go by, having a drop in replacement is just not enough to get people to migrate existing code. Class Uses in the Java 6 update 25 src.zip StringBuffer    1,409 StringB...

What can make Java code go faster and slower.

Overview Something is fairly widely known is that the JVM optimises code as it runs.  This can result in code running much faster as you execute it many times. However, something not so well understood is what you do before a section of code can slow it down. Warming up code int[] display = {0, 1, 10, 100, 1000, 10000, 20000, 100001}; for (int i = 0; i = 0) System.out.printf("%,d: Took %,d us to serialize/deserialze " + "GregorianCalendar%n", i, time / 1000); } outputs 0: Took 34,751 us to serialize/deserialze GregorianCalendar 1: Took 1,551 us to serialize/deserialze GregorianCalendar 10: Took 1,474 us to serialize/deserialze GregorianCalendar 100: Took 1,010 us to serialize/deserialze GregorianCalendar 1,000: Took 264 us to serialize/deserialze GregorianCalendar 10,000: Took 151 us to serialize/deserialze GregorianCalendar 20,000: Took 95 us to serialize/deserialze GregorianCalendar 100,001: Took 91 us to serialize/deserialze...

How *slow* can you read/write files in Java?

A common question on stackoverflow is; Why is reading/writing from a file in Java so slow? What is the fastest way? The discussion often compares NIO vs IO. However the read/writing is usually not the problem and the comparison has little importance. To demonstrate this, I am going to show the one of the simplest/slowest ways to read/write text which is slower than writing binary in NIO or IO but is fast enough IMHO for most use cases. The following program prints the following output. Wrote 101 MB/s. Read 109 MB/s. If 100 MB/s is fast enough, it really shouldn't matter which way you read/write data to disk. Note: For very large files, this result depends on the speed and configuration of your disks. In which case, you need to look at how your hardware, don't blame your software. // generate a string with full of A's char[] chars = new char[40]; Arrays.fill(chars, 'A'); String text = new String(chars); final File file = new File("/tmp/a.txt"...

More uses for dynamic code in Java.

In 2008 I wrote a library for compiling and running dynamic code in Java. Essence JCF At the time the purpose was to load configuration files which were written in Java rather than XML or properites files. One advantage this library has is that it can load into the current class loader, rather than requiring an additonal class loader so the interface or class can be used immediately in code without the need for reflection. See below for an example. For me, it has been a very cool solution without a unique problem to solve. i.e. there wasn't a problem it solved particularly well. Since then, I have come across a few situations where it is particularly useful. Objects in direct memory Using dynamically generated code, you can build a data store from an interface which is row based or column based, stored either in the heap or in direct memory. Both can reduce the number of objects created improving cache locality and reducing GC times. Precompile expressions Expressions which are ...

Two uses for enum most people forget.

The enum can be used to create enumerated values and even many instances with different implementations but there are two simple uses which are appear to be under utilised. The utility class A utility class is a class with no instances. To declare this as an enum is trivial. You just give it no instances. public enum MyUtils {; public static String process(String text) { /* ... */ } } The singleton A singleton which is a class which has one and only one instances, ideally loaded lazily. Using the lazy loading of classes can give the same benifit in a simpler/thread safe way. To declare a singleton as an enum, you give it one instance and only reference the instance rather than the class. public enum Singleton implements SingletonService { INSTANCE; public String instanceMethod(String text) { /* ... */ } } An enum can implement an interface, allowing it to be mocked out where ever the interface has been used.

Gotcha: Save on objects and get more Full GCs.

We have system which is latency sensive and object light. However as we tuned the system to run less minor collections we saw the number of Full GCs increase. Some investigation found that there is a timer for RMI which checks if a GC has occurred in the last hour and if it hasn't performs a Full GC. :P If you are not really using RMI, this is undesireable. There are two command line options which can be increased to reduce the number of these only-for-RMI Full GCs. Increasing just one has no effect. The defaults are: -Dsun.rmi.dgc.server.gcInterval=3600000 -Dsun.rmi.dgc.client.gcInterval=3600000 For more details bug id 6200091 See line 109 of The sun.misc.GC.Daemon class

Stupidly long class name or a geeky poem?

In the JRE is a stupidly long class name, only a code generator could produce such a long name. (Which the developer of the code generator never checked I assume) com.sun.java.swing.plaf.nimbus. InternalFrameInternalFrameTitlePaneInternalFrameTitlePaneMaximizeButtonWindowNotFocusedState Or is it a geeky poem burried in the code? InternalFrame InternalFrame Title Pane, Internal Frame Title Pane. Maximize Button Window, Not Focused State. The moral of the story, always check the readability/sanity of generated code.

OMG: Using a triple cast.

I have used double casts before but today found myself writing a triple cast. :P The situation was; I need a method which returned the default value for a type. public static <T> T nullValue(Class<T> clazz) { if (clazz == byte.class) return (T) (Byte) (byte) 0; // other primitive types handled. return null; } Certainly this is casting madness. So I wrote the method a different way. static { NULL_MAP.put(byte.class, (byte) 0); // other primitive types handled. } public static <T> T nullValue(Class<T> clazz) { return (T) NULL_MAP.get(clazz); } There the same casting is going on, but one cast is implied and the other two are seperated. Its not as ugly and more efficient. :)

Calculating an average.

A long standing bug in many algorithims is using the obvious int m = (h + l)/2; The problem with this is that (h + l) can overflow for large values of h and l. One alternative is a cumbersome int m = l + (h - l)/2; Or the one I prefer is using >>> to perform an unsigned divide by two int m = (h + l) >>> 1; For example, say m, h and l where bytes and h = 100 and l = 90. In the first case, h + l is -65 due to the overflow, so m = -32. (incorrect) In the second case, h - l is 10, so m = 95 (correct) In the last case, h + l is -65 or 10111110 in binary. Unsigned shifting right by 1 is 1011111 or 95. (correct)

Locking a ConcurrenthashMap for exclusive access.

A friend recently pointed me to an acticle on ConcurrentHashMap which indicated to him that you can't lock a ConcurrentHashMap for exclusive access. This came as a surprise to me as I have been doing just that for years. Hashtable and Collections.synchronizedMap achieve thread safety by synchronizing every method. This means that when one thread is executing one of the Map methods, other threads cannot until the first thread is finished, regardless of what they want to do with the Map. In most cases, ConcurrentHashMap is a drop-in replacement for Hashtable or Collections.synchronizedMap(new HashMap()). However, there is one significant difference -- synchronizing on a ConcurrentHashMap instance does not lock the map for exclusive use. In fact, there is no way to lock a ConcurrentHashMap for exclusive use -- it is designed to be accessed concurrently. https://www6.software.ibm.com/developerworks/education/j-concur/j-concur-a4.pdf This appears confused to me. On the one hand it state...