Effectively final

Steven Simpson ss at comp.lancs.ac.uk
Mon Aug 15 07:22:41 PDT 2011


On 15/08/11 15:08, Steven Simpson wrote:
>     void foo(final Socket socket) {
>       new Object() {
>         boolean timedOut;
>         {
>           system.setTimeout(100, #{ timedOut = true; });
>           socket.onData(#{ if (!timedOut) System.out.println("Got data"); });
>         }
>       };
>     }

I just noticed that this technique leaks 'this' before construction is 
complete.  Is it generally a problem?  If so, use Runnable instead:

    void foo(final Socket socket) {
      new Runnable() {
        boolean timedOut;
        public void run() {
          system.setTimeout(100, #{ timedOut = true; });
          socket.onData(#{ if (!timedOut) System.out.println("Got data"); });
        }
      }.run();
    }

It's a little more clunky, though.



More information about the lambda-dev mailing list