2

I have code like this:

while(true){
    var x = get();
    new Thread(()->parse(x)).start();
}

It dawned upon me that this may not be thread safe as the variable x may be (?) getting re-assigned.

However my function seems to be working fine.

Is this actually safe?

Tobiq
  • 2,489
  • 19
  • 38
  • 6
    Should be, since Java does not have real closures; the value of `x` is copied to a synthetic final field of the lambda, so when the lambda is run in another thread, it reads it from that field, not the local scope of the `while` loop. – kaya3 Feb 14 '20 at 18:20
  • Wonderful stuff. Thanks for the explanation – Tobiq Feb 14 '20 at 18:21
  • 1
    In the nomenclature of a certain other programming language that shall not be named, the lambda _captures_ `x` _by value_. – Solomon Slow Feb 14 '20 at 18:51

1 Answers1

3

Variable x in your code should be effectively final, which means it can not be reassigned. See e.g. this explanation or this stackoverflow question.

But the solution in general is not thread-safe, when x is an object and its fields can be accessed from outside. In such cases all changes to fields of x should be synchronized.

Daniil
  • 913
  • 8
  • 19