Este roteiro é projetado para testar e visualizar na prática como o computador e a Máquina Virtual Java (JVM) lidam com limites físicos de memória e de processamento.
long (8 bytes por elemento).N) e descubra qual é a ordem de grandeza que fará seu ambiente estourar.public class ExperimentoMemoryLimit {
public static void main(String[] args) {
System.out.println("Iniciando teste de Memory Limit...");
// Cada 'long' na matriz ocupa 8 bytes de memória.
// Tente alterar o valor de N e observe quando a máquina falha!
// Valores sugeridos: 10000, 20000, 30000, 50000...
int N = 10000;
try {
System.out.println("Alocando " + N + " x " + N + "...");
long[][] matriz = new long[N][N];
long bytes = (long) N * N * 8;
long megaBytes = bytes / (1024 * 1024);
System.out.println("Sucesso! Alocado: " + megaBytes + " MB.");
} catch (OutOfMemoryError e) {
System.out.println("\nESTOURO DE MEMÓRIA!");
}
}
}Marque a alternativa (X) que descreve onde ocorreu o estouro:
numero = 200000) e verifique o comportamento.public class ExperimentoStackOverflow {
public static long fatorial(long n, int prof) {
if (prof % 1000 == 0) System.out.println("Stack: " + prof);
if (n <= 1) return 1;
return n * fatorial(n - 1, prof + 1);
}
public static void main(String[] args) {
long numero = 150000;
try {
System.out.println("Resultado: " + fatorial(numero, 1));
} catch (StackOverflowError e) {
System.err.println("\nESTOURO DA PILHA DE CHAMADAS!");
}
}
}for/while ao invés de recursão)N com números aleatórios.System.currentTimeMillis() para verificar o tempo gasto pelo Bubble Sort e pelo Arrays.sort().import java.util.Arrays;
import java.util.Random;
public class ExperimentoTimeLimit {
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
} public static void main(String[] args) {
int N = 50000;
int[] arrB = new int[N];
int[] arrQ = new int[N];
Random rand = new Random();
for (int i = 0; i < N; i++) {
arrB[i] = rand.nextInt(N);
arrQ[i] = arrB[i];
}
long t1 = System.currentTimeMillis();
bubbleSort(arrB);
System.out.println("Bubble: " + (System.currentTimeMillis() - t1) + "ms");
long t2 = System.currentTimeMillis();
Arrays.sort(arrQ);
System.out.println("Quick: " + (System.currentTimeMillis() - t2) + "ms");
}
}Execute o código variando o tamanho de N (25000, 50000, 100000).
N? Quantas vezes o tempo aumenta?