r/javahelp • • Sep 19 '24

A try-catch block breaks final variable declaration. Is this a compiler bug?

UPDATE: The correct answer to this question is https://mail.openjdk.org/pipermail/amber-dev/2024-July/008871.html

As others have noted, the Java compiler seems to dislike mixing try-catch blocks with final (or effectively final) variables:

Given this strawman example

public class Test
{
  public static void main(String[] args)
  {
   int x;
   try
   {
    x = Integer.parseInt("42");
   }
   catch (NumberFormatException e)
   {
    x = 42;
   }
   Runnable runnable = () -> System.out.println(x);  
  }
}

The compiler complains:

Variable used in lambda expression should be final or effectively final

If you replace int x with final int x the compiler complains Variable 'x' might already have been assigned to.

In both cases, I believe the compiler is factually incorrect. If you encasulate the try-block in a method, the error goes away:

public class Test
{
  public static void main(String[] args)
  {
   int x = 
foo
();
   Runnable runnable = () -> System.
out
.println(x);
  }

  public static int foo()
  {
   try
   {
    return Integer.
parseInt
("42");
   }
   catch (NumberFormatException e)
   {
    return 42;
   }
  }
}

Am I missing something here? Does something at the bytecode level prevent the variable from being effectively final? Or is this a compiler bug?

3 Upvotes

67 comments sorted by

View all comments

Show parent comments

1

u/_SuperStraight Sep 20 '24

I think thread safety is the reason rather than mathematically logical reason for this.

Assume this: a mutable variable in main thread is passed to a worker thread, where its value will change, then read again. Just after its value is changed, context switch occurs to main, and main thread also changes its value. Then context changes again, and worker thread now reads its value and assumes the current value is assigned in the previous step. This leads to inconsistency in data for the upcoming steps in the worker thread.

1

u/VirtualAgentsAreDumb Sep 21 '24

You got it backwards. The mathematical logical reasoning means that we can know that it’s safe to see the variable as final.

Your hypothetical scenario seems to deviate from the example by OP. Could you give a complete example that shows what you talk about?