Understand error message

Asked

Viewed 269 times

4

I’m not getting this error message. Someone understands and can help me?

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:3210)
at java.util.Arrays.copyOf(Arrays.java:3181)
at java.util.ArrayList.grow(ArrayList.java:261)
at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
at java.util.ArrayList.add(ArrayList.java:458)
at so.SO.main(SO.java:100)

My code

try {

        try (FileReader arq = new FileReader(arquivo)) {
            BufferedReader lerArq = new BufferedReader(arq);

            String linha = lerArq.readLine();

            num_processos = Integer.parseInt(linha);

            String array[] = new String[3];  // array criado para determinar a quantidade de parãmetros a serem armazenados.

            while (linha != null) {         // Condição de saída do arquivo pois quando acabam as linhas o valor é null.

                linha = lerArq.readLine();

                if (linha != null) //Condição usada para verificar se está em uma linha vazia uma vez que somente o while ainda dava alguns erros.
                {
                    quantidade_linha++; // Contador de linhas do arquivo "txt".

                    cont_caracter = 0;  // Contador de caracteres.

                    if (quantidade_linha == 2) {
                        num_ciclos = Integer.parseInt(linha);

                    }

                    if (quantidade_linha > 2) {
                        PID++;
                        temporario = new Processos();  // instanciamento do processo temporário para que a cada linha seja registrado um novo.
                        temporario.inicializa(PID);   // Método contido na classe de Processos para inicializar com "0" os valores do mesmo.

                        while (cont_caracter < linha.length()) {      // Condição para chegada ao fim da linha.

                            array = linha.split(",");           // Caracter usado para separamento usando o método split.

                            // Atribuir os valores ao processo temporário.
                            temporario.num_ciclos = (Integer.parseInt(array[0]));
                            temporario.entrada_saida = (Integer.parseInt(array[1]));
                            temporario.prioridade = (Integer.parseInt(array[2]));

                            cont_caracter++;
                        }
                        // Condição para determinar em qual lista o processo entratrá dependendo da sua prioridade.
                        if (temporario.prioridade == 0) {
                            prioridade0.add(temporario);
                        } else if (temporario.prioridade == 1) {
                            prioridade1.add(temporario);
                        } else if (temporario.prioridade == 2) {
                            prioridade2.add(temporario);
                        }

                    }
                } else {
                    break;
                }

            }

            while (!fim) {
                for (i = 0; i < prioridade2.size(); i++) {
                    while (prioridade2.get(i).num_ciclos > 0) {
                        pronto.add(prioridade2.get(i));
                    }
                }
                for (i = 0; i < prioridade1.size(); i++) {
                    while (prioridade1.get(i).num_ciclos > 0) {
                        pronto.add(prioridade1.get(i));
                    }
                }
                for (i = 0; i < prioridade0.size(); i++) {
                    while (prioridade0.get(i).num_ciclos > 0) {
                        pronto.add(prioridade0.get(i));
                    }
                }

                fim = true;
            }
            System.out.println("FIM DA EXECUÇÃO!");
        }

    } catch (IOException e) {

        System.err.printf("Erro na abertura do arquivo: %s.\n",
                e.getMessage());

    }
  • 5

    Add the code that is triggering this error to the question too by clicking EDIT.

  • 1

    OutOfMemoryError means you tried to use more memory than the Java virtual machine can handle.

2 answers

6

This is because the default JVM configuration (if you haven’t changed any parameters in the installation) is around 16 MB.

But there’s no way to give you a conclusive answer because I don’t know what prompted your application to use all the allocated memory space, you may be running an infinite loop, filling a buffer vector, among so many other options, If your application is really large and uses more memory, you can reconfigure that volume in your JVM.

To reconfigure the memory volume used by JVM at runtime we have two commands:

  • -Xms: defining the quantity minimal Heap memory for JVM;
  • -Xmx: defining the quantity maxim Heap memory for JVM.

We can use to execute: Java –Xms256M –Xmx1024M –jar seuApp.jar

Link about setting up memory in the JVM, very well explained by the luizricardo.org

If you use Netbeans you can change these values through the Project Properties, under Build > Run > VM Options

6


Heap

Heap is the place (memory space) where objects created in Java are allocated.

In the heap only objects are allocated. Methods and other stops are stored elsewhere.

To heap is divided into two regions: Nursery and Old Space.

  • Nursery: Region where new objects are allocated

  • Old Space: Region where objects that already have some lifespan are allocated


How it works?

When the Nursery begins to fill, is made a kind of "transition" of objects between one region and the other. This transition is called Young Collection, where the objects initially allocated in the Nursery (who are already with some time of life) go to the region Old Space.

When the region Old Space begins to fill, is made a collection called Old Collection, where "old" objects begin to be actually removed from memory.


OutOfMemoryError

I’m not getting this error message. Someone understands and can help me?

This message informs that all space in the Heap was used. The Garbage Collector failed to free up the amount of memory needed to continue running the application in time.

It is no longer possible to move objects from Nursery to the Old Space nor remove from Old Space


How to solve?

This is directly related to your implementation.

No code has been posted, so Sopt can’t help you make a better/less costly implementation".

Post your code so we can help.


Common scenarios of OutOfMemoryError

These are some common scenarios where one can occur OutOfMemoryError:

  • Loops that create many new objects

  • Read and/or write to files storing a lot of information in memory

  • Bring a lot of information from the bank ("dumb" paging is an example)

  • Keep references to objects unnecessarily

Among several other possibilities.


References: Heap and OutOfMemoryError

  • I edited by putting in my code..

  • 1

    It is the second topic I commented on (read file in memory). Notice that you add the variable temporario lists and uses those lists even outside the loop. This causes references to all instances of Processo created are valid outside the loop, causing the Garbage Collector cannot wipe the memory, for for it, all these instances are still "in use".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.