Showing posts from June, 2011

Being as fast as possible is a bad idea

Overview When you design a system which must perform, a common assumption is that you need to it to be as fast as possible. However this needs to be qualified and not having a clear idea of how much performance you need can mean you spend more money, waste time or impact your design more than needed. The first question is knowing whether it is latency, throughput or both which are required. Often only one really matters. A low latency usually gives you a high throughput. If only throughput is required using parallelism is often a cost effective solution. Should you only design a system to be just what you need? It is a brave move to only design a system to do exactly what you need and no more. This is because systems often behave as well as they should on paper. The other reason is that systems tend to vary in their performance due to the complexity of their systems. End users tend to remember the worse performance they ever got making the occasion slow performance more sign

Java Secret: What is called before main.

Overview The starting point for core java applications is the main(String[]) method. But is there any code which is called before this method and do we even need it? The class has to be initialised Before calling main, the static block for the class is called to initialise the class. public class Main { static { System.out.println("Called first."); } public static void main(String... args) { System.out.println("Hello world."); } } prints Called first. Hello world. Can we avoid having a main() Normally, if you don't have a main() method, you will get an error. However if your program exits before calling main() no error is produced. public class Main { static { System.out.println("Hello world."); System.exit(0); } } prints Hello world. The premain method If you have Java agents, those agents can have a premain method which is called first. Instrument package public static void premain(St

Java Secret: More uses for varargs

Overview Varargs have many uses from simplifying code. However, they are not always used as often as they could be. Use in reflections Calling a method via reflections is fairly ugly without varargs. ClassLoader cl = Thread.currentThread().getContextClassLoader(); Method defineClass = cl.getClass().getDeclaredMethod("defineClass", new Class[] { String.class, byte[].class, int.class, int.class}); defineClass.setAccessible(true); defineClass.invoke(cl, new Object[] { myNewClassName, myByteCode, 0, myByteCode.length }); With varargs, the code appears cleaner. ClassLoader cl = Thread.currentThread().getContextClassLoader(); Method defineClass = cl.getClass().getDeclaredMethod( "defineClass", String.class, byte[].class, int.class, int.class); defineClass.setAccessible(true); defineClass.invoke(cl, myNewClassName, myByteCode, 0, myByteCode.length); Use of varargs for optional arguments System.out.printf use varargs which might be optional. System.o

Queues with Threads to be avoided.

Warning: Contains some ranting. ;) It baffles me why so many developers use Queue and Thread explicitly when there is an ExecutorService built in which does both much more elegantly. This has been part of Java 5.0 since 2004 and was available as a third party library many years before that. There are specific cases where using a Queue and Thread is the best choice but that doesn't appear to be the reason it is done most of the time. Is it a lack of understanding of these core libraries? Is it because that is how it is done in other languages and people are bringing the patterns they know to Java? I wonder if developers get some satisfaction doing things the hard way. There is a greater sense of achievement when you have written some really complex code? Any other theories welcome. ;) Examples of developers doing things the hard way. Using a text editor for development instead of an IDE Using double checked locking lazy Singleton instead of an enum with one instance

4000 hits today.

I am pleased to say my blog got 4000 hits today, a record me. ;) Thank you everyone for taking an interest and reading my articles, it motivates me to post more.

Java Secret: Using an enum to build a State machine.

Overview The enum is Java is more powerful than many other languages which can lead to surprising uses. In this article, I outline some the individual features of enum in Java, and put them together to form a state machine. Enum for Singleton and Utility class You can use an enum as a Singleton or Utility very simply. enum Singleton { INSTANCE; } enum Utility { ; // no instances } Enum to implement an interface You can also implement an interface in an enum. interface Named { public String name(); public int order(); } enum Planets implements Named { Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune; // name() is implemented automagically. public int order() { return ordinal()+1; } } Each Enum Instance a different sub-class You can override the behaviour of an instance. This effectively give the instance a different sub-class of the enum with its own implementation. // from,5.0/docs/guide/language/e

Java Insanity: Two methods with the same super.method()

Overview Recently I wrote an article on how you could write multiple methods with the same name and parameters by using generics. I wondered if you can have multiple methods with the same super.method() Generics and signatures The way the Java compiler works, the generic is effectively part of the signature. However, due to type erasure, the JVM doesn't care so how can this work? The answer is that for the JVM the return type is part of the signature. This means if you have two method with different generic signatures and return types they can have the same name and parameter types. For the purposes of determining a parent super.method(), they share the same method. So if you have two methods overriding a method, which one is actually called. The answer is neither, polymorphism breaks and the parent still gets called. static class A { public Number method() { System.out.println("Inside: Number A.method()"); return 0; } } static class B

Java Secrets: Using ExecutorService to run many background tasks.

Overview Java has had support for thread pools for a many years, but using them is still black art for many. Part of the problem is that misusing a thread pool will make a program run slower not faster and cause the program to crash or even hang the system. I often see people trying to use a queue, or wait/notify and thread(s) when an ExecutorService does all this for you. Choosing the right thread pool For different situations, different pools are useful. Sometimes it makes sense to have more than one to take advantage of their different characteristics. Thread pool type How to create uses disadvantages Single threaded pool Executors. newSingleThreadExecutor(); Useful to event processing e.g. logs always performs tasks in order and minimises overhead Only one thread Fixed size pool Executors. newFixedThreadPool (n_threads); Useful for using many cores, possibly all cores in your system Always has the same number of threads even if not used. Cached thread pool Executors. newC

How to avoid Garbage Collection

Overview The unpredictability of Garbage Collection can be a serious issue for some applications. You can play with the tuning parameters, but the simplest approach is to create less garbage. Low garbage application For low latency trading system, minimising GC time is important. The extreme case is avoid GCs all together. If you reduce the garbage produced and increase your Eden size you can reduce your GCs to once per day (as an over night task) In the case of this application the Full GC triggered at 5 am every morning takes 1-2 seconds (during the overnight maintenance window) It should be possible to extend the period between GCs to once a week. Related articles Using primitives instead of wrappers Using primitives and collections which support them More to come ...

Java Secret: Labels as an Anti-Pattern

Overview It is well known that Java has no goto . (Technically goto is a keyword, but it cannot be used any where) However, Java has continue and break which can be mis-used just like goto can. NOTE: This article is not an example what to do. It is an article which will help you better understand Java's edge cases and help you recognise mis-use. Recognising a label A Java Puzzler uses a label to create some strange looking code. public static void main(String... args) { System.out.println("Hello World"); } This compiles and runs. This is because what appears to be a URL is actually a label and a comment. ;) goto backwards If you want to go back you can use the following structure. while(true) { // do something. if(go-back) continue; // do something else. if(go-back) continue; break; } The only purpose of the loop is to allow code to jump back to the start. Using labels it co

Java Secret: Double Brace Initialization

Overview Java allow you to add initialisation blocks to a class definition. This is particularly useful in combination with anonymous classes for creating mock collections. esp for unit tests. Initializer Blocks In a class you can add blocks of code which are called during class initialisation. This are not widely used because they tend to be confusing. IMHO. public class A { private int version; { String versionText = System.getProperty("A.version", "-1"); try { version = Integer.parseInt(System.getProperty("A.version", "-1")); } catch (NumberFormatException nfe) { System.err.println("Unable to parse A.version "+versionText); version = -1; } } } In this class, the initialisation of version is too complex to write in one statement. An initializer block has been used which is section of code which is added to the constructor (in this case, the default cons

Java Secret: InheritableThreadLocal

Overview If you follow functional programming methodologies, every dependency for a function is passed to it including all dependencies of the functions its calls etc. This model can work very well because it makes it clear all the values which a piece of code depends on. However, it can mean passing dependencies through code which shouldn't need to know about these values. (Or in fact cannot be changed to include them) Using a ThreadLocal A way to avoid passing values over level of calls which don't know anything about them is to use a ThreadLocal. This allows you to set a value which is available at any point in the call stack in a thread safe way. Its like passing a ball into the air you want to run and catch later. static final ThreadLocal userName = new ThreadLocal (); public static void main(String... args) { userName.set("Jane"); Runnable run = new Runnable() { @Override public void run() { String threadName = Thr

Java Secret: LRU cache in Java.

Overview Since Java 1.4, Java has had a support for a LRU (least recently used) cache. Very few seem to know about it even though it can be very useful. LinkedHashMap as an LRU Cache This class has a couple of features which allows it to support an LRU cache. The default order for LHM is the order entries are added, but you can change the order so it can be ordered by last accessed. Another feature is the removeEldest method which allows you to specify whether the eldest entry should be implicitly removed. Used in combination we have an LRU cache. public static <K,V> Map<K,V> lruCache(final int maxSize) { return new LinkedHashMap<K,V>(maxSize*4/3, 0.75f, true) { @Override protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { return size() > maxSize; } }; } This cache is not thread safe and you would need to wrap it in Collections.synchronizedMap() if you needed thre

Are String, Date, Method immutable?

Overview There are many forms of immutability and each can have different uses. It is worth knowing the difference between them. Immutable classes are simpler to reason about and are very useful in multi-threaded contexts as they do not suffer from thread-safety issues. Technically Immutable An object is technically immutable if its state doesn't change after construction. This includes the primitive wrapper classes, but excludes many classes described as immutable. From Integer public class Integer { private final int value; } As you can see nothing should change after the object is created. Note: even this immutable object can be changed using reflection, however that is usually ignored for the purposes of discussing immutability. If you consider reflection, only inlined compile time constants are effectively immutable as a copy is placed in every usage. Logically Immutable A class is logically immutable provided the exposed interface never changes. The intern

Bugs: Don't use new StringBuilder(char)

Overview For StringBuilder append() , using a char can be faster than using a String . However for the constructor it doesn't do the same thing. Don't use new StringBuilder(char) When you use new StringBuilder(String) it is the similar to new StringBuilder().append(String) (If the string is large the former can be slightly more efficient) From Formatter.FormatSpecifier public String toString() { StringBuilder sb = new StringBuilder('%'); There is no StringBuilder(char) but there is a StringBuilder(int) and what it does is give the StringBuilder the initial capacity specified. This means the code is the same as follows which is unlikely to be what was intended. StringBuilder sb = new StringBuilder(37);

Best Practice: Don't use equals(null)

Overview Sometimes it is not clear when to use == or equals() however one situation where equals is never useful is with null . Don't use equals(null) From SerialRef if(!object.equals(null)) { The only class object can be is a SerialRef which doesn't implement equals() so a == comparison happens to be used. However this is not clear and a different implementation could be used which doesn't do this. A better alternative would be if(object != null) { which is probably what was intended.

Best Practice: Don't create instances of Utility classes.

Overview A utility class is one which only contains static methods. No instance of the class is required and can be confusing is one is created/used. Avoid creating a Utility class instance From InetAddress.static impl = (new InetAddressImplFactory()).create(); The InetAddressImplFactory instance is created for a single method call, however all methods for this class are static, making the instance pointless and possibly confusing. Using a private constructor for a Utility class is not always enough A common practice to avoid creating utility class instances is to use a private constructor. The problem being that an instance can still be create in the same or nested classes. From JMX Utility class static final JMX proof = new JNX(); private JMX() { } As JMX only has static methods, you might be wonder what it is used for.... From DescriptorCache static DescriptorCache getInstance() { return instance; } public static DescriptorCache getInstance(JMX proof) { if(proo

Bugs: Don't use co-variant equals and compareTo

Overview When it comes to comparing objects it is tempting to write in class A; equals(A) or compareTo(A). However these methods may not be called the way you expect if they don't overridden the default equals(Object) or compareTo(Object) Don't implement equals(Class) From Area public boolean equals(Area area) { } The problem is that many methods expect to call equals(Object) and won't call this method. Area a = new Area(); Object o = a; Area a2 = (Area) a.clone(); System.out.println("a.equals(o) is "+a.equals(o)); System.out.println("a2.equals(o) is "+a2.equals(o)); System.out.println("a2.equals(a) is "+a2.equals(a)); List areas = new ArrayList (); areas.add(a); System.out.println("areas.contains(a) is "+areas.contains(a)); System.out.println("areas.contains(a2) is "+areas.contains(a2)); prints a.equals(o) is true a2.equals(o) is false a2.equals(a) is true areas.contains(a) is true areas.contains(a2) is false Don&#

Best Practices: Don't make the finalize() method public.

Overview finalize() can be so easily mis-used and cause serious performance problems for your system that many recommend not to use it. However something your shouldn't do is make it public. Don't make finalize() public From ServiceRegistry public void finalize() throw Throwable { deregisterAll(); super.finalise(); } If you have clean up functionality you want the caller to make e.g. close(); use a different method. In this case, the only method used is public, so there is no good reason to make the finalize() method public.

Performance Tip: Avoid creating an Object to convert between a primitive and String.

Overview One way of parsing a String or converting to a String is to create the wrapper object. This is often redundant. Avoid creating an object to parse a primitive From ExsltMath.constant() return new Double(value).doubleValue(); All the wrapper class have parseXxxx() methods which take a String and give you a primitive without creating an extra object. return Double.parseDouble(value); Avoid creating a Wrapper to convert to a String From CMAny.toString() strRet.append ( " (Pos:" + new Integer(fPosition).toString() + ")" ); The creation of the new Integer is redundant. String.valueOf(int) can be used. strRet.append ( " (Pos:" + String.valueOf(fPosition) + ")" ); In this situation, if we don't use String.valueOf(), it will be called anyway. strRet.append ( " (Pos:" + fPosition + ")" ); Using String + with StringBuilder.append() can be made more efficient. strRet.append("

Performance Tip: Avoid using String + inside a StringBuilder.append()

Overview It can make sense to use String + or a StringBuilder however using them in combination is both inefficient and confusing. IMHO make the decision to use one or the other. From VMId.toString() result.append((x < 0x10 ? "0" : "") + Integer.toString(x, 16)); Here a '0' is optionally added to the start of a number. This could be written as result.append((x < 0x10 ? "0" : "")); result.append(Integer.toString(x, 16)); However using an if statement is likely to be clearer if not at least faster if (x < 0x10) result.append('0'); result.append(Integer.toString(x, 16));

Performance Tip: Avoid using a String when char will do.

Overview There are a number of operations where you can use a String or a char. In each case the char option is likely to be fastest. Use String.indexOf with a char instead of a String From URI.appendAuthority() int end = authority.indexOf("]"); if (end != -1 && authority.indexOf(":")!=-1) { In the same method, indexOf(':') is used. Appending a char instead of a String Using a char instead of a String can make a small difference. From File.slashify() if (!p.startsWith("/")) p = "/" + p; if (!p.endsWith("/") && isDirectory()) p = p + "/"; In both case a '/' could be used instead of a '/' p = p + '/';

Performance Tip: Avoid String operations which don't do anything.

Overview There are a number of String operations which don't do anything. Avoiding these may improve performance and clarity as well. Avoid String.substring(0) Even though this method doesn't do anything it can be confusing. From Mlet.removeSpace(String) String temp = ""; int k = 0; while (j != -1) { s = s.substring(k); j = s.indexOf(' '); if (j != -1) { temp = temp + s.substring(0, j); } else { temp = temp + s.substring(0); } k = j + 1; } return temp; This attempts to optimise the search by using indexOf but suffers from using + to build a string. The else block can be replaced with temp = temp + s; or even temp += s; If you look at the whole block of code, the simplest way to do the following which might not be slower. return s.replaceAll(" ",""); For speed a better option is using a StringBuilder StringBuilder sb = new StringBuilder(s.length()); for(int i=0, len=s.length(); i <

Performance Tip: Use StringBuilder instead of String for a non constant field.

Overview Appending to a String is much slower than appending to a StringBuilder. Append to a StringBuilder From Logger.entering() String msg = "ENTRY"; // later for (int i = 0; i < params.length; i++) { msg = msg + " {" + i + "}"; } Inside the loop it creates a StringBuilder and another String every time. It can be replaced with code which creates one StringBuilder and String, total. StringBuilder msgSB = new StringBuilder("ENTRY"); // later for (int i = 0; i < params.length; i++) { msgSB.append(" {").append(i).append("}"); } String msg = msgSB.toString();

Performance Tip: System.arrayCopy is usually faster than a manual array copy.

Overview Using System.arrayCopy can be cumbersome, but it has some performance advantages. Replacing a manual array copy From BigInteger.shiftLeft() for (int i=0; i < magLen; i++) newMag[i] = mag[i]; Can be replaced with System.arrayCopy(mag, 0, newMag, 0, magLen); Bonus tip: Replace a manual clone with .clone() for primitive array or arrays of immutables When a primitive array is manually copied and is created the same length, it worth using clone(). The clone() should usually be avoided due to some of its design limitations however, for primitive arrays and arrays of immutables it is the best option. From Introspector.getBeanInfoSearchPath String result[] = new String[searchPath.length]; for (int i = 0; i < searchPath.length; i++) { result[i] = searchPath[i]; } return result; Can be replaced with return searchPath.clone();

Performance tip: If you want to iterate over the keys and values use entrySet()

Overview Using entrySet() is the fastest way to get all the keys with their values. Don't use keySet() with get() From AnimationController.actionPerformed() for (Part part : map.keySet()) { if (map.get(part).isDone()) { if (partsToRemove == null) { partsToRemove = new ArrayList (); } partsToRemove.add(part); } } Using get() is much more expensive than Entry.getValue(). for (Map.Entry entry : map.entrySet()) { if (entry.getValue().isDone()) { if (partsToRemove == null) { partsToRemove = new ArrayList (); } partsToRemove.add(entry.getKey()); } }

Performance Tip: Use static fields and classes.

Overview Using a non-static field or a non-static class adds a field to each instance which may not be needed. It also improves clarity to show that a value does not change between instances or an outer class is not used implicitly. Use a static field From Writer.writeBufferSize private final int writeBufferSize = 1024; As this field is private and final it has to be the same for every instance. This makes it a constant, though its not clear this is the case. private static final int WRITE_BUFFER_SIZE = 1024; This makes it clear that every buffer will be the same size and saves a field from each instance (4-8 bytes). Use a static class The compiler will tell you if a class cannot be static. If you don't have code analysis tools, you can make an inner class static and if it compiles, it can be static. From XMLEncoder.ValueData private class ValueData { public int refs = 0; public boolean marked = false; // Marked -> refs > 0 unless ref was a target. pub

PeformanceTip: Pre-compile your patterns

Overview Building/compiling a regular expression can be expensive and is done at runtime. This can be avoided by pre-compiling the pattern. Save the pattern in a CONSTANT From UUID.fromString(String) String[] components = name.split("-"); can be replaced with public static final Pattern HYPHEN_PATTERN = Pattern.compile("-"); String[] components = HYPHEN_PATTERN.split(name, 0);

Performance Tip: Don't use StringBuilder for compile time constants.

Overview Using String + String notation is simpler than using a StringBuilder. It can be slower but for compiler time constants is faster to use. When using String + String is faster One of the few optimisations the compiler will do is inline compile time constants. String + expressions which can be evaluated at compile time and don't need to be computed at runtime. From ContextFinder.find() final String jaxbContextFQCN = JAXBContext.class.getName(); final StringBuilder resource = new StringBuilder().append("META-INF/services/").append(jaxbContextFQCN); However, the compiler can compute the resource variable to a String literal at compile time improving performance. final String jaxbContextFQCN = JAXBContext.class.getName(); // becomes a String literal. final StringBuilder resource = "META-INF/services/" + jaxbContextFQCN; Not only is this simpler, but also faster.

Performance Tip: Avoid "" + x to convert to a String.

Overview Personally I find using "" +x to be clearer and shorter than using String.valueOf(x) Some believe the later is clearer. Certainly the later is faster for the CPU, but slower for the developer. Avoid using "" + x when performance is critical Using ""+x creates a StringBuilder which is redundant (this is two objects in one) Using String.valueOf(x) is more efficient. Using StringBuilder is never more efficient because it calls String.valueOf(x) anyway. From LogManager.loadLoggerhandlers System.err.println("" + ex); ex.printStackTrace(); The use of "" + is not only inefficient, but pointless. This is because println(Object) will call String.valueOf() anyway. To make it doubly pointless the next line will do the same thing making the error and the message appear twice (even though it occurred once) The second line will also print the Stack Trace.

Performance Tip: Set the capacity of a collection is you know its size.

Overview An advantage of using a Collection or Map over using a plain array is you don't need to know how big it will be when you create it. Often this is the case. However sometimes you know what the size will be and its can be more efficient in CPU and memory if you give the correct length when it is created. Don't set the length if you don't know what it is Often the default size is likely to be the best, so just leave the default. public static <T> ArrayList<T> list(Enumeration<T> e) { ArrayList<T> l = new ArrayList<T>(); while (e.hasMoreElements()) l.add(e.nextElement()); return l; } Enumeration does give you a hint as the the final size, so just leave the default. If you know the size of a Collection set it In this example, the number of elements in the List is fixed and known. From AnyImpl.checkExtractBadOperationList(int[] expected) List list = new ArrayList() ; for (int ctr=0; ctr<expected.length; ctr++

Performance Tip: Use String.intern() correctly.

Overview String.intern() can be used to improve memory consumption. However its benifit is limited to specific situations, and can be misused as a general performance method when it doesn't help. Don't: Use String.intern() on compile-time constants Compile time constants are automatically placed in the String literal pool. From SchemaSymbols public static final String ELT_GROUP = "group".intern(); public static final String ELT_IMPORT = "import".intern(); public static final String ELT_INCLUDE = "include".intern(); The String literals will be placed in the String pool anyway. Calling intern() on them adds complexity to the code, and overhead but adds no benefit. Is there a side effect? There is the side effect that using .intern() on a compile time literal stops it being inlined into another Compile time literal. Sometimes this is desirable, however when it is not is adds a performance

Performance Tip: avoid Collection.toArray(new Type[0])

Overview The Collection.toArray(Object[]) can be used in a number of ways. Depending on how big you expect the collection to be, one of three approaches can be a better solution. A four option Collection.toArray(new Type[0]) should be avoided. Create an empty array constant A pre-built String[] is used to pass as an argument. This is most efficient when the array usually has a size of 0. If the size is greater than 0, an extra reflective call is required. From AbstractPreferences.childNames(): // ends with return (String[]) s.toArray(EMPTY_STRING_ARRAY); } private static final String[] EMPTY_STRING_ARRAY = new String[0]; Generally its safe to assume all zero length array of a given type are the same. i.e. they are immutable. Arrays can be used for locks, but this is rare and bad practice (esp. to use the result of a method like this as a lock) Create an array of the correct size. This avoids a reflective call, but results in creating an array every time (even for zero length

Thread Safety issues with Vector and Hashtable.

Overview Even though these classes are legacy replaces which were replaced in Java 1.2 (1998) they remain widely using. One misconception is that they are synchronized and there for thread safe. Is Iterator thread safe? For many collections the Iterator is not thread safe. They fail fast by throwing a ConcurrentModiciationException. However throwing this exception is not guaranteed and the counter used to detect this situation is not volatile. Collection Iterator behavior ArrayList, LinkedList, TreeSet Usually throws a ConcurrentModicationException CopyOnWriteArraySet, CopyOnWriteArrayList Consistent for the state of the collection at a given point in time ArrayBlockingQueue, LinkedBlockingQueue Weakly consistent, won't throw an error ArrayBlockingQueue, LinkedBlockingQueue Also weakly consistent, won't throw an error, the Iterator is sorted PriorityQueue Also weakly consistent, even though the collection is sorted , the Iterator is not sorted. Enumeration is thre

A review of some old best practices

Overview Best practices tend to date and what was s good idea ten years ago, may not be considered a good idea today. A review of some old best practices This article was written in 1997. Thirteen Great Ways to Increase Java Performance Is it still reliant today? Use buffered I/O This still applies today. It catches those New to Java, however I believe it is widely used. Try to avoid new. This doesn't apply as much as it used to, however there is still use cases where you want to avoid creating new objects, esp when you may be calling code many times. Unfortunately creating new objects is a common occurrence in the JDK and when it comes to rewriting libraries which come with the JDK, it usually because the functionality create needless objects. Native methods are really fast. They are even faster than they used to be. For some native calls the JVM is smart enough to inline the native code. Some natives methods are replaced with a single machine code instruction. String

Common tricks to optimising Java with examples from the JDK

Overview While best practices for programming in Java have moved improved over the years, the code base for the OpenJDK has some sections which are very old. They have some best practices but also some good examples of what not to do. Don't create objects needlessly Using a object pool doesn't help as much as it did pre-Java 5.0 however that doesn't mean a simple pool won't help. For this reason many of the wrapper classes use a cache for their values, introduced in Java 5.0. This is used by auto-boxing to reduce the overhead of creating objects. One class which has always had a cache is Boolean. There is only two possible values and they are immutable, so you would think there is never a good reason to create one. This doesn't store many methods in the OpenJDK doing just that. This class can be used when you get a boolean field via reflection. class UnsafeBooleanFieldAccessorImpl extends UnsafeFieldAccessorImpl { public Object get(Object obj) throws

Writing human readable data faster than binary.

Overview It is conventional wisdom that writing binary data is faster than writing human readable data. While binary is typically faster, are all means of writing text slower than standard approaches in writing binary? For the purposes of this test I compare writing long values in binary as a fixed width fields (the most CPU efficient binary format) and human readable format with a '\n' separator. Techniques of writing and reading text and binary Two of the most common ways to write binary and text is to use DataOutputStream/DataInputStream and using PrintWriter/BufferedReader. I compare these with using ByteBuffer for binary and lower level memory access using the Unsafe class. The Code The code is too long include here so I have made it available on Google Code The results I ran this test on a Xeon 2.67 GHz with Java 6 update 25 on Windows Vista. Unsafe binary: Typically took 4.2 ns to write/read per long. ByteBuffer binary: Typically took 10.4 ns to write/read pe

How long does throwing an Exception take?

Overview It is best practice to use Exceptions for exceptional conditions. Another reason given to avoid Exceptions is for performance reasons. However how long does creating and throwing an exception take? Breaking it down A common way to throw exceptions is to create and throw the exception in one operation. throw new RuntimeException(); However these can be separated, though it is rarely useful to do so. RuntimeException re = new RuntimeException(); // take stack trace here. // later throw re; The stack trace is snapshot'ed in where the exception was created, not where it was thrown which can be confusing. It is filled in later only if it is needed for performance reason. Timing creating and throwing A micro benchmark prints the following on a 2.67 GHz Xeon with Java 6 update 25. Creating a Throwable took 0.8 us on average Optimised Throw/catch a Throwable took 0.007 us on average Throw/catch a Throwable took 0.4 us on average Time to printStackTrace for a short stack

Linkedin Group for Core Java Performance Professionals

I have joined this Open Group Core Java Performance Professionals

Does Thread.stop() really stop a Thread?

Overview Thread.stop() is deprecated, with good reason. However there are times when it is really the only option available to you. How does Thread.stop() really work Thread.stop() creates a java.lang.ThreadDeath which is an Error. It uses the current threads stack trace and causes the thread you use to throw this error. However, at this point, its an Error like any other. You can catch it, print it and ignore it. Any finally block will be called as normal and any synchronized blocks will be unlocked in the same manner as throwing this Error in the current thread. What is special about ThreadDeath Apart from its name not ending in Error, ThreadDeath is unusual in that it is not printed by default if not caught. The ThreadGroup.uncaughtException() method ignores this exception by default. You can change this behaviour by overriding this method or using Thread.setDefaultUncaughtExceptionHandler(); Note: if you do print the stack trace of ThreadDeath, it has the stack trace o