public synchronized void free(QueryId queryId, String allocationTag, long bytes) { checkArgument(bytes >= 0, "bytes is negative"); checkArgument(reservedBytes >= bytes, "tried to free more memory than is reserved"); if (bytes == 0) { // Freeing zero bytes is a no-op return; } Long queryReservation = queryMemoryReservations.get(queryId); requireNonNull(queryReservation, "queryReservation is null"); checkArgument(queryReservation - bytes >= 0, "tried to free more memory than is reserved by query"); queryReservation -= bytes; if (queryReservation == 0) { queryMemoryReservations.remove(queryId); taggedMemoryAllocations.remove(queryId); } else { queryMemoryReservations.put(queryId, queryReservation); updateTaggedMemoryAllocations(queryId, allocationTag, -bytes); } reservedBytes -= bytes; if (getFreeBytes() > 0 && future != null) { future.set(null); future = null; } }
/** * Try to reserve the given number of bytes. Return value indicates whether the caller may use the requested memory. */ public boolean tryReserve(QueryId queryId, String allocationTag, long bytes) { checkArgument(bytes >= 0, "bytes is negative"); synchronized (this) { if (getFreeBytes() - bytes < 0) { return false; } reservedBytes += bytes; if (bytes != 0) { queryMemoryReservations.merge(queryId, bytes, Long::sum); updateTaggedMemoryAllocations(queryId, allocationTag, bytes); } } onMemoryReserved(); return true; }
/** * Reserves the given number of bytes. Caller should wait on the returned future, before allocating more memory. */ public ListenableFuture<?> reserve(QueryId queryId, String allocationTag, long bytes) { checkArgument(bytes >= 0, "bytes is negative"); ListenableFuture<?> result; synchronized (this) { if (bytes != 0) { queryMemoryReservations.merge(queryId, bytes, Long::sum); updateTaggedMemoryAllocations(queryId, allocationTag, bytes); } reservedBytes += bytes; if (getFreeBytes() <= 0) { if (future == null) { future = NonCancellableMemoryFuture.create(); } checkState(!future.isDone(), "future is already completed"); result = future; } else { result = NOT_BLOCKED; } } onMemoryReserved(); return result; }