File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Use of static anonymous Comparator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Use of static anonymous Comparator" Watch "Use of static anonymous Comparator" New topic

Use of static anonymous Comparator

Justin Chu
Ranch Hand

Joined: Apr 19, 2002
Posts: 209
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?)
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15100

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.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
subject: Use of static anonymous Comparator
It's not a secret anymore!