Записать много данных из базы данных в файл - PullRequest
0 голосов
/ 28 марта 2020

Здравствуйте, я пытаюсь создать файл для записи данных в файл. Данные достаточно велики, поэтому сервер не может сразу выделить их в память. Для меня это скорее теоретическая задача.

FileOutputStream outputStream = new FileOutputStream("test1.txt");
                try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017")) {
                    MongoDatabase database = mongoClient.getDatabase("test");
                    MongoCursor<Document> users = database.getCollection("users").find().cursor();
                    while (users.hasNext()) {
                        System.out.println("Writing some bytes..");
                        byte[] userByte = SerializationUtils.serialize(users.next());
                        outputStream.write(userByte, 0, userByte.length);
                        if (outputStream.getChannel().size() > 80000) {
                            outputStream.flush();
                        }
                        System.out.println(outputStream.getChannel().size());
                    }
                    outputStream.close();
                }

Насколько я понимаю, очистка буфера должна освободить выделенную память, но этого не происходит, и, таким образом, происходит сбой jvm.

Writing some bytes..
101008
Writing some bytes..
102024
2020-03-28 15:59:57.884  INFO 7340 --- [nio-8080-exec-1] org.mongodb.driver.connection            : Closed connection [connectionId{localValue:3, serverValue:52}] to localhost:27017 because there was a socket exception raised by this connection.
2020-03-28 15:59:57.899 ERROR 7340 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is com.mongodb.MongoInternalException: Unexpected exception] with root cause

java.lang.OutOfMemoryError: Java heap space

Как мне изменить код, чтобы я мог записать файл в чанк и не получить ошибку OOM?

...