<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.flink.runtime.memory;

import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.core.memory.HybridMemorySegment;
import org.apache.flink.core.memory.MemorySegment;
import org.apache.flink.core.memory.MemorySegmentFactory;
import org.apache.flink.core.memory.MemoryType;
import org.apache.flink.util.MathUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;

/**
 * The memory manager governs the memory that Flink uses for sorting, hashing, and caching. Memory
 * is represented in segments of equal size. Operators allocate the memory by requesting a number
 * of memory segments.
 *
 * <p>The memory may be represented as on-heap byte arrays or as off-heap memory regions
 * (both via {@link HybridMemorySegment}). Which kind of memory the MemoryManager serves can
 * be passed as an argument to the initialization.
 *
 * <p>The memory manager can either pre-allocate all memory, or allocate the memory on demand. In the
 * former version, memory will be occupied and reserved from start on, which means that no OutOfMemoryError
 * can come while requesting memory. Released memory will also return to the MemoryManager's pool.
 * On-demand allocation means that the memory manager only keeps track how many memory segments are
 * currently allocated (bookkeeping only). Releasing a memory segment will not add it back to the pool,
 * but make it re-claimable by the garbage collector.
 */
public class MemoryManager {

	private static final Logger LOG = LoggerFactory.getLogger(MemoryManager.class);
	/** The default memory page size. Currently set to 32 KiBytes. */
	public static final int DEFAULT_PAGE_SIZE = 32 * 1024;

	/** The minimal memory page size. Currently set to 4 KiBytes. */
	public static final int MIN_PAGE_SIZE = 4 * 1024;

	// ------------------------------------------------------------------------

	/** The lock used on the shared structures. */
	private final Object lock = new Object();

	/** The memory pool from which we draw memory segments. Specific to on-heap or off-heap memory */
	private final MemoryPool memoryPool;

	/** Memory segments allocated per memory owner. */
	private final HashMap<Object, Set<MemorySegment>> allocatedSegments;

	/** The size of the memory segments. */
	private final int pageSize;

	/** The initial total size, for verification. */
	private final int totalNumPages;

	/** The total size of the memory managed by this memory manager. */
	private final long memorySize;

	/** Number of slots of the task manager. */
	private final int numberOfSlots;

	/** Flag marking whether the memory manager immediately allocates the memory. */
	private final boolean isPreAllocated;

	/** The number of memory pages that have not been allocated and are available for lazy allocation. */
	private int numNonAllocatedPages;

	/** Flag whether the close() has already been invoked. */
	private boolean isShutDown;


	/**
	 * Creates a memory manager with the given capacity and given page size.
	 *
	 * @param memorySize The total size of the memory to be managed by this memory manager.
	 * @param numberOfSlots The number of slots of the task manager.
	 * @param pageSize The size of the pages handed out by the memory manager.
	 * @param memoryType The type of memory (heap / off-heap) that the memory manager should allocate.
	 * @param preAllocateMemory True, if the memory manager should immediately allocate all memory, false
	 *                          if it should allocate and release the memory as needed.
	 */
	public MemoryManager(long memorySize, int numberOfSlots, int pageSize,
							MemoryType memoryType, boolean preAllocateMemory) {
		// sanity checks
		if (memoryType == null) {
			throw new NullPointerException();
		}
		if (memorySize <= 0) {
			throw new IllegalArgumentException("Size of total memory must be positive.");
		}
		if (pageSize < MIN_PAGE_SIZE) {
			throw new IllegalArgumentException("The page size must be at least " + MIN_PAGE_SIZE + " bytes.");
		}
		if (!MathUtils.isPowerOf2(pageSize)) {
			throw new IllegalArgumentException("The given page size is not a power of two.");
		}

		this.memorySize = memorySize;
		this.numberOfSlots = numberOfSlots;

		// assign page size and bit utilities
		this.pageSize = pageSize;

		final long numPagesLong = memorySize / pageSize;
		if (numPagesLong > Integer.MAX_VALUE) {
			throw new IllegalArgumentException("The given number of memory bytes (" + memorySize
					+ ") corresponds to more than MAX_INT pages.");
		}
		this.totalNumPages = (int) numPagesLong;
		if (this.totalNumPages < 1) {
			throw new IllegalArgumentException("The given amount of memory amounted to less than one page.");
		}

		this.allocatedSegments = new HashMap<Object, Set<MemorySegment>>();
		this.isPreAllocated = preAllocateMemory;

		this.numNonAllocatedPages = preAllocateMemory ? 0 : this.totalNumPages;
		final int memToAllocate = preAllocateMemory ? this.totalNumPages : 0;

		switch (memoryType) {
			case HEAP:
				this.memoryPool = new HybridHeapMemoryPool(memToAllocate, pageSize);
				break;
			case OFF_HEAP:
				if (!preAllocateMemory) {
					LOG.warn("It is advisable to set 'taskmanager.memory.preallocate' to true when" +
						" the memory type 'taskmanager.memory.off-heap' is set to true.");
				}
				this.memoryPool = new HybridOffHeapMemoryPool(memToAllocate, pageSize);
				break;
			default:
				throw new IllegalArgumentException("unrecognized memory type: " + memoryType);
		}

		LOG.debug("Initialized MemoryManager with total memory size {}, number of slots {}, page size {}, " +
				"memory type {}, pre allocate memory {} and number of non allocated pages {}.",
			memorySize,
			numberOfSlots,
			pageSize,
			memoryType,
			preAllocateMemory,
			numNonAllocatedPages);
	}

	// ------------------------------------------------------------------------
	//  Shutdown
	// ------------------------------------------------------------------------

	/**<commit_msg>[hotfix] Refactor MemoryManager constructor<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.flink.runtime.memory;

import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.configuration.TaskManagerOptions;
import org.apache.flink.core.memory.HybridMemorySegment;
import org.apache.flink.core.memory.MemorySegment;
import org.apache.flink.core.memory.MemorySegmentFactory;
import org.apache.flink.core.memory.MemoryType;
import org.apache.flink.util.MathUtils;
import org.apache.flink.util.Preconditions;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;

/**
 * The memory manager governs the memory that Flink uses for sorting, hashing, and caching. Memory
 * is represented in segments of equal size. Operators allocate the memory by requesting a number
 * of memory segments.
 *
 * <p>The memory may be represented as on-heap byte arrays or as off-heap memory regions
 * (both via {@link HybridMemorySegment}). Which kind of memory the MemoryManager serves can
 * be passed as an argument to the initialization.
 *
 * <p>The memory manager can either pre-allocate all memory, or allocate the memory on demand. In the
 * former version, memory will be occupied and reserved from start on, which means that no OutOfMemoryError
 * can come while requesting memory. Released memory will also return to the MemoryManager's pool.
 * On-demand allocation means that the memory manager only keeps track how many memory segments are
 * currently allocated (bookkeeping only). Releasing a memory segment will not add it back to the pool,
 * but make it re-claimable by the garbage collector.
 */
public class MemoryManager {

	private static final Logger LOG = LoggerFactory.getLogger(MemoryManager.class);
	/** The default memory page size. Currently set to 32 KiBytes. */
	public static final int DEFAULT_PAGE_SIZE = 32 * 1024;

	/** The minimal memory page size. Currently set to 4 KiBytes. */
	public static final int MIN_PAGE_SIZE = 4 * 1024;

	// ------------------------------------------------------------------------

	/** The lock used on the shared structures. */
	private final Object lock = new Object();

	/** The memory pool from which we draw memory segments. Specific to on-heap or off-heap memory */
	private final MemoryPool memoryPool;

	/** Memory segments allocated per memory owner. */
	private final HashMap<Object, Set<MemorySegment>> allocatedSegments;

	/** The size of the memory segments. */
	private final int pageSize;

	/** The initial total size, for verification. */
	private final int totalNumPages;

	/** The total size of the memory managed by this memory manager. */
	private final long memorySize;

	/** Number of slots of the task manager. */
	private final int numberOfSlots;

	/** Flag marking whether the memory manager immediately allocates the memory. */
	private final boolean isPreAllocated;

	/** The number of memory pages that have not been allocated and are available for lazy allocation. */
	private int numNonAllocatedPages;

	/** Flag whether the close() has already been invoked. */
	private boolean isShutDown;


	/**
	 * Creates a memory manager with the given capacity and given page size.
	 *
	 * @param memorySize The total size of the memory to be managed by this memory manager.
	 * @param numberOfSlots The number of slots of the task manager.
	 * @param pageSize The size of the pages handed out by the memory manager.
	 * @param memoryType The type of memory (heap / off-heap) that the memory manager should allocate.
	 * @param preAllocateMemory True, if the memory manager should immediately allocate all memory, false
	 *                          if it should allocate and release the memory as needed.
	 */
	public MemoryManager(
			long memorySize,
			int numberOfSlots,
			int pageSize,
			MemoryType memoryType,
			boolean preAllocateMemory) {
		sanityCheck(memorySize, pageSize, memoryType, preAllocateMemory);

		this.allocatedSegments = new HashMap<>();
		this.memorySize = memorySize;
		this.numberOfSlots = numberOfSlots;
		this.pageSize = pageSize;
		this.isPreAllocated = preAllocateMemory;
		this.totalNumPages = calculateTotalNumberOfPages(memorySize, pageSize);
		this.numNonAllocatedPages = preAllocateMemory ? 0 : this.totalNumPages;
		this.memoryPool = createMemoryPool(preAllocateMemory ? this.totalNumPages : 0, pageSize, memoryType);

		LOG.debug("Initialized MemoryManager with total memory size {}, number of slots {}, page size {}, " +
				"memory type {}, pre allocate memory {} and number of non allocated pages {}.",
			memorySize,
			numberOfSlots,
			pageSize,
			memoryType,
			preAllocateMemory,
			numNonAllocatedPages);
	}

	private static void sanityCheck(long memorySize, int pageSize, MemoryType memoryType, boolean preAllocateMemory) {
		Preconditions.checkNotNull(memoryType);
		Preconditions.checkArgument(memorySize > 0L, "Size of total memory must be positive.");
		Preconditions.checkArgument(
			pageSize >= MIN_PAGE_SIZE,
			"The page size must be at least %d bytes.", MIN_PAGE_SIZE);
		Preconditions.checkArgument(
			MathUtils.isPowerOf2(pageSize),
			"The given page size is not a power of two.");
		warnAboutPreallocationForOffHeap(memoryType, preAllocateMemory);
	}

	private static void warnAboutPreallocationForOffHeap(MemoryType memoryType, boolean preAllocateMemory) {
		if (memoryType == MemoryType.OFF_HEAP && !preAllocateMemory) {
			LOG.warn("It is advisable to set '{}' to true when the memory type '{}' is set to true.",
				TaskManagerOptions.MANAGED_MEMORY_PRE_ALLOCATE.key(),
				TaskManagerOptions.MEMORY_OFF_HEAP.key());
		}
	}

	private static int calculateTotalNumberOfPages(long memorySize, int pageSize) {
		long numPagesLong = memorySize / pageSize;
		Preconditions.checkArgument(
			numPagesLong <= Integer.MAX_VALUE,
			"The given number of memory bytes (%s) corresponds to more than MAX_INT pages.", memorySize);

		@SuppressWarnings("NumericCastThatLosesPrecision")
		int totalNumPages = (int) numPagesLong;
		Preconditions.checkArgument(totalNumPages >= 1, "The given amount of memory amounted to less than one page.");

		return totalNumPages;
	}

	private static MemoryPool createMemoryPool(int segmentsToAllocate, int pageSize, MemoryType memoryType) {
		switch (memoryType) {
			case HEAP:
				return new HybridHeapMemoryPool(segmentsToAllocate, pageSize);
			case OFF_HEAP:
				return new HybridOffHeapMemoryPool(segmentsToAllocate, pageSize);
			default:
				throw new IllegalArgumentException("unrecognized memory type: " + memoryType);
		}
	}

	// ------------------------------------------------------------------------
	//  Shutdown
	// ------------------------------------------------------------------------

	/**
{'fraction_non_alphanumeric': 0.10514316368269296, 'fraction_numerical': 0.003352779454167505, 'mean_word_length': 3.6130528920507268, 'pattern_counts': {'":': 0, '<': 18, '<?xml version=': 0, '>': 18, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6963860', 'n_tokens_mistral': 4133, 'n_tokens_neox': 3812, 'n_words': 1566}