private DiskElement checkForFreeBlock(int bufferLength) throws IOException { DiskElement diskElement = findFreeBlock(bufferLength); if (diskElement == null) { diskElement = new DiskElement(); diskElement.position = randomAccessFile.length(); diskElement.blockSize = bufferLength; } return diskElement; }
/** * Marks a block as free. * * @param diskElement the DiskElement to move to the free space list */ private void freeBlock(final DiskElement diskElement) { totalSize -= diskElement.payloadSize; diskElement.payloadSize = 0; // reset Element meta data diskElement.key = null; diskElement.hitcount = 0; diskElement.expiryTime = 0; freeSpace.add(diskElement); }
private void writeElement(Element element, Serializable key) throws IOException { try { int bufferLength; long expirationTime = element.getExpirationTime(); MemoryEfficientByteArrayOutputStream buffer = null; try { buffer = serializeEntry(element); bufferLength = buffer.size(); DiskElement diskElement = checkForFreeBlock(bufferLength); // Write the record randomAccessFile.seek(diskElement.position); randomAccessFile.write(buffer.toByteArray(), 0, bufferLength); buffer = null; // Add to index, update stats diskElement.payloadSize = bufferLength; diskElement.key = key; diskElement.expiryTime = expirationTime; diskElement.hitcount = element.getHitCount(); totalSize += bufferLength; lastElementSize = bufferLength; synchronized (diskElements) { diskElements.put(key, diskElement); } } catch (OutOfMemoryError e) { LOG.error("OutOfMemoryError on serialize: " + key); } } catch (Exception e) { // Catch any exception that occurs during serialization LOG.error( name + "Cache: Failed to write element to disk '" + key + "'. Initial cause was " + e.getMessage(), e); } }