Search code examples
javaclosuresprocessbuilder

Bypassing 'Cannot refer to a non-final variable inside an inner class defined'


I have the following code, but when I declare the String line outside of the new Thread class I get an exception. I'm from a C# background, so I understand now that Java does not support true closures. So my question is:

How can I declare a string outside of new Thread and use it in new Thread?

Cannot refer to a non-final variable line inside an inner class defined in a different method

ProcessBuilder builder =
    new ProcessBuilder("/Users/Joe/Desktop/file", "-i", src);
builder.redirectErrorStream(true);
Process process = builder.start();
final InputStream is = process.getInputStream();
String line;
new Thread(new Runnable() {
    @Override public void run() {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            while ((br.readLine()) != null) {
                line += br.readLine() + "\n";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }               
}).start();

Solution

  • Change line to be a StringBuilder and declare it as final. Then change the run() method to append to the StringBuilder.

    Provided that you join() the child thread before you attempt to read line in the main thread, you don't need to use a StringBuffer.