12

I'm playing with Java 8 and hit a basic scenario that illustrates a catch 22 where fixing one compile error causes another compile error. The scenario (which is just an example simplified from something more complex):

public static List<String> catch22(List<String> input) {
    List<String> result = null;
    if (input != null) {
      result = new ArrayList<>(input.size());
      input.forEach(e -> result.add(e)); // compile error here
    }

    return result;
}

I get a compile error:

Local variable result defined in an enclosing scope must be final or effectively final

If I change the first line to:

List<String> result;

I get a compile error on the last line:

The local variable result may not have been initialized

It seems like the only approach here is to pre-initialize my result to an ArrayList, which I don't want to do, or not use lambda expressions. Am I missing any other solution?

3
  • 3
    OTOH, the callers of this method won't be happy to check for null every time they need to access the returned list. Do the right thing, and return an empty list instead of returning null.
    – JB Nizet
    Apr 1, 2014 at 6:03
  • You are just transferring the values from input to result?
    – Rohit Jain
    Apr 1, 2014 at 6:06
  • 2
    @RohitJain In this simplified fake example, yes.
    – Josh Stone
    Apr 1, 2014 at 15:31

7 Answers 7

17

The error is coming because your result list is not effectively final which is a requirement for it's usage in lambda. One option is to declare the variable inside the if condition, and return null; outside. But I don't think that would be good idea. Your current method is not doing anything productive. It would make much more sense to return an empty list from it.

Having said that all, I would say, since you are playing with Java 8, use Optional along with streams here:

public static List<String> catch22(List<String> input) {
    return Optional.ofNullable(input)
            .orElse(new ArrayList<String>())
            .stream().collect(Collectors.toList());
}

And if you want to return null, I'll probably change your method to:

public static List<String> catch22(List<String> input) {
    if (input == null) return null;
    return input.stream().collect(Collectors.toList());
    // Or this. B'coz this is really what your code is doing.
    return new ArrayList<>(input);
}
2
  • Good answer - thanks for showing two diff interesting approaches.
    – Josh Stone
    Apr 1, 2014 at 15:35
  • In that first example, even if input is passed as non-null, the call to .orElse means that the constructor expression (the new ArrayList) will always happen. I don't see any rule that the argument to the function call is allowed to be not evaluated. So if the runtime optimizer isn't smart enough about orElse semantics to skip evaluating its argument, it's going to create an ArrayList with default capacity, and then immediately mark it as garbage. (Granted, all this is just an example, so this doesn't really matter.)
    – Ti Strga
    Jan 26, 2017 at 20:33
10

Push the declaration inside the block with input != null. Example:

public static List<String> catch22(List<String> input) {
    if (input != null) {
        List<String> result;
        result = new ArrayList<>(input.size());
        input.forEach(e -> result.add(e)); // compile error here
        return result;
    } else {
        return null; // or empty list or something that suits your app
    }
}
1
  • 4
    result doesn't need to be final. It needs to be effectively final.
    – JB Nizet
    Apr 1, 2014 at 6:12
2

forEach(...) applies an operation on each element of the Stream. You really don't want that, you want a Stream "consumer" which produces a single output of List<String>.

Fortunately these are considered Collectors in the current framework, and Collectors.toList() does exactly what you want.

List<String> duplicate = input.stream().collect(Collectors.toList());
1

Here, i summarized some general solutions for lambdas expressions modifying method local variables.

Lambdas Expressions are actually anonymous inner classes in a concise form. When we use them in local methods we should take several constraints into consideration:

  • lambdas expressions(anonymous inner class) cant modify local variables of surrounding method link here they must be final or in java 8 effectively final

  • Unlike instance variables, local variables do not get default values and if you want to use or return them you must initialize them first

When these two constraints collide (in case of defining a lambdas in a method where lambdas modifies local variable in surrounding method), we get into trouble

solutions:

solution 1: do not modify method local variable in lambdas or use instance variables instead

solution 2: do some tricks, for example copy local variable into another one and pass that to lambdas:

public static List<String> catch22(List<String> input) {
 List<String> result = null;
 if (input != null) {
   result = new ArrayList<>(input.size());
   List<String> effectivelyFinalResult = result;
   input.forEach(e -> effectivelyFinalResult.add(e)); 
 }
 return result;
}

or limit local variables scope so you dont get into trouble for not initializing them:

public static List<String> catch22(List<String> input) {
if (input != null) {
    List<String> result; // result gets its value in the lambdas so it is effectively final
    result = new ArrayList<>(input.size());
    input.forEach(e -> result.add(e));
    return result;
} else {
    return null; 
}
} 
0

By making the result final and putting the null assignment in the else block you can keep the current structure of your method and 'solve' your catch22.

public static List<String> catch22(List<String> input) {
    final List<String> result;
    if (input != null) {
        result = new ArrayList<>(input.size());
        input.forEach(e -> result.add(e));
    } else {
        result = null;
    }

    return result;
}
0

You can do this

public static List<String> catch22(List<String> input) {
List<String> result = null;
if (input != null) {
  result = new ArrayList<>(input.size());
  List<String> effectivelyFinalResult = result;
  input.forEach(e -> effectivelyFinalResult.add(e)); // No compile error here
}

return result;
}

to get around it.

0

Its presence prevents the introduction of a new class of multithreading bugs involving local variables.

Local variables in Java have until now been immune to race conditions and visibility problems because they are accessible only to the thread executing the method in which they are declared. But a lambda can be passed from the thread that created it to a different thread, and that immunity would therefore be lost if the lambda, evaluated by the second thread, were given the ability to mutate local variables.

Even the ability to read the value of mutable local variables from a different thread would introduce the necessity for synchronization or the use of volatile in order to avoid reading stale data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.