Many times I've encountered the need to write code like this:
Since the anonymous class is thread safe, I feel compelled to declare it as static. What is a good way to approach this?
Here are a few options I've thought of: 1. Don't do it. 2. Move it out to the class level and declare as static final, possibly making the code harder to read, because this is a utility-based attribute, rather than a true class attribute. 3. Leave it in the method, but declare it as final. (any performance improvement from this?)
Option 1: The anonymous Comparator object does not have any member variables and it is probably a short-lived object. The Java garbage collector has optimizations for short-lived objects. Creating the new object does ofcourse have some overhead, but it is not much. One golden rule of optimizing is that you should not do it unless you know (through measurements with a profiler) that the code you are optimizing is a bottleneck. Optimizing code that is not a bottleneck is a waste of time.
Option 2: You could do that, if the small overhead of object creation really bothers you.
Option 3 does not really do anything. I haven't tried it out but I wouldn't be surprised if the generated bytecode would be exactly the same as with your original code. If you really want to find out, you could use the tool javap (included with the JDK) to disassemble your class file and see if "final" makes any difference to the bytecode or not.