1 25 26 package org.jrobin.core; 27 28 import java.io.IOException ; 29 import java.nio.channels.FileChannel ; 30 import java.nio.MappedByteBuffer ; 31 import java.util.TimerTask ; 32 import java.util.Timer ; 33 34 38 public class RrdNioBackend extends RrdFileBackend { 39 53 public static final boolean SHOULD_GC = true; 54 55 static { 56 if(SHOULD_GC) { 57 final Runtime runtime = Runtime.getRuntime(); 58 runtime.addShutdownHook(new Thread () { 59 public void run() { 60 runtime.runFinalization(); 61 runtime.gc(); 62 } 63 }); 64 } 65 } 66 67 private static final Timer syncTimer = new Timer (true); 68 69 private int syncMode; 70 MappedByteBuffer byteBuffer; 71 private TimerTask syncTask; 72 73 protected RrdNioBackend(String path, boolean readOnly, int lockMode, int syncMode, int syncPeriod) 74 throws IOException { 75 super(path, readOnly, lockMode); 76 map(readOnly); 77 this.syncMode = syncMode; 78 if(syncMode == RrdNioBackendFactory.SYNC_BACKGROUND && !readOnly) { 79 createSyncTask(syncPeriod); 80 } 81 } 82 83 private void map(boolean readOnly) throws IOException { 84 long length = getLength(); 85 if(length > 0) { 86 FileChannel.MapMode mapMode = 87 readOnly? FileChannel.MapMode.READ_ONLY: FileChannel.MapMode.READ_WRITE; 88 byteBuffer = channel.map(mapMode, 0, length); 89 } 90 else { 91 byteBuffer = null; 92 } 93 } 94 95 private void createSyncTask(int syncPeriod) { 96 syncTask = new TimerTask () { 97 public void run() { 98 sync(); 99 } 100 }; 101 syncTimer.schedule(syncTask, syncPeriod * 1000L, syncPeriod * 1000L); 102 } 103 104 110 protected void setLength(long newLength) throws IOException { 111 if(newLength < getLength()) { 112 if(SHOULD_GC) { 114 byteBuffer = null; 115 System.gc(); 116 } 117 } 118 super.setLength(newLength); 119 map(false); 120 } 121 122 127 protected void write(long offset, byte[] b) { 128 synchronized(byteBuffer) { 129 byteBuffer.position((int)offset); 130 byteBuffer.put(b); 131 } 132 } 133 134 139 protected void read(long offset, byte[] b) { 140 synchronized(byteBuffer) { 141 byteBuffer.position((int)offset); 142 byteBuffer.get(b); 143 } 144 } 145 146 150 public void close() throws IOException { 151 if(syncTask != null) { 153 syncTask.cancel(); 154 } 155 super.close(); byteBuffer = null; 158 } 159 160 166 public void sync() { 167 if(byteBuffer != null) { 168 synchronized(byteBuffer) { 169 byteBuffer.force(); 171 } 172 } 173 } 174 175 180 protected void beforeUpdate() { 181 if(syncMode == RrdNioBackendFactory.SYNC_BEFOREUPDATE) { 182 sync(); 183 } 184 } 185 186 191 protected void afterUpdate() { 192 if(syncMode == RrdNioBackendFactory.SYNC_AFTERUPDATE) { 193 sync(); 194 } 195 } 196 197 202 protected void beforeFetch() { 203 if(syncMode == RrdNioBackendFactory.SYNC_BEFOREFETCH) { 204 sync(); 205 } 206 } 207 208 213 protected void afterFetch() { 214 if(syncMode == RrdNioBackendFactory.SYNC_AFTERFETCH) { 215 sync(); 216 } 217 } 218 } 219 | Popular Tags |