Question

I was implementing the V setValue(V value) method in Map.Entry<K,V> and have done the following:

@Override public T setValue(T value) {
  try {
    return this.value;
  } finally {
    this.value = value;
  }
}

It works as it should.

I know there are some questions about finally blocks and stuff, but I couldn't find this specific question. What are your thoughts on this particular use-case? Is this legal? Should be avoided? If yes then why or why not. Thanks!

Was it helpful?

Solution

Prefer simple, obvious code. i.e.

@Override public T setValue(T value) {
    T old = this.value;
    this.value = value;
    return old;
}

Also, this can be extended to be [locally] thread-safe (as NIO attach).

private final AtomicReference<T> valueRef;

@Override public T setValue(T value) {
    return valueRef.getAndSet(value);
}

OTHER TIPS

It works, but it's not nearly as obvious (easy to understand) as:

@Override public T setValue(T value) {
  T oldValue = this.value;
  this.value = value;
  return oldValue;
}

Why not use this simpler form?

Well, I think that, by the moment, it's absolutely legal. Normally you use the finally clause to specify values that execute o are assigned just before the return. But sometimes we use to put inside the return, and a warning is thrown. I think you must avoid that return, but you can use the finally for the rest.

Otherwise, it is like an obsolete function, for example, and it does no matter if you put those assignments inside the finally or after the try/catch block.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top