blob: bee43a8653e105ce83d1c6e253deebb550d40cfb (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
package com.yahoo.io;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.logging.Logger;
import com.sun.jna.LastErrorException;
import com.sun.jna.Native;
import com.sun.jna.Platform;
public class NativeIO {
private final Logger logger = Logger.getLogger(getClass().getName());
private static final int POSIX_FADV_DONTNEED = 4; // See /usr/include/linux/fadvise.h
private static boolean initialized = false;
private static Throwable initError = null;
static {
try {
if (Platform.isLinux()) {
Native.register(Platform.C_LIBRARY_NAME);
initialized = true;
}
} catch (Throwable throwable) {
initError = throwable;
}
}
private static final Field fieldFD = getField(FileDescriptor.class, "fd");
private static native int posix_fadvise(int fd, long offset, long len, int flag) throws LastErrorException;
public NativeIO() {
if (!initialized) {
logger.warning("native IO not possible due to " + getError().getMessage());
}
}
public boolean valid() { return initialized; }
public Throwable getError() {
if (initError != null) {
return initError;
} else {
return new RuntimeException("Platform is unsúpported. Only supported on linux.");
}
}
public void dropFileFromCache(FileDescriptor fd) {
if (initialized) {
posix_fadvise(getNativeFD(fd), 0, 0, POSIX_FADV_DONTNEED);
}
}
public void dropFileFromCache(File file) {
try {
dropFileFromCache(new FileInputStream(file).getFD());
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static Field getField(Class<?> clazz, String fieldName) {
Field field;
try {
field = clazz.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
}
field.setAccessible(true);
return field;
}
private static int getNativeFD(FileDescriptor fd) {
try {
return fieldFD.getInt(fd);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
|