3

https://stackoverflow.com/a/180191

Here a method is timed by calling System.nanoTime() in a normal block, while the end time is called for in a finally block?

Was this only done to report a correct time even if the method throws an exception? or does guarantee even more: not only that it will be called but also right after the method (i.e. preventing task switching or similar...) ?

what is the motivation of using final modifiers here?

Community
  • 1
  • 1
propaganda
  • 470
  • 2
  • 6
  • 14

1 Answers1

6

The only reason to do this is to make sure that the second nanoTime() is called even in the presence of exceptions.

There are no guarantees related to task switching.

As to the final modifiers, I think they are just a matter of personal style, and have no effect on the timings. Like the person who wrote that answer, I often mark variables that are effectively constant as final.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • and why are final modifiers used? the example assumes it will only be timed once? – propaganda Jan 26 '12 at 08:44
  • @propaganda: Just a matter of personal style I suppose. Don't think they have any effect on the timings. I've updated the answer. – NPE Jan 26 '12 at 08:48
  • 1
    The `final` modifiers are a defensive programming practice (like `const` in C++). If you've marked the reference as final, you can't introduce a bug by changing it when you didn't mean to. It's especially useful with primitives and with immutable objects. – Andrew Spencer Jan 26 '12 at 09:24
  • Also, note that entering and exiting the `try` block will incur a measurable overhead. – Andrew Spencer Jan 26 '12 at 09:25