-2

I am reading Java source code, encounter two little questions. I don't know why Sun write code like this, here are questions (JDK version:1.6):

Question 1:

java.util.concurrent.PriorityBlockingQueue#offer(E e):


public boolean offer(E e) {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        boolean ok = q.offer(e);
        assert ok;
        notEmpty.signal();
        return true;
    } finally {
        lock.unlock();
    }
}

Why to define a local final ReentrantLock variable in method block, why not directly to use a global variable lock?

Question 2:

This method java.text.NumberFormat#getInstance(Locale desiredLocale, int choice): creates a DecimalFormat object, but a return type is NumberFormat. Why not to make return type as DecimalFormat?

Roman C
  • 49,761
  • 33
  • 66
  • 176
hiway
  • 3,906
  • 10
  • 34
  • 57
  • 9
    You might want to separate this into 2 totally separate questions, since they are unrelated – DWright Jan 05 '13 at 06:18
  • @DWright: yes, I will do this in the future, thanks for your recommendation – hiway Jan 05 '13 at 06:38
  • The API is what it is. Asking why is pretty pointless unless you can get hold of the guy who wrote it. #1 seems entirely pointless to me unless it relates to the memory model rules. Re #2, note that all the `getInstance()` methods return `NumberFormat,` not just that one. – user207421 Jan 05 '13 at 09:10

2 Answers2

3

To the first question:

  1. That is not a global variable, that is a member variable. I do suggest that you look into scoping rules to get a better idea of the vocabulary.
  2. There are a couple of possibilities for why a programmer might make this decision. Most immediately I am reminded of the Android SDK where there is a mild performance increase when you use a locally scoped variable. It also might be that the programmer felt that using final would be a better choice in this instance (more on why that might happen here.).

To the second question:

It returns a DecimalFormat most of the time, but it is possible (and you can see the source here) for the getInstance method to return a different descendant of NumberFormat.

cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
  • to your first point: I am wrong, it is a member variable, thanks. to your second point: member variable 'lock' is already defined as final: private final ReentrantLock lock = new ReentrantLock(true); I think the author define a locally scoped variable in method block is just making an unnecessary move. – hiway Jan 05 '13 at 06:36
1
  1. Locally scoped variable not intended to modify.
  2. NumberFormat is an abstract class, so it's treated like interface.
Roman C
  • 49,761
  • 33
  • 66
  • 176