Path: blob/master/test/jdk/java/nio/MappedByteBuffer/Force.java
41149 views
/*1* Copyright (c) 2002, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/* @test24* @bug 4625907 824672925* @summary Testing force()26* @library /test/lib27* @build jdk.test.lib.RandomFactory28* @run main/othervm Force29* @key randomness30*/3132import java.io.File;33import java.io.RandomAccessFile;34import java.nio.MappedByteBuffer;35import java.nio.channels.FileChannel;36import java.nio.file.Files;37import static java.nio.file.StandardOpenOption.*;38import java.util.Random;39import jdk.test.lib.RandomFactory;4041public class Force {42public static void main(String[] args) throws Exception {43test1();44test2();45}4647private static void test1() throws Exception {48Random random = RandomFactory.getRandom();49long filesize = random.nextInt(3*1024*1024);50int cut = random.nextInt((int)filesize);51File file = File.createTempFile("Blah", null);52file.deleteOnExit();53try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) {54raf.setLength(filesize);55FileChannel fc = raf.getChannel();56MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, cut, filesize-cut);57mbb.force();58}5960// improve chance that mapped buffer will be unmapped61System.gc();62Thread.sleep(500);63}6465private static void test2() throws Exception {66var path = Files.createTempFile("test", "map");67var channel = FileChannel.open(path, READ, WRITE);68MappedByteBuffer buffer =69channel.map(FileChannel.MapMode.READ_WRITE, 0, 1000);70buffer.putInt(1234);71buffer.limit(4);72buffer.force();73}74}757677