E
E
eagle2016-04-08 14:42:36
Java
eagle, 2016-04-08 14:42:36

Error in thread synchronization or something else?

At work, a NullPointerException pops up regularly.
Here is the code:

...
public class FindWordsUsingThreads {

    public static char[] letters = {'c', 'e', 'n', 'r', 'c', 'u', 't', 'm'}; //изначальный набор симоволов
    public static int l = letters.length - 1; //количество символов
    public static String finalText; //конечный результат
    public static char[][] results = new char[l + 1][l]; // массив строк с результатами
    public static boolean[][] flags = new boolean[l + 1][]; //флаги, учитывающие использование букв. true - можно использовать. false - уже использована
    public static int[] position; // номер буквы, которая подбирается в данный момент

...
public static synchronized void work(int number, FileWriter writer){
        // устанавливаем начальную позицию
        position[number] = 0;

        // удаляем из массива букву, которая стоит первой и которую не используем в алгоритме
        char[] currentLetters = new char[l];
        for (int i = 0; i < l; i++) {
            if (i < number) currentLetters[i] = letters[i];
            if (i > number) currentLetters[i] = letters[i + 1];
        }

        //устанавливаем стартовые флаги true
        for (int i = 0; i < l; i++) flags[number][i] = true;

        //поехали по алгоритму
        for (int i = 0; i < l; i++) {
            results[number][position[number]] = currentLetters[i];
            flags[number][i] = false;
            position[number]++;
            getNextLetter(position[number], number, currentLetters);
            position[number]--;
            flags[number][i] = true;
            try{
                writer.write(finalText);
            } catch (IOException ex){

            }
        }
    }
...

class NewThread implements Runnable{
    String name;
    Thread t;
    int number;
    FileWriter writer;

    public NewThread(String threadname, int threadnumber, FileWriter threadwriter){
        name = threadname;
        number = threadnumber;
        writer = threadwriter;
        t = new Thread(this, name);
        System.out.println(name + " стартовал.");
        t.start();
    }

    //входная точка потока
    public void run(){
        FindWordsUsingThreads.work(number, writer);
        System.out.println(this.name + " закончил.");
    }
}

So, why is nullpointer popping up? Throws an error on the line
for (int i = 0; i < l; i++) flags[number][i] = true;

work method.
the flags array is explicitly initialized in the main.
maybe this is due to the fact that flags is occupied by another thread?
if so, how to fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evhen, 2016-04-08
@unowhat

Are you sure you will pre-initialize it in the main? Because at this stage it is an array of zeros.
public static boolean[][] flags = new boolean[l + 1][];
And preinitialize the array before the start of the threads or after?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question