Path: blob/master/test/jdk/java/nio/MappedByteBuffer/ForceException.java
41149 views
/*1* Copyright (c) 2021, 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 653970725* @summary Test behavior of force() with respect to throwing exceptions26* @run main ForceException27*/2829import java.io.File;30import java.io.IOException;31import java.io.RandomAccessFile;32import java.io.UncheckedIOException;33import java.nio.MappedByteBuffer;34import java.nio.channels.FileChannel;3536public class ForceException {37public static void main(String[] args) throws IOException {38int blockSize = 2048 * 1024;39int numberOfBlocks = 200;40int fileLength = numberOfBlocks * blockSize;4142File file = new File(System.getProperty("test.src", "."), "test.dat");43file.deleteOnExit();44try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) {45raf.setLength(fileLength);4647int pos = (numberOfBlocks - 1) * blockSize;48int size = (int)Math.min(blockSize, fileLength - pos);49MappedByteBuffer mbb =50raf.getChannel().map(FileChannel.MapMode.READ_WRITE, pos, size);5152System.out.printf("Write region 0x%s..0x%s%n",53Long.toHexString(pos), Long.toHexString(size));54for (int k = 0; k < mbb.limit(); k++) {55mbb.put(k, (byte)65);56}5758// Catch and process UncheckedIOException; other Throwables fail59try {60System.out.println("Force");61mbb.force();62} catch (UncheckedIOException legal) {63System.out.printf("Caught legal exception %s%n", legal);64IOException cause = legal.getCause(); // can't be null65// Throw the cause if flush failed (should be only on Windows)66if (cause.getMessage().startsWith("Flush failed")) {67throw cause;68}69}7071System.out.println("OK");72}73}74}757677