wood burning stoves 2.0*
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 OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Use of static anonymous Comparator" Watch "Use of static anonymous Comparator" New topic
Author

Use of static anonymous Comparator

Justin Chu
Ranch Hand

Joined: Apr 19, 2002
Posts: 209
    
    1
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: 14117
    
  16

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 7 API documentation
Scala Notes - My blog about Scala
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Use of static anonymous Comparator