Search code examples
javamultithreadingvariablesnetbeanslocal

Java MultiThreadding Local variables referenced from an inner class must be final of effectively final


I am using multithreadding in a for loop. I am trying to run a method for each thread containing some parameters declared inside the for loop.

I have tried moving the variables to the Thread Body and it works. Apart from variables i and AccuraciesList.

enter image description here

     for (int i = 0; i < 30; i++) {

        String classifierName = "NaiveBayes";
        String dataFile = "decision_tree_image_dataset";
        String folderName = "dataset2_ff_time";
        String folder = "testFold";

        Instances dataSet = WekaTools.loadData(dataFile + ".arff");

        String path = "Results diagrams/" + folderName + "/" + classifierName;

        new Thread(new Runnable() {

            public void run() {
                try {

                    runThread(classifierName, folder, path, dataFile, i, accuraciesList, dataSet);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

I am still getting the same error no matter what I do. I really need the i to be passed in the function as well as the accuraciesList


Solution

  • i must be either as final or has no value modification after declaration (effectively final).

    Since it cannot be final as it is a loop iterator, just copy the value and use that copied final value like this.

    final int iVal=i;
    new Thread(new Runnable() {
    
        public void run() {
            try {
    
                runThread(classifierName, folder, path, dataFile, iVal, accuraciesList, dataSet);
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();