3. PROGRAMAÇÃO CONCORRENTE – Prof. Thomás da Costa
MEMÓRIA COMPARTILHADA
Memória Compartilhada
O que é?:
É o processo de compartilhar informações contidas na memória diretamente
em arquivos. Neste processo o Java utiliza diretamente a memória física
tornando o processo de leitura e escrita o mais rápido possível.
4. PROGRAMAÇÃO CONCORRENTE – Prof. Thomás da Costa
package edu.anhanguera.prc.aula07;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class ArquivoMemoriaEscrever {
@SuppressWarnings("resource")
public static void main(String[] args) {
long bufferSize = 8 * 10000;
try {
File arquivo = new File("/tmp/arquivo_memoria.txt");
arquivo.delete();
FileChannel fileChannel = new RandomAccessFile(arquivo, "rw").getChannel();
MappedByteBuffer mp = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, bufferSize);
String valor = "GRAVANDO UMA INFORMACAO";
for (int j=0;j<=10;j++) {
mp.put(valor.getBytes());
}
fileChannel.close();
mp.clear();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
5. PROGRAMAÇÃO CONCORRENTE – Prof. Thomás da Costa
package edu.anhanguera.prc.aula07;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class ArquivoMemoriaLer {
@SuppressWarnings("resource")
public static void main(String[] args) throws FileNotFoundException, IOException,
InterruptedException {
long bufferSize = 8 * 10000;
File arquivo = new File("/tmp/arquivo_memoria.txt");
FileChannel fileChannel = new RandomAccessFile(arquivo, "r").getChannel();
MappedByteBuffer mp = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, bufferSize);
mp.load();
byte[] bytes = new byte[23];
for (int i=0;i<=mp.limit()-1;i++) {
mp.get(bytes);
String valor = new String(bytes);
if (!valor.trim().isEmpty()) {
System.out.println(new String(bytes));
} else {
break;
}
}
}
}