Debian Codegraph @

src/main/org/h2/store/fs/async/FileAsync.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.store.fs.async;
7
8 import java.io.IOException;
9 import java.nio.ByteBuffer;
10 import java.nio.channels.AsynchronousFileChannel;
11 import java.nio.channels.FileLock;
12 import java.nio.file.Paths;
13 import java.util.concurrent.ExecutionException;
14 import java.util.concurrent.Future;
15 import org.h2.store.fs.FileBaseDefault;
16 import org.h2.store.fs.FileUtils;
17
18 /**
19 * File which uses NIO2 AsynchronousFileChannel.
20 */
21 class FileAsync extends FileBaseDefault {
22
23 private final String name;
24 private final AsynchronousFileChannel channel;
25
26 private static <T> T complete(Future<T> future) throws IOException {
27 boolean interrupted = false;
28 for (;;) {
29 try {
30 T result = future.get();
31 if (interrupted) {
32 Thread.currentThread().interrupt();
33 }
34 return result;
35 } catch (InterruptedException e) {
36 interrupted = true;
37 } catch (ExecutionException e) {
38 throw new IOException(e.getCause());
39 }
40 }
41 }
42
43 FileAsync(String fileName, String mode) throws IOException {
44 this.name = fileName;
45 channel = AsynchronousFileChannel.open(Paths.get(fileName), FileUtils.modeToOptions(mode), null,
46 FileUtils.NO_ATTRIBUTES);
47 }
48
49 @Override
50 public void implCloseChannel() throws IOException {
51 channel.close();
52 }
53
54 @Override
55 public long size() throws IOException {
56 return channel.size();
57 }
58
59 @Override
60 public int read(ByteBuffer dst, long position) throws IOException {
61 return complete(channel.read(dst, position));
62 }
63
64 @Override
65 public int write(ByteBuffer src, long position) throws IOException {
66 return complete(channel.write(src, position));
67 }
68
69 @Override
70 protected void implTruncate(long newLength) throws IOException {
71 channel.truncate(newLength);
72 }
73
74 @Override
75 public void force(boolean metaData) throws IOException {
76 channel.force(metaData);
77 }
78
79 @Override
80 public FileLock tryLock(long position, long size, boolean shared) throws IOException {
81 return channel.tryLock(position, size, shared);
82 }
83
84 @Override
85 public String toString() {
86 return "async:" + name;
87 }
88
89 }