You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ignite.apache.org by ag...@apache.org on 2018/03/13 13:37:51 UTC
[1/2] ignite git commit: IGNITE-7638 Implemented robin-hood hashing
for FullPageIdTable - Fixes #3481.
Repository: ignite
Updated Branches:
refs/heads/master ac3d54504 -> 1f8ec79d2
http://git-wip-us.apache.org/repos/asf/ignite/blob/1f8ec79d/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/RobinHoodBackwardShiftHashMap.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/RobinHoodBackwardShiftHashMap.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/RobinHoodBackwardShiftHashMap.java
new file mode 100644
index 0000000..fd4e0e6
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/RobinHoodBackwardShiftHashMap.java
@@ -0,0 +1,654 @@
+/*
+ * 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.ignite.internal.processors.cache.persistence.pagemem;
+
+import java.util.function.BiConsumer;
+import org.apache.ignite.internal.mem.IgniteOutOfMemoryException;
+import org.apache.ignite.internal.pagemem.FullPageId;
+import org.apache.ignite.internal.util.GridLongList;
+import org.apache.ignite.internal.util.GridUnsafe;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.jetbrains.annotations.NotNull;
+
+import static org.apache.ignite.IgniteSystemProperties.IGNITE_LONG_LONG_HASH_MAP_LOAD_FACTOR;
+import static org.apache.ignite.IgniteSystemProperties.getFloat;
+import static org.apache.ignite.internal.util.GridUnsafe.getInt;
+import static org.apache.ignite.internal.util.GridUnsafe.getLong;
+import static org.apache.ignite.internal.util.GridUnsafe.putInt;
+import static org.apache.ignite.internal.util.GridUnsafe.putLong;
+
+/**
+ * Loaded pages mapping to relative pointer based on Robin Hood hashing: backward shift deletion algorithm. <br>
+ * Performance of initial Robin Hood hashing could be greatly improved with only a little change to the removal
+ * method.<br> Instead of replacing entries with 'Removed' fake entries on deletion, backward shift deletion variant
+ * for the Robin Hood hashing algorithm does shift backward all the entries following the entry to delete until
+ * either an empty bucket, or a bucket with a DIB of 0 (distance to initial bucket).<br>
+ *
+ * Every deletion will shift backwards entries and therefore decrease their respective DIBs by 1
+ * (all their initial DIB values would be >= 1)<br>
+ *
+ * This implementation stores ideal bucket with entry value itself.<br>
+ *
+ */
+public class RobinHoodBackwardShiftHashMap implements LoadedPagesMap {
+ /** Load factor. */
+ private static final float LOAD_FACTOR = getFloat(IGNITE_LONG_LONG_HASH_MAP_LOAD_FACTOR, 2.5f);
+
+ /** Size of count of entries (value returned by size() method). */
+ private static final int MAPSIZE_SIZE = 4;
+
+ /** Padding to provide read/write from word beginning for each cell. Change this to 0 if padding is not required. */
+ private static final int CELL_PADDING = 4;
+
+ /** Padding to provide read/write from word beginning. Change this to 0 if padding is not required. */
+ private static final int MAPSIZE_PADDING = 4;
+
+ /** Count of entries offset starting from base address. */
+ private static final int MAPSIZE_OFFSET = 0;
+
+ /** Size of initial/ideal bucket (cell to store value to avoid probing other cells followed). */
+ private static final int IDEAL_BUCKET_SIZE = 4;
+
+ /** Offset of initial/ideal bucket starting from entry base. */
+ private static final int IDEAL_BUCKET_OFFSET = 0;
+
+ /** Group ID size. */
+ private static final int GRP_ID_SIZE = 4;
+
+ /** Group ID offset from entry base. */
+ private static final int GRP_ID_OFFSET = IDEAL_BUCKET_OFFSET + IDEAL_BUCKET_SIZE;
+
+ /** Page ID size. */
+ private static final int PAGE_ID_SIZE = 8;
+
+ /** Page ID offset from entry base. */
+ private static final int PAGE_ID_OFFSET = GRP_ID_OFFSET + GRP_ID_SIZE;
+
+ /** Value size. */
+ private static final int VALUE_SIZE = 8;
+
+ /** Value offset from entry base. */
+ private static final int VALUE_OFFSET = PAGE_ID_OFFSET + PAGE_ID_SIZE;
+
+ /** Version (tag/generation) offset from entry base. */
+ private static final int VERSION_SIZE = 4;
+
+ /** Version (tag/generation) offset from entry base. */
+ private static final int VERSION_OFFSET = VALUE_OFFSET + VALUE_SIZE;
+
+ /** Page ID used for empty bucket. */
+ private static final long EMPTY_PAGE_ID = 0;
+
+ /** Cache Group ID used for empty bucket. */
+ private static final int EMPTY_CACHE_GRP_ID = 0;
+
+ /** Bytes required for storing one entry (cell). */
+ private static final int BYTES_PER_CELL = IDEAL_BUCKET_SIZE
+ + GRP_ID_SIZE + PAGE_ID_SIZE
+ + VALUE_SIZE + VERSION_SIZE
+ + CELL_PADDING;
+
+ /** Number of buckets, indicates range of scan memory, max probe count and maximum map size. */
+ private final int numBuckets;
+
+ /** Base address of map content. */
+ private long baseAddr;
+
+ /**
+ * @param elementsCnt Maximum elements can be stored in map, its maximum size.
+ * @return Estimated memory size required for this map to store the given number of elements.
+ */
+ public static long requiredMemory(long elementsCnt) {
+ float loadFactor = LOAD_FACTOR;
+
+ assert loadFactor != 0;
+
+ return requiredMemoryByBuckets((long)(elementsCnt * loadFactor));
+ }
+
+ /**
+ * @param numBuckets Number of buckets (cells) to store, capacity.
+ * @return required size to allocate, based on number of buckets (cells) to store in map, its capacity.
+ */
+ static long requiredMemoryByBuckets(long numBuckets) {
+ return numBuckets * BYTES_PER_CELL + MAPSIZE_SIZE + MAPSIZE_PADDING;
+ }
+
+ /**
+ * Creates map in preallocated unsafe memory segment.
+ *
+ * @param baseAddr Base buffer address.
+ * @param size Size available for map, number of buckets (cells) to store will be determined accordingly.
+ */
+ public RobinHoodBackwardShiftHashMap(long baseAddr, long size) {
+ this.numBuckets = (int)((size - MAPSIZE_SIZE - MAPSIZE_PADDING) / BYTES_PER_CELL);
+ this.baseAddr = baseAddr;
+
+ GridUnsafe.setMemory(baseAddr, size, (byte)0);
+ }
+
+ /**
+ * @param idx cell index.
+ * @return base cell (bucket) address in buffer.
+ */
+ private long entryBase(int idx) {
+ assert idx >= 0 && idx < numBuckets;
+
+ return baseAddr + MAPSIZE_SIZE + MAPSIZE_PADDING + (long)idx * BYTES_PER_CELL;
+ }
+
+ /** {@inheritDoc} */
+ @Override public long get(int grpId, long pageId, int reqVer, long absent, long outdated) {
+ assert grpId != EMPTY_CACHE_GRP_ID;
+
+ // initial index is also ideal for searhed element
+ int idxInit = U.safeAbs(FullPageId.hashCode(grpId, pageId)) % numBuckets;
+
+ for (int i = 0; i < numBuckets; i++) {
+ int idxCurr = (idxInit + i) % numBuckets;
+
+ final long base = entryBase(idxCurr);
+ final int distanceFromInit = distance(idxCurr, idxInit);
+
+ final int curGrpId = getGrpId(base);
+ final long curPageId = getPageId(base);
+
+ final int dibCurEntry = distance(idxCurr, getIdealBucket(base));
+
+ if (isEmpty(curGrpId, curPageId))
+ return absent;
+ else if (curGrpId == grpId && curPageId == pageId) {
+ //equal value found
+ long actualVer = getVersion(base);
+ boolean freshVal = actualVer >= reqVer;
+
+ return freshVal ? getValue(base) : outdated;
+ }
+ else if (dibCurEntry < distanceFromInit) {
+ //current entry has quite good position, it would be swapped at hypothetical insert of current value
+ return absent;
+ }
+ }
+
+ return absent;
+ }
+
+ /** {@inheritDoc} */
+ @Override public void put(int grpId, long pageId, long val, int ver) {
+ assert grpId != 0;
+
+ // initial index is also ideal for inserted element
+ int idxInit = U.safeAbs(FullPageId.hashCode(grpId, pageId)) % numBuckets;
+
+ int swapCnt = 0;
+
+ int grpIdToInsert = grpId;
+ long pageIdToInsert = pageId;
+ long valToInsert = val;
+ int verToInsert = ver;
+ long idxIdealToInsert = idxInit;
+
+ for (int i = 0; i < numBuckets; i++) {
+ int idxCurr = (idxInit + i) % numBuckets;
+
+ final long base = entryBase(idxCurr);
+ final int dibEntryToInsert = distance(idxCurr, idxInit);
+
+ final int curGrpId = getGrpId(base);
+ final long curPageId = getPageId(base);
+ final int curIdealBucket = getIdealBucket(base);
+ final long curVal = getValue(base);
+ final int curVer = getVersion(base);
+ final int dibCurEntry = distance(idxCurr, curIdealBucket);
+
+ if (isEmpty(curGrpId, curPageId)) {
+ setCellValue(base, idxIdealToInsert, grpIdToInsert, pageIdToInsert, valToInsert, verToInsert);
+
+ setSize(size() + 1);
+
+ return;
+ }
+ else if (curGrpId == grpIdToInsert && curPageId == pageIdToInsert) {
+ if (swapCnt != 0)
+ throw new IllegalStateException("Swapped " + swapCnt + " times. Entry: " + dumpEntry(idxCurr));
+
+ setValue(base, valToInsert);
+
+ return; //equal value found
+ }
+ else if (dibCurEntry < dibEntryToInsert) {
+ //swapping *toInsert and state in bucket: save cur state to bucket
+ setCellValue(base, idxIdealToInsert, grpIdToInsert, pageIdToInsert, valToInsert, verToInsert);
+
+ idxIdealToInsert = curIdealBucket;
+ pageIdToInsert = curPageId;
+ grpIdToInsert = curGrpId;
+ valToInsert = curVal;
+ verToInsert = curVer;
+
+ swapCnt++;
+ }
+ }
+
+ // no free space left
+ throw new IgniteOutOfMemoryException("No room for a new key");
+ }
+
+ /** {@inheritDoc} */
+ @Override public boolean remove(int grpId, long pageId) {
+ assert grpId != EMPTY_CACHE_GRP_ID;
+
+ int idxInit = U.safeAbs(FullPageId.hashCode(grpId, pageId)) % numBuckets;
+
+ int idxEqualValFound = -1;
+ for (int i = 0; i < numBuckets; i++) {
+ int idxCurr = (idxInit + i) % numBuckets;
+
+ final long base = entryBase(idxCurr);
+ final int dibEntryToInsert = distance(idxCurr, idxInit);
+
+ final int curGrpId = getGrpId(base);
+ final long curPageId = getPageId(base);
+ final int curIdealBucket = getIdealBucket(base);
+ final int dibCurEntry = distance(idxCurr, curIdealBucket);
+
+ if (isEmpty(curGrpId, curPageId))
+ return false;
+ else if (curGrpId == grpId && curPageId == pageId) {
+ idxEqualValFound = idxCurr;
+
+ break; //equal value found
+ }
+ else if (dibCurEntry < dibEntryToInsert) {
+ //If our value was present in map we had already found it.
+ return false;
+ }
+ }
+
+ setSize(size() - 1);
+
+ doBackwardShift(idxEqualValFound);
+
+ return true;
+ }
+
+ /**
+ * Runs backward shifts from current index to .
+ *
+ * @param idxRmv removed index.
+ */
+ private void doBackwardShift(int idxRmv) {
+ assert idxRmv >= 0;
+
+ //scanning rest of map to perform backward shifts
+ for (int i = 0; i < numBuckets - 1; i++) {
+ int idxCurr = (idxRmv + i) % numBuckets;
+ int idxNext = (idxRmv + i + 1) % numBuckets;
+
+ long baseCurr = entryBase(idxCurr);
+
+ long baseNext = entryBase(idxNext);
+ final int nextGrpId = getGrpId(baseNext);
+ final long nextPageId = getPageId(baseNext);
+ final int nextIdealBucket = getIdealBucket(baseNext);
+ final int nextEntryVer = getVersion(baseNext);
+
+ if (isEmpty(nextGrpId, nextPageId)
+ || distance(idxNext, nextIdealBucket) == 0) {
+ setEmpty(baseCurr);
+
+ return;
+ }
+ else
+ setCellValue(baseCurr, nextIdealBucket, nextGrpId, nextPageId, getValue(baseNext), nextEntryVer);
+ }
+
+ int lastShiftedIdx = (idxRmv - 1) % numBuckets;
+
+ setEmpty(entryBase(lastShiftedIdx));
+ }
+
+ /** {@inheritDoc} */
+ @Override public ReplaceCandidate getNearestAt(final int idxStart) {
+ for (int i = 0; i < numBuckets; i++) {
+ int idxCurr = (idxStart + i) % numBuckets;
+
+ if (isEmptyAt(idxCurr))
+ continue;
+
+ long base = entryBase(idxCurr);
+
+ return new ReplaceCandidate(getVersion(base), getValue(base), getFullPageId(base));
+ }
+
+ return null;
+ }
+
+ /**
+ * @param idx Index to test.
+ * @return {@code True} if value is not provided in cell having index.
+ */
+ private boolean isEmptyAt(int idx) {
+ long base = entryBase(idx);
+
+ return isEmpty(getGrpId(base), getPageId(base));
+ }
+
+ /** {@inheritDoc} */
+ @Override public long refresh(int grpId, long pageId, int ver) {
+ assert grpId != EMPTY_CACHE_GRP_ID;
+
+ int idxInit = U.safeAbs(FullPageId.hashCode(grpId, pageId)) % numBuckets;
+
+ for (int i = 0; i < numBuckets; i++) {
+ int idxCurr = (idxInit + i) % numBuckets;
+
+ final long base = entryBase(idxCurr);
+ final int distanceFromInit = distance(idxCurr, idxInit);
+
+ final int curGrpId = getGrpId(base);
+ final long curPageId = getPageId(base);
+ final int curIdealBucket = getIdealBucket(base);
+ final int dibCurEntry = distance(idxCurr, curIdealBucket);
+
+ if (isEmpty(curGrpId, curPageId))
+ break; // break to fail
+ else if (curGrpId == grpId && curPageId == pageId) {
+ //equal value found
+ long actualVer = getVersion(base);
+
+ boolean freshVal = actualVer >= ver;
+
+ if (freshVal) {
+ throw new IllegalArgumentException("Fresh element found at " +
+ dumpEntry(idxCurr) + " during search of cell to refresh. " +
+ "Refresh should be called for existent outdated element. ");
+ }
+
+ setVersion(base, ver);
+
+ return getValue(base);
+ }
+ else if (dibCurEntry < distanceFromInit) {
+ //current entry has quite good position, it would be swapped at hypothetical insert of current value
+
+ break;
+ }
+ }
+
+ throw new IllegalArgumentException("Element not found group ID: " + grpId + ", page ID: " + pageId +
+ " during search of cell to refresh. Refresh should be called for existent outdated element. ");
+ }
+
+ /** {@inheritDoc} */
+ @Override public GridLongList removeIf(int startIdxToClear, int endIdxToClear, KeyPredicate keyPred) {
+ assert endIdxToClear >= startIdxToClear
+ : "Start and end indexes are not consistent: {" + startIdxToClear + ", " + endIdxToClear + "}";
+
+ int sz = endIdxToClear - startIdxToClear;
+
+ GridLongList list = new GridLongList(sz);
+
+ for (int idx = startIdxToClear; idx < endIdxToClear; idx++) {
+ long base = entryBase(idx);
+
+ int grpId = getGrpId(base);
+ long pageId = getPageId(base);
+
+ if (isEmpty(grpId, pageId))
+ continue; // absent value, no removal required
+
+ if (!keyPred.test(grpId, pageId))
+ continue; // not matched value, no removal required
+
+ long valAt = getValue(base);
+
+ setSize(size() - 1);
+
+ doBackwardShift(idx);
+
+ list.add(valAt);
+
+ idx--; //Need recheck current cell because of backward shift
+ }
+
+ return list;
+ }
+
+ /** {@inheritDoc} */
+ @Override public int capacity() {
+ return numBuckets;
+ }
+
+ /**
+ * @param curr current selected index to store value.
+ * @param baseIdx base or ideal bucket to store entry value to avoid probing.
+ * @return distance between cells, or 0 if cell is ideal.
+ */
+ private int distance(int curr, int baseIdx) {
+ int diff = curr - baseIdx;
+
+ if (diff < 0)
+ return diff + numBuckets;
+
+ return diff;
+ }
+
+ /**
+ * @param grpId Cache group ID.
+ * @param pageId Page ID.
+ * @return {@code true} if group & page id indicates cell has state 'Empty'.
+ */
+ private boolean isEmpty(int grpId, long pageId) {
+ return pageId == EMPTY_PAGE_ID && grpId == EMPTY_CACHE_GRP_ID;
+ }
+
+ /**
+ * Sets cell value to be empty.
+ *
+ * @param addr entry base address.
+ */
+ private void setEmpty(long addr) {
+ setPageId(addr, EMPTY_PAGE_ID);
+ setGrpId(addr, EMPTY_CACHE_GRP_ID);
+ setValue(addr, 0);
+ setIdealBucket(addr, 0);
+ setVersion(addr, 0);
+ }
+
+ /**
+ * @param base Entry base, address in buffer of the entry start.
+ * @param idxIdeal number of ideal bucket (cell) to insert this value.
+ */
+ private void setIdealBucket(long base, long idxIdeal) {
+ assert idxIdeal >= 0 && idxIdeal < numBuckets;
+
+ putLong(base + IDEAL_BUCKET_OFFSET, idxIdeal);
+ }
+
+ /**
+ * @return printable dump with all buckets state.
+ */
+ public String dump() {
+ StringBuilder sb = new StringBuilder();
+
+ for (int idx = 0; idx < numBuckets; idx++)
+ dumpEntry(sb, idx);
+
+ return sb.toString();
+ }
+
+ /**
+ * @param idx index of entry to dump
+ * @return string representation of bucket content.
+ */
+ private String dumpEntry(int idx) {
+ StringBuilder sb = new StringBuilder();
+
+ dumpEntry(sb, idx);
+
+ return sb.toString();
+ }
+
+ /**
+ * @param sb destination string builder to dump entry to.
+ * @param idx bucket index.
+ */
+ private void dumpEntry(StringBuilder sb, int idx) {
+ long base = entryBase(idx);
+ int curGrpId = getGrpId(base);
+ long curPageId = getPageId(base);
+ long curVal = getValue(base);
+ long ver = getVersion(base);
+
+ sb.append("slot [").append(idx).append("]:");
+
+ if (isEmpty(curGrpId, curPageId))
+ sb.append("Empty: ");
+
+ sb.append("i.buc=").append(getIdealBucket(base)).append(",");
+ sb.append("(grp=").append(curGrpId).append(",");
+ sb.append("page=").append(curPageId).append(")");
+ sb.append("->");
+ sb.append("(val=").append(curVal).append(",");
+ sb.append("ver=").append(ver).append(")");
+ sb.append("\n");
+ }
+
+ /**
+ * @param base Entry base, address in buffer of the entry start.
+ * @param idealBucket number of ideal bucket (cell) to insert this value.
+ * @param grpId Entry key. Group ID to be stored in entry.
+ * @param pageId Entry key. Page ID to be stored.
+ * @param val Entry value associated with key.
+ * @param ver Entry version.
+ */
+ private void setCellValue(long base, long idealBucket, int grpId, long pageId, long val, int ver) {
+ setIdealBucket(base, idealBucket);
+ setGrpId(base, grpId);
+ setPageId(base, pageId);
+ setValue(base, val);
+ setVersion(base, ver);
+ }
+
+ /**
+ * @param base address of current cell.
+ * @return number of ideal bucket (cell) to store this value.
+ */
+ private int getIdealBucket(long base) {
+ return getInt(base + IDEAL_BUCKET_OFFSET);
+ }
+
+ /**
+ * @param base Address of current cell.
+ * @return Page ID saved in cell.
+ */
+ private long getPageId(long base) {
+ return getLong(base + PAGE_ID_OFFSET);
+ }
+
+ /**
+ * @param base Address of cell.
+ * @param pageId Page ID to set in current cell.
+ */
+ private void setPageId(long base, long pageId) {
+ putLong(base + PAGE_ID_OFFSET, pageId);
+ }
+
+ /**
+ * @param base Entry base address.
+ * @return Group ID stored in entry.
+ */
+ private int getGrpId(long base) {
+ return getInt(base + GRP_ID_OFFSET);
+ }
+
+ /**
+ * @param base Entry base address.
+ * @param grpId Group ID to be stored in entry.
+ */
+ private void setGrpId(long base, int grpId) {
+ putInt(base + GRP_ID_OFFSET, grpId);
+ }
+
+ /**
+ * @param base Bucket base address.
+ * @return value stored in bucket.
+ */
+ private long getValue(long base) {
+ return getLong(base + VALUE_OFFSET);
+ }
+
+ /**
+ * @param base Bucket base address.
+ * @param val Value to store in bucket.
+ */
+ private void setValue(long base, long val) {
+ putLong(base + VALUE_OFFSET, val);
+ }
+
+ /**
+ * @param base Bucket base address.
+ * @return Entry version associated with bucket.
+ */
+ private int getVersion(long base) {
+ return getInt(base + VERSION_OFFSET);
+ }
+
+ /**
+ * @param base Bucket base address.
+ * @param ver Entry version to set in bucket.
+ */
+ private void setVersion(long base, int ver) {
+ putInt(base + VERSION_OFFSET, ver);
+ }
+
+ /** {@inheritDoc} */
+ @Override public final int size() {
+ return GridUnsafe.getInt(baseAddr + MAPSIZE_OFFSET);
+ }
+
+ /**
+ * Changes collection size.
+ *
+ * @param sz new size to set.
+ */
+ private void setSize(int sz) {
+ putInt(baseAddr + MAPSIZE_OFFSET, sz);
+ }
+
+ /** {@inheritDoc} */
+ @Override public void forEach(BiConsumer<FullPageId, Long> act) {
+ for (int i = 0; i < numBuckets; i++) {
+ if (isEmptyAt(i))
+ continue;
+
+ long base = entryBase(i);
+
+ act.accept(getFullPageId(base), getValue(base));
+ }
+ }
+
+ /**
+ * @param base bucket base address.
+ * @return Key. Full page ID from bucket.
+ */
+ @NotNull private FullPageId getFullPageId(long base) {
+ return new FullPageId(getPageId(base), getGrpId(base));
+ }
+}
http://git-wip-us.apache.org/repos/asf/ignite/blob/1f8ec79d/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/db/checkpoint/IgniteMassLoadSandboxTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/db/checkpoint/IgniteMassLoadSandboxTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/db/checkpoint/IgniteMassLoadSandboxTest.java
index 316cb8b..76cd5bd 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/db/checkpoint/IgniteMassLoadSandboxTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/db/checkpoint/IgniteMassLoadSandboxTest.java
@@ -110,7 +110,7 @@ public class IgniteMassLoadSandboxTest extends GridCommonAbstractTest {
DataRegionConfiguration regCfg = new DataRegionConfiguration()
.setName("dfltMemPlc")
.setMetricsEnabled(true)
- .setMaxSize(256L * 1024 * 1024)
+ .setMaxSize(2 * 1024L * 1024 * 1024)
.setPersistenceEnabled(true);
DataStorageConfiguration dsCfg = new DataStorageConfiguration();
http://git-wip-us.apache.org/repos/asf/ignite/blob/1f8ec79d/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/FullPageIdTableTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/FullPageIdTableTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/FullPageIdTableTest.java
index 1f29549..43b27aa 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/FullPageIdTableTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/FullPageIdTableTest.java
@@ -20,32 +20,45 @@ package org.apache.ignite.internal.processors.cache.persistence.pagemem;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
+import org.apache.ignite.internal.mem.DirectMemoryProvider;
import org.apache.ignite.internal.mem.DirectMemoryRegion;
import org.apache.ignite.internal.mem.unsafe.UnsafeMemoryProvider;
import org.apache.ignite.internal.pagemem.FullPageId;
-import org.apache.ignite.internal.processors.cache.persistence.pagemem.FullPageIdTable;
-import org.apache.ignite.internal.util.typedef.CI2;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.logger.java.JavaLogger;
-import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
/**
*
*/
-public class FullPageIdTableTest extends GridCommonAbstractTest {
+public class FullPageIdTableTest {
+ /** */
+ private static final int CACHE_ID_RANGE = 1;
+
+ /** */
+ private static final int PAGE_ID_RANGE = 3000;
+
/** */
- private static final int CACHE_ID_RANGE = 10;
+ private static final int CACHE_ID_RANGE2 = 1024;
/** */
- private static final int PAGE_ID_RANGE = 1000;
+ private static final int PAGE_ID_RANGE2 = 3000;
+
+ /** Logger. */
+ private JavaLogger log = new JavaLogger();
/**
* @throws Exception if failed.
*/
+ @Test
public void testRandomOperations() throws Exception {
- long mem = FullPageIdTable.requiredMemory(CACHE_ID_RANGE * PAGE_ID_RANGE);
+ int cnt = CACHE_ID_RANGE * PAGE_ID_RANGE;
+
+ long mem = FullPageIdTable.requiredMemory(cnt);
- UnsafeMemoryProvider prov = new UnsafeMemoryProvider(new JavaLogger());
+ UnsafeMemoryProvider prov = new UnsafeMemoryProvider(log);
prov.initialize(new long[] {mem});
@@ -58,7 +71,7 @@ public class FullPageIdTableTest extends GridCommonAbstractTest {
Random rnd = new Random(seed);
- FullPageIdTable tbl = new FullPageIdTable(region.address(), region.size(), true);
+ LoadedPagesMap tbl = new FullPageIdTable(region.address(), region.size(), true);
Map<FullPageId, Long> check = new HashMap<>();
@@ -77,7 +90,7 @@ public class FullPageIdTableTest extends GridCommonAbstractTest {
check.put(fullId, val);
}
else {
- tbl.remove(cacheId, pageId, 0);
+ tbl.remove(cacheId, pageId);
check.remove(fullId);
}
@@ -93,23 +106,163 @@ public class FullPageIdTableTest extends GridCommonAbstractTest {
}
/**
+ * @throws Exception if failed.
+ */
+ @Test
+ public void putRemoveScenario() throws Exception {
+ long seed = U.currentTimeMillis();
+
+ doPutRemoveTest(seed, false, 1_000_000);
+ }
+
+ /**
+ * @throws Exception if failed.
+ */
+ @Test
+ public void putRemoveScenarioNewMap() throws Exception {
+ long seed = U.currentTimeMillis();
+ doPutRemoveTest(seed, true, 30_000_000);
+ }
+
+ /**
+ * @param seed random initial value.
+ * @param newMapImpl use RobinHood map
+ * @param iters iterations.
+ */
+ private void doPutRemoveTest(long seed, boolean newMapImpl, int iters) {
+ int elementsCnt = 7000;
+
+ //System.setProperty(IGNITE_LONG_LONG_HASH_MAP_LOAD_FACTOR, "11");
+ long mem = newMapImpl
+ ? RobinHoodBackwardShiftHashMap.requiredMemory(elementsCnt)
+ : FullPageIdTable.requiredMemory(elementsCnt);
+
+ DirectMemoryProvider prov = new UnsafeMemoryProvider(log);
+
+ prov.initialize(new long[] {mem});
+
+ DirectMemoryRegion region = prov.nextRegion();
+
+ try {
+ info("Seed: " + seed + "L; //");
+
+ Random rnd = new Random(seed);
+
+ LoadedPagesMap tbl =
+ newMapImpl
+ ? new RobinHoodBackwardShiftHashMap(region.address(), region.size())
+ : new FullPageIdTable(region.address(), region.size(), true);
+
+ Map<FullPageId, Long> check = new HashMap<>();
+
+ int tag = 0;
+ for (int i = 0; i < iters; i++) {
+ int op = rnd.nextInt(5);
+
+ int cacheId = rnd.nextInt(CACHE_ID_RANGE2) + 1;
+ int pageId = rnd.nextInt(PAGE_ID_RANGE2);
+
+ FullPageId fullId = new FullPageId(pageId, cacheId);
+
+ if (op == 0) {
+ long val = tbl.get(cacheId, pageId, tag, -1, -2);
+ if (val == -2)
+ tbl.refresh(cacheId, pageId, tag);
+ else {
+ Long checkVal = check.get(fullId);
+
+ if (checkVal != null) {
+ assertEquals("Ret " + val + "Check " + checkVal,
+ checkVal.longValue(), val);
+ }
+ }
+
+ }
+ else if ((op == 1 || op == 2) && (check.size() < elementsCnt)) {
+ long val = U.safeAbs(rnd.nextLong());
+
+ tbl.put(cacheId, pageId, val, tag);
+ check.put(fullId, val);
+ }
+ else if ((op == 3) && check.size() >= elementsCnt * 2 / 3) {
+ tbl.remove(cacheId, pageId);
+ check.remove(fullId);
+ }
+ else if (check.size() >= elementsCnt * 2 / 3) {
+ int idx = rnd.nextInt(tbl.capacity());
+ ReplaceCandidate ec = tbl.getNearestAt(idx);
+ if (ec != null) {
+ FullPageId fullPageId = ec.fullId();
+
+ tbl.remove(fullPageId.groupId(), fullPageId.pageId());
+
+ check.remove(fullPageId);
+ }
+ }
+
+ if (i > 0 && i % 100_000 == 0) {
+ info("Done: " + i
+ + " Size: " + check.size()
+ + " Capacity: " + tbl.capacity() );
+
+ verifyLinear(tbl, check);
+
+ tag++;
+ }
+
+ i++;
+ }
+
+ verifyLinear(tbl, check);
+ }
+ finally {
+ long msPassed = U.currentTimeMillis() - seed;
+ System.err.println("Seed used [" + seed + "] duration ["+ msPassed+ "] ms");
+ prov.shutdown();
+ }
+ }
+
+ /**
+ * @param msg Message to print.
+ */
+ protected void info(String msg) {
+ if (log.isInfoEnabled())
+ log.info(msg);
+
+ System.out.println(msg);
+ }
+
+
+ /**
* @param tbl Table to check.
* @param check Expected mapping.
*/
- private void verifyLinear(FullPageIdTable tbl, Map<FullPageId, Long> check) {
- final Map<FullPageId, Long> collector = new HashMap<>();
+ private void verifyLinear(LoadedPagesMap tbl, Map<FullPageId, Long> check) {
+ final Map<FullPageId, Long> tblSnapshot = new HashMap<>();
- tbl.visitAll(new CI2<FullPageId, Long>() {
- @Override public void apply(FullPageId fullId, Long val) {
- if (collector.put(fullId, val) != null)
- throw new AssertionError("Duplicate full page ID mapping: " + fullId);
- }
+ tbl.forEach((fullId, val) -> {
+ if (tblSnapshot.put(fullId, val) != null)
+ throw new AssertionError("Duplicate full page ID mapping: " + fullId);
});
- assertEquals("Size check failed", check.size(), collector.size());
+ int chkSize = check.size();
+ int foundTblSize = tblSnapshot.size();
- for (Map.Entry<FullPageId, Long> entry : check.entrySet())
- assertEquals("Mapping comparison failed for key: " + entry.getKey(),
- entry.getValue(), collector.get(entry.getKey()));
+ HashMap<FullPageId, Long> cp = new HashMap<>(tblSnapshot);
+ check.keySet().forEach(cp::remove);
+
+ assertEquals("Size check failed, check map size " +
+ chkSize + " but found in table " + foundTblSize + " elements," +
+ " table size " + tbl.size() +
+ "\n Difference: " + cp, chkSize, foundTblSize);
+
+ for (Map.Entry<FullPageId, Long> entry : check.entrySet()) {
+ Long valCheck = entry.getValue();
+ Long actual = tblSnapshot.get(entry.getKey());
+
+ if (!valCheck.equals(actual))
+ assertEquals("Mapping comparison failed for key: " + entry.getKey(),
+ valCheck, actual);
+ }
}
}
http://git-wip-us.apache.org/repos/asf/ignite/blob/1f8ec79d/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/RobinHoodBackwardShiftHashMapTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/RobinHoodBackwardShiftHashMapTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/RobinHoodBackwardShiftHashMapTest.java
new file mode 100644
index 0000000..da59145
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/RobinHoodBackwardShiftHashMapTest.java
@@ -0,0 +1,430 @@
+/*
+ * 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.ignite.internal.processors.cache.persistence.pagemem;
+
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Random;
+import java.util.function.Consumer;
+import org.apache.ignite.internal.mem.IgniteOutOfMemoryException;
+import org.apache.ignite.internal.pagemem.FullPageId;
+import org.apache.ignite.internal.util.GridLongList;
+import org.apache.ignite.internal.util.GridUnsafe;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.hamcrest.MatcherAssert;
+import org.hamcrest.Matchers;
+import org.jetbrains.annotations.NotNull;
+import org.junit.Test;
+
+import static org.apache.ignite.IgniteSystemProperties.IGNITE_LONG_LONG_HASH_MAP_LOAD_FACTOR;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Unit tests of {@link RobinHoodBackwardShiftHashMap} implementation.
+ */
+public class RobinHoodBackwardShiftHashMapTest {
+
+ /**
+ * @param tester map test code
+ * @param cap required map capacity.
+ */
+ private void withMap(Consumer<RobinHoodBackwardShiftHashMap> tester, int cap) {
+ long memSize = RobinHoodBackwardShiftHashMap.requiredMemoryByBuckets(cap);
+ long addr = GridUnsafe.allocateMemory(memSize);
+
+ RobinHoodBackwardShiftHashMap map = new RobinHoodBackwardShiftHashMap(addr, memSize);
+ boolean success = false;
+ try {
+ tester.accept(map);
+
+ success = true;
+ }
+ finally {
+ if (!success)
+ System.err.println(map.dump());
+
+ GridUnsafe.freeMemory(addr);
+ }
+ }
+
+ /**
+ * @throws Exception If failed.
+ */
+ @Test
+ public void testSimplestPutGet() throws Exception {
+ int cnt = 100;
+ withMap(map -> {
+ for (int i = 0; i < cnt; i++) {
+ int grpId = i + 1;
+ int val = grpId * grpId;
+
+ assertSizeChanged("Unique put should be successful " + grpId,
+ map, () -> map.put(grpId, 1, val, 1));
+ assertEquals(val, map.get(grpId, 1, 0, -1, -2));
+
+ assertSizeNotChanged("Duplicate put for " + grpId,
+ map, () -> map.put(grpId, 1, 1, 1));
+ assertEquals(1, map.get(grpId, 1, 0, -1, -2));
+ }
+
+ assertEquals(cnt, map.size());
+ }
+ , cnt);
+ }
+
+ /**
+ * @throws Exception If failed.
+ */
+ @Test(expected = IgniteOutOfMemoryException.class)
+ public void testSimplestOverflow() throws Exception {
+ withMap(map -> {
+ for (int i = 0; i < 10; i++) {
+ int grpId = i + 1;
+ int val = grpId * grpId;
+ assertSizeChanged("Unique put should be successful [" + grpId + "]", map, () -> map.put(grpId, 1, val, 1));
+
+ assertEquals(val, map.get(grpId, 1, 0, -1, -2));
+
+ assertSizeNotChanged("Duplicate put for " + grpId, map, () -> map.put(grpId, 1, 1, 1));
+ assertEquals(1, map.get(grpId, 1, 0, -1, -2));
+ }
+
+ map.put(11, 1, 11, 1);
+ }
+ , 10);
+ }
+
+ /**
+ * @param msg message to dump in case assertion failed.
+ * @param map page map to check.
+ * @param act action during which size is expected to be changed.
+ */
+ private static void assertSizeChanged(String msg, LoadedPagesMap map, Runnable act) {
+ int size = map.size();
+ act.run();
+ int newSize = map.size();
+
+ assertNotEquals(msg, size, newSize);
+ }
+
+ /**
+ * @param msg message to dump in case assertion failed.
+ * @param map page map to check.
+ * @param act action during which size is expected to constant.
+ */
+ private static void assertSizeNotChanged(String msg, LoadedPagesMap map, Runnable act) {
+ int size = map.size();
+ act.run();
+ int newSize = map.size();
+
+ assertEquals(msg, size, newSize);
+ }
+
+ /**
+ * @throws Exception If failed.
+ */
+ @Test
+ public void testPutRemoveOnSamePlaces() throws Exception {
+ withMap(map -> {
+ doAddRemove(map);
+
+ //fill with 1 space left;
+ for (int i = 0; i < 99; i++) {
+ int grpId = i + 1;
+ int val = grpId * grpId;
+ assertSizeChanged("Unique put should be successful " + grpId, map,
+ () -> map.put(grpId, 1, val, 1));
+ }
+
+ doAddRemove(map);
+ }
+ , 100);
+ }
+
+ /**
+ * @param map tested map implementation
+ */
+ private void doAddRemove(LoadedPagesMap map) {
+ for (int i = 0; i < 100; i++) {
+ int grpId = i + 1;
+ int val = grpId * grpId;
+ map.put(grpId, 1, val, 1);
+ assertEquals(val, map.get(grpId, 1, 0, -1, -2));
+
+ assertTrue(map.remove(grpId, 1));
+ assertEquals(-1, map.get(grpId, 1, 0, -1, -2));
+ }
+ }
+
+ /**
+ *
+ */
+ @Test
+ public void testCollisionOnRemove() {
+ Map<FullPageId, Long> ctrl = new LinkedHashMap<>();
+ int cap = 10;
+ FullPageId baseId = new FullPageId(0, 1);
+
+ withMap(map -> {
+ for (int i = 0; i < cap; i++) {
+ int grpId = i + 1;
+ int pageId = findPageIdForCollision(grpId, baseId, cap);
+ ctrl.put(new FullPageId(pageId, grpId), (long)grpId);
+ map.put(grpId, pageId, (long)grpId, 1);
+ }
+ for (FullPageId next : ctrl.keySet()) {
+ assertTrue(map.remove(next.groupId(), next.pageId()));
+ }
+ }, cap);
+ }
+
+ /**
+ * @param grpId Group ID to use
+ * @param id Page to be placed to same bucket with
+ * @param cap map maximum cells.
+ * @return page ID to use in addition to provided {@code grpId} to reach collision.
+ */
+ private int findPageIdForCollision(int grpId, FullPageId id, int cap) {
+ int bucket = U.safeAbs(id.hashCode()) % cap;
+
+ for (int p = 0; p < 1_000_000; p++) {
+ if (U.safeAbs(FullPageId.hashCode(grpId, p)) % cap == bucket)
+ return p;
+ }
+ assertTrue(false);
+ return -1;
+ }
+
+ /**
+ *
+ */
+ @Test
+ public void testRandomOpsPutRemove() {
+ doPutRemoveTest(System.currentTimeMillis());
+ }
+
+ /**
+ * @param seed random seed, use timer to random run.
+ */
+ private void doPutRemoveTest(long seed) {
+ System.setProperty(IGNITE_LONG_LONG_HASH_MAP_LOAD_FACTOR, "11");
+
+ int elementsCnt = 10_000;
+
+ withMap(tbl -> {
+ Random rnd = new Random(seed);
+
+ Map<FullPageId, Long> check = new HashMap<>();
+
+ int tag = 0;
+ for (int i = 0; i < 20_000_000; i++) {
+ int op = rnd.nextInt(5);
+
+ int cacheId = rnd.nextInt(100) + 1;
+ int pageId = rnd.nextInt(100);
+
+ FullPageId fullId = new FullPageId(pageId, cacheId);
+
+ if (op == 0) {
+ long val = tbl.get(cacheId, pageId, tag, -1, -2);
+ if (val == -2)
+ tbl.refresh(cacheId, pageId, tag);
+ else {
+ Long checkVal = check.get(fullId);
+
+ if (checkVal != null) {
+ assertEquals("Ret." +
+ getPageString(fullId) +
+ " tbl: " + val + " Check " + checkVal,
+ checkVal.longValue(), val);
+ }
+ }
+ }
+ else if ((op == 1 || op == 2) && (check.size() < elementsCnt)) {
+ long val = U.safeAbs(rnd.nextInt(30));
+
+ check.put(fullId, val);
+
+ tbl.put(cacheId, pageId, val, tag);
+ }
+ else if ((op == 3) && check.size() >= elementsCnt * 2 / 3) {
+ tbl.remove(cacheId, pageId);
+
+ check.remove(fullId);
+ }
+ else if (check.size() >= elementsCnt * 2 / 3) {
+ ReplaceCandidate ec = tbl.getNearestAt(rnd.nextInt(tbl.capacity()));
+
+ if (ec != null) {
+ FullPageId fullPageId = ec.fullId();
+
+ tbl.remove(fullPageId.groupId(), fullPageId.pageId());
+
+ check.remove(fullPageId);
+ }
+ }
+
+ i++;
+ }
+
+ }, elementsCnt);
+ }
+
+ /**
+ * @param fullId page ID.
+ * @return Printable string for page ID.
+ */
+ @NotNull private String getPageString(FullPageId fullId) {
+ return "(grp=" + fullId.groupId() + "," +
+ "page=" + fullId.pageId() + ")";
+ }
+
+ /**
+ * @throws Exception If failed.
+ */
+ @Test
+ public void testPutAndCantGetOutdatedValue() throws Exception {
+ withMap(map -> {
+ //fill with 1 space left;
+ for (int i = 0; i < 99; i++) {
+ int ver = i;
+ int grpId = ver + 1;
+ int val = grpId * grpId;
+ map.put(grpId, 1, val, ver);
+
+ assertEquals(val, map.get(grpId, 1, ver, -1, -2));
+
+ assertEquals(-2, map.get(grpId, 1, ver + 1, -1, -2));
+ }
+ }, 100);
+ }
+
+ /**
+ * @throws Exception If failed.
+ */
+ @Test
+ public void testPutAndRefreshValue() throws Exception {
+ withMap(map -> {
+ //fill with 1 space left;
+ for (int i = 0; i < 99; i++) {
+ int ver = i;
+ int grpId = ver + 1;
+ int val = grpId * grpId;
+ int pageId = 1;
+ map.put(grpId, pageId, val, ver);
+
+ map.refresh(grpId, pageId, ver + 1);
+
+ assertEquals(val, map.get(grpId, pageId, ver + 1, -1, -2));
+
+ }
+
+ doAddRemove(map);
+ }, 100);
+ }
+
+ /**
+ * @throws Exception If failed.
+ */
+ @Test
+ public void testClearAtWithControlMap3() throws Exception {
+ int cap = 100;
+
+ doRemovalTests(cap, (grpId, pageId) -> {
+ int hc = Integer.hashCode(grpId) + 31 * Long.hashCode(pageId);
+
+ return hc % 3 == 0;
+ });
+ }
+
+ /**
+ * @throws Exception If failed.
+ */
+ @Test
+ public void testClearAtWithControlMap7() throws Exception {
+ int cap = 100;
+
+ doRemovalTests(cap, (grpId, pageId) -> {
+ int hc = Integer.hashCode(grpId) + 31 * Long.hashCode(pageId);
+
+ return hc % 7 == 0;
+ });
+ }
+
+ /**
+ * @throws Exception If failed.
+ */
+ @Test
+ public void testClearAllWithControlMap() throws Exception {
+ int cap = 100;
+
+ doRemovalTests(cap, (grpId, pageId) -> true);
+ }
+
+ /**
+ * @param cap capacity of map
+ * @param pred predicate to filter entries to be removed.
+ */
+ private void doRemovalTests(int cap, LoadedPagesMap.KeyPredicate pred) {
+ withMap(map -> {
+ Map<FullPageId, Long> check = new HashMap<>();
+
+ int elems = cap - 1; //fill with 1 space left;
+ for (int i = 0; i < elems; i++) {
+ int grpId = i + 1;
+ long val = grpId * grpId;
+ int pageId = 1;
+
+ map.put(grpId, pageId, val, i);
+
+ check.put(new FullPageId(pageId, grpId), val);
+ }
+
+ int sz = map.size();
+
+ GridLongList list = map.removeIf(pred);
+ for (int i = 0; i < list.size(); i++) {
+ long val = list.get(i);
+
+ assertTrue(val > 0);
+ }
+
+ assertThat(sz - map.size(), Matchers.is(list.size()));
+
+ Map<FullPageId, Long> res = new HashMap<>();
+
+ map.forEach(res::put);
+
+ assertThat(map.size(), Matchers.is(map.size()));
+
+ for (int i = 0; i < cap; i++) {
+ GridLongList list1 = map.removeIf(i, i + 1, pred);
+
+ assertTrue(list1.isEmpty()); // clear should not be successful.
+ }
+
+ check.keySet().removeIf(entry -> pred.test(entry.groupId(), entry.pageId()));
+
+ MatcherAssert.assertThat(res, Matchers.is(check));
+
+ }, cap);
+ }
+}
http://git-wip-us.apache.org/repos/asf/ignite/blob/1f8ec79d/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePdsUnitTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePdsUnitTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePdsUnitTestSuite.java
index 9906429..c022eea 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePdsUnitTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePdsUnitTestSuite.java
@@ -16,8 +16,10 @@
*/
package org.apache.ignite.testsuites;
+import org.apache.ignite.internal.processors.cache.persistence.pagemem.FullPageIdTableTest;
import org.apache.ignite.internal.processors.cache.persistence.pagemem.IgnitePageMemReplaceDelayedWriteUnitTest;
import org.apache.ignite.internal.processors.cache.persistence.pagemem.IgniteThrottlingUnitTest;
+import org.apache.ignite.internal.processors.cache.persistence.pagemem.RobinHoodBackwardShiftHashMapTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@@ -27,7 +29,10 @@ import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
IgniteThrottlingUnitTest.class,
- IgnitePageMemReplaceDelayedWriteUnitTest.class
+ IgnitePageMemReplaceDelayedWriteUnitTest.class,
+ IgniteThrottlingUnitTest.class,
+ FullPageIdTableTest.class,
+ RobinHoodBackwardShiftHashMapTest.class
})
public class IgnitePdsUnitTestSuite {
}
[2/2] ignite git commit: IGNITE-7638 Implemented robin-hood hashing
for FullPageIdTable - Fixes #3481.
Posted by ag...@apache.org.
IGNITE-7638 Implemented robin-hood hashing for FullPageIdTable - Fixes #3481.
Signed-off-by: Alexey Goncharuk <al...@gmail.com>
Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/1f8ec79d
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/1f8ec79d
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/1f8ec79d
Branch: refs/heads/master
Commit: 1f8ec79d22305fb5a6e28c9c9fa8efa2a2e391bf
Parents: ac3d545
Author: dpavlov <dp...@gridgain.com>
Authored: Tue Mar 13 16:18:54 2018 +0300
Committer: Alexey Goncharuk <al...@gmail.com>
Committed: Tue Mar 13 16:18:54 2018 +0300
----------------------------------------------------------------------
modules/core/pom.xml | 7 +
.../apache/ignite/IgniteSystemProperties.java | 7 +
.../GridCacheDatabaseSharedManager.java | 18 +-
.../pagemem/CheckpointMetricsTracker.java | 2 +-
.../persistence/pagemem/EvictCandidate.java | 77 ---
.../persistence/pagemem/FullPageIdTable.java | 358 +++++-----
.../persistence/pagemem/LoadedPagesMap.java | 137 ++++
.../cache/persistence/pagemem/PageMemoryEx.java | 8 +-
.../persistence/pagemem/PageMemoryImpl.java | 192 +++---
.../persistence/pagemem/ReplaceCandidate.java | 78 +++
.../pagemem/RobinHoodBackwardShiftHashMap.java | 654 +++++++++++++++++++
.../checkpoint/IgniteMassLoadSandboxTest.java | 2 +-
.../pagemem/FullPageIdTableTest.java | 195 +++++-
.../RobinHoodBackwardShiftHashMapTest.java | 430 ++++++++++++
.../testsuites/IgnitePdsUnitTestSuite.java | 7 +-
15 files changed, 1812 insertions(+), 360 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ignite/blob/1f8ec79d/modules/core/pom.xml
----------------------------------------------------------------------
diff --git a/modules/core/pom.xml b/modules/core/pom.xml
index 68c19a7..e56d141 100644
--- a/modules/core/pom.xml
+++ b/modules/core/pom.xml
@@ -124,6 +124,13 @@
</dependency>
<dependency>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ <version>1.3</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
http://git-wip-us.apache.org/repos/asf/ignite/blob/1f8ec79d/modules/core/src/main/java/org/apache/ignite/IgniteSystemProperties.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/IgniteSystemProperties.java b/modules/core/src/main/java/org/apache/ignite/IgniteSystemProperties.java
index b1a1542..11419ec 100644
--- a/modules/core/src/main/java/org/apache/ignite/IgniteSystemProperties.java
+++ b/modules/core/src/main/java/org/apache/ignite/IgniteSystemProperties.java
@@ -815,12 +815,19 @@ public final class IgniteSystemProperties {
* Because other thread may require exactly the same page to be loaded from store, reads are protected by locking.
*/
public static final String IGNITE_DELAYED_REPLACED_PAGE_WRITE = "IGNITE_DELAYED_REPLACED_PAGE_WRITE";
+
/**
* When set to {@code true}, WAL implementation with dedicated worker will be used even in FSYNC mode.
* Default is {@code false}.
*/
public static final String IGNITE_WAL_FSYNC_WITH_DEDICATED_WORKER = "IGNITE_WAL_FSYNC_WITH_DEDICATED_WORKER";
+ /**
+ * When set to {@code false}, loaded pages implementation is switched to previous version of implementation,
+ * FullPageIdTable. {@code True} value enables 'Robin Hood hashing: backward shift deletion'.
+ * Default is {@code true}.
+ */
+ public static final String IGNITE_LOADED_PAGES_BACKWARD_SHIFT_MAP = "IGNITE_LOADED_PAGES_BACKWARD_SHIFT_MAP";
/**
* Enforces singleton.
http://git-wip-us.apache.org/repos/asf/ignite/blob/1f8ec79d/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/GridCacheDatabaseSharedManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/GridCacheDatabaseSharedManager.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/GridCacheDatabaseSharedManager.java
index d4ba4ef..d6a8a30 100755
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/GridCacheDatabaseSharedManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/GridCacheDatabaseSharedManager.java
@@ -113,8 +113,6 @@ import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
import org.apache.ignite.internal.processors.cache.StoredCacheData;
import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtLocalPartition;
import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtPartitionState;
-import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtPartitionTopology;
-import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtPartitionTopologyImpl;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture;
import org.apache.ignite.internal.processors.cache.persistence.file.FileIO;
import org.apache.ignite.internal.processors.cache.persistence.file.FilePageStore;
@@ -141,7 +139,6 @@ import org.apache.ignite.internal.util.lang.GridInClosure3X;
import org.apache.ignite.internal.util.tostring.GridToStringInclude;
import org.apache.ignite.internal.util.typedef.CI1;
import org.apache.ignite.internal.util.typedef.F;
-import org.apache.ignite.internal.util.typedef.P3;
import org.apache.ignite.internal.util.typedef.T2;
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.internal.util.typedef.internal.LT;
@@ -1251,11 +1248,7 @@ public class GridCacheDatabaseSharedManager extends IgniteCacheDatabaseSharedMan
for (Map.Entry<PageMemoryEx, Collection<Integer>> entry : destroyed.entrySet()) {
final Collection<Integer> grpIds = entry.getValue();
- clearFuts.add(entry.getKey().clearAsync(new P3<Integer, Long, Integer>() {
- @Override public boolean apply(Integer grpId, Long pageId, Integer tag) {
- return grpIds.contains(grpId);
- }
- }, false));
+ clearFuts.add(entry.getKey().clearAsync((grpId, pageIdg) -> grpIds.contains(grpId), false));
}
for (IgniteInternalFuture<Void> clearFut : clearFuts) {
@@ -1985,12 +1978,9 @@ public class GridCacheDatabaseSharedManager extends IgniteCacheDatabaseSharedMan
PageMemoryEx pageMem = gId == METASTORAGE_CACHE_ID ? storePageMem : getPageMemoryForCacheGroup(gId);
- pageMem.clearAsync(new P3<Integer, Long, Integer>() {
- @Override public boolean apply(Integer cacheId, Long pageId, Integer tag) {
- return cacheId == gId && PageIdUtils.partId(pageId) == pId;
- }
- }, true).get();
-
+ pageMem.clearAsync(
+ (grpId, pageId) -> grpId == gId && PageIdUtils.partId(pageId) == pId,
+ true).get();
}
break;
http://git-wip-us.apache.org/repos/asf/ignite/blob/1f8ec79d/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/CheckpointMetricsTracker.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/CheckpointMetricsTracker.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/CheckpointMetricsTracker.java
index e533f41..dbe0f40 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/CheckpointMetricsTracker.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/CheckpointMetricsTracker.java
@@ -70,7 +70,7 @@ public class CheckpointMetricsTracker {
private long cpEnd;
/**
- *
+ * Increments counter if copy on write page was written.
*/
public void onCowPageWritten() {
COW_PAGES_UPDATER.incrementAndGet(this);
http://git-wip-us.apache.org/repos/asf/ignite/blob/1f8ec79d/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/EvictCandidate.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/EvictCandidate.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/EvictCandidate.java
deleted file mode 100644
index eb172c9..0000000
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/EvictCandidate.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * 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.ignite.internal.processors.cache.persistence.pagemem;
-
-import org.apache.ignite.internal.pagemem.FullPageId;
-import org.apache.ignite.internal.util.tostring.GridToStringExclude;
-import org.apache.ignite.internal.util.tostring.GridToStringInclude;
-import org.apache.ignite.internal.util.typedef.internal.S;
-import org.apache.ignite.internal.util.typedef.internal.U;
-
-/**
- *
- */
-public class EvictCandidate {
- /** */
- private int tag;
-
- /** */
- @GridToStringExclude
- private long relPtr;
-
- /** */
- @GridToStringInclude
- private FullPageId fullId;
-
- /**
- * @param tag Tag.
- * @param relPtr Relative pointer.
- * @param fullId Full page ID.
- */
- public EvictCandidate(int tag, long relPtr, FullPageId fullId) {
- this.tag = tag;
- this.relPtr = relPtr;
- this.fullId = fullId;
- }
-
- /**
- * @return Tag.
- */
- public int tag() {
- return tag;
- }
-
- /**
- * @return Relative pointer.
- */
- public long relativePointer() {
- return relPtr;
- }
-
- /**
- * @return Index.
- */
- public FullPageId fullId() {
- return fullId;
- }
-
- /** {@inheritDoc} */
- @Override public String toString() {
- return S.toString(EvictCandidate.class, this, "relPtr", U.hexLong(relPtr));
- }
-}
http://git-wip-us.apache.org/repos/asf/ignite/blob/1f8ec79d/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/FullPageIdTable.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/FullPageIdTable.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/FullPageIdTable.java
index 19d26ff..7fabfe0 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/FullPageIdTable.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/FullPageIdTable.java
@@ -17,13 +17,14 @@
package org.apache.ignite.internal.processors.cache.persistence.pagemem;
+import java.util.function.BiConsumer;
import org.apache.ignite.internal.mem.IgniteOutOfMemoryException;
import org.apache.ignite.internal.pagemem.FullPageId;
import org.apache.ignite.internal.pagemem.PageIdUtils;
+import org.apache.ignite.internal.util.GridLongList;
import org.apache.ignite.internal.util.GridUnsafe;
-import org.apache.ignite.internal.util.lang.GridPredicate3;
+import org.apache.ignite.internal.util.typedef.internal.A;
import org.apache.ignite.internal.util.typedef.internal.U;
-import org.apache.ignite.lang.IgniteBiInClosure;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_LONG_LONG_HASH_MAP_LOAD_FACTOR;
import static org.apache.ignite.IgniteSystemProperties.getFloat;
@@ -31,7 +32,7 @@ import static org.apache.ignite.IgniteSystemProperties.getFloat;
/**
*
*/
-public class FullPageIdTable {
+public class FullPageIdTable implements LoadedPagesMap {
/** Load factor. */
private static final float LOAD_FACTOR = getFloat(IGNITE_LONG_LONG_HASH_MAP_LOAD_FACTOR, 2.5f);
@@ -68,6 +69,15 @@ public class FullPageIdTable {
/** */
private static final int OUTDATED = -3;
+ /** Tag offset from entry base. */
+ private static final int TAG_OFFSET = 4;
+
+ /** Page id offset from entry base. */
+ private static final int PAGE_ID_OFFSET = 8;
+
+ /** Value offset from entry base. */
+ private static final int VALUE_OFFSET = 16;
+
/** Max size, in elements. */
protected int capacity;
@@ -102,31 +112,21 @@ public class FullPageIdTable {
clear();
}
- /**
- * @return Current number of entries in the map.
- */
- public final int size() {
+ /** {@inheritDoc} */
+ @Override public final int size() {
return GridUnsafe.getInt(valPtr);
}
- /**
- * @return Maximum number of entries in the map. This maximum can not be always reached.
- */
- public final int capacity() {
+ /** {@inheritDoc} */
+ @Override public final int capacity() {
return capacity;
}
- /**
- * Gets value associated with the given key.
- *
- * @param cacheId Cache ID.
- * @param pageId Page ID.
- * @return A value associated with the given key.
- */
- public long get(int cacheId, long pageId, int tag, long absent, long outdated) {
- assert assertKey(cacheId, pageId);
+ /** {@inheritDoc} */
+ @Override public long get(int grpId, long pageId, int reqVer, long absent, long outdated) {
+ assert assertKey(grpId, pageId);
- int idx = getKey(cacheId, pageId, tag, false);
+ int idx = getKey(grpId, pageId, reqVer, false);
if (idx == -1)
return absent;
@@ -137,112 +137,97 @@ public class FullPageIdTable {
return valueAt(idx);
}
- /**
- * Refresh outdated value.
- *
- * @param cacheId Cache ID.
- * @param pageId Page ID.
- * @param tag Partition tag.
- * @return A value associated with the given key.
- */
- public long refresh(int cacheId, long pageId, int tag) {
- assert assertKey(cacheId, pageId);
+ /** {@inheritDoc} */
+ @Override public long refresh(int grpId, long pageId, int ver) {
+ assert assertKey(grpId, pageId);
- int idx = getKey(cacheId, pageId, tag, true);
+ int idx = getKey(grpId, pageId, ver, true);
- assert idx >= 0 : "[idx=" + idx + ", tag=" + tag + ", cacheId=" + cacheId +
- ", pageId=" + U.hexLong(pageId) + ']';
+ if (!(idx >= 0) || !(tagAt(idx) < ver)) {
+ A.ensure(idx >= 0, "[idx=" + idx + ", tag=" + ver + ", cacheId=" + grpId +
+ ", pageId=" + U.hexLong(pageId) + ']');
- assert tagAt(idx) < tag : "[idx=" + idx + ", tag=" + tag + ", cacheId=" + cacheId +
- ", pageId=" + U.hexLong(pageId) + ", tagAtIdx=" + tagAt(idx) + ']';
+ A.ensure(tagAt(idx) < ver, "[idx=" + idx + ", tag=" + ver + ", cacheId=" + grpId +
+ ", pageId=" + U.hexLong(pageId) + ", tagAtIdx=" + tagAt(idx) + ']');
+ }
- setTagAt(idx, tag);
+ setTagAt(idx, ver);
return valueAt(idx);
}
- /**
- * Associates the given key with the given value.
- * @param cacheId Cache ID
- * @param pageId Page ID.
- * @param value Value to set.
- */
- public void put(int cacheId, long pageId, long value, int tag) {
- assert assertKey(cacheId, pageId);
+ /** {@inheritDoc} */
+ @Override public void put(int grpId, long pageId, long val, int ver) {
+ assert assertKey(grpId, pageId);
- int index = putKey(cacheId, pageId, tag);
+ int idx = putKey(grpId, pageId, ver);
- setValueAt(index, value);
+ setValueAt(idx, val);
}
- /**
- * Removes key-value association for the given key.
- *
- * @param grpId Cache group ID.
- * @param pageId Page ID.
- */
- public void remove(int grpId, long pageId, int tag) {
+ /** {@inheritDoc} */
+ @Override public boolean remove(int grpId, long pageId) {
assert assertKey(grpId, pageId);
- int index = removeKey(grpId, pageId, tag);
+ int idx = removeKey(grpId, pageId);
+
+ boolean valRmv = idx >= 0;
+
+ if (valRmv)
+ setValueAt(idx, 0);
- if (index >= 0)
- setValueAt(index, 0);
+ return valRmv;
}
- /**
- * Find nearest value from specified position to the right.
- *
- * @param idx Index to start searching from.
- * @param absent Default value that will be returned if no values present.
- * @return Closest value to the index and it's partition tag or {@code absent} and -1 if no values found.
- */
- public EvictCandidate getNearestAt(final int idx, final long absent) {
- for (int i = idx; i < capacity + idx; i++) {
- final int idx2 = i >= capacity ? i - capacity : i;
+ /** {@inheritDoc} */
+ @Override public ReplaceCandidate getNearestAt(final int idxStart) {
+ for (int i = idxStart; i < capacity + idxStart; i++) {
+ final int idx2 = normalizeIndex(i);
if (isValuePresentAt(idx2)) {
long base = entryBase(idx2);
- int cacheId = GridUnsafe.getInt(base);
- int tag = GridUnsafe.getInt(base + 4);
- long pageId = GridUnsafe.getLong(base + 8);
- long val = GridUnsafe.getLong(base + 16);
+ int grpId = GridUnsafe.getInt(base);
+ int tag = GridUnsafe.getInt(base + TAG_OFFSET);
+ long pageId = GridUnsafe.getLong(base + PAGE_ID_OFFSET);
+ long val = GridUnsafe.getLong(base + VALUE_OFFSET);
- return new EvictCandidate(tag, val, new FullPageId(pageId, cacheId));
+ return new ReplaceCandidate(tag, val, new FullPageId(pageId, grpId));
}
}
return null;
}
- /**
- * @param idx Index to clear value at.
- * @param pred Test predicate.
- * @param absent Value to return if the cell is empty.
- * @return Value at the given index.
- */
- public long clearAt(int idx, GridPredicate3<Integer, Long, Integer> pred, long absent) {
- long base = entryBase(idx);
+ /** {@inheritDoc} */
+ @Override public GridLongList removeIf(int startIdxToClear, int endIdxToClear, KeyPredicate keyPred) {
+ assert endIdxToClear > startIdxToClear
+ : "Start and end indexes are not consistent: {" + startIdxToClear + ", " + endIdxToClear + "}";
- int grpId = GridUnsafe.getInt(base);
- int tag = GridUnsafe.getInt(base + 4);
- long pageId = GridUnsafe.getLong(base + 8);
+ int sz = endIdxToClear - startIdxToClear;
- if ((pageId == REMOVED_PAGE_ID && grpId == REMOVED_CACHE_GRP_ID)
- || (pageId == EMPTY_PAGE_ID && grpId == EMPTY_CACHE_GRP_ID))
- return absent;
+ GridLongList list = new GridLongList(sz);
+
+ for (int idx = startIdxToClear; idx < endIdxToClear; idx++) {
+ long base = entryBase(idx);
+
+ int grpId = GridUnsafe.getInt(base);
+ long pageId = GridUnsafe.getLong(base + PAGE_ID_OFFSET);
+
+ if (isRemoved(grpId, pageId) || isEmpty(grpId, pageId))
+ continue;
+
+ if (!keyPred.test(grpId, pageId))
+ continue;
- if (pred.apply(grpId, pageId, tag)) {
long res = valueAt(idx);
- setKeyAt(idx, REMOVED_CACHE_GRP_ID, REMOVED_PAGE_ID);
- setValueAt(idx, 0);
+ setRemoved(idx);
- return res;
+ list.add(res);
}
- else
- return absent;
+
+ return list;
}
/**
@@ -253,50 +238,50 @@ public class FullPageIdTable {
private int putKey(int cacheId, long pageId, int tag) {
int step = 1;
- int index = U.safeAbs(FullPageId.hashCode(cacheId, pageId)) % capacity;
+ int idx = U.safeAbs(FullPageId.hashCode(cacheId, pageId)) % capacity;
- int foundIndex = -1;
+ int foundIdx = -1;
int res;
do {
- res = testKeyAt(index, cacheId, pageId, tag);
+ res = testKeyAt(idx, cacheId, pageId, tag);
if (res == OUTDATED) {
- foundIndex = index;
+ foundIdx = idx;
break;
}
else if (res == EMPTY) {
- if (foundIndex == -1)
- foundIndex = index;
+ if (foundIdx == -1)
+ foundIdx = idx;
break;
}
else if (res == REMOVED) {
// Must continue search to the first empty slot to ensure there are no duplicate mappings.
- if (foundIndex == -1)
- foundIndex = index;
+ if (foundIdx == -1)
+ foundIdx = idx;
}
else if (res == EQUAL)
- return index;
+ return idx;
else
assert res == NOT_EQUAL;
- index++;
+ idx++;
- if (index >= capacity)
- index -= capacity;
+ if (idx >= capacity)
+ idx -= capacity;
}
while (++step <= maxSteps);
- if (foundIndex != -1) {
- setKeyAt(foundIndex, cacheId, pageId);
- setTagAt(foundIndex, tag);
+ if (foundIdx != -1) {
+ setKeyAt(foundIdx, cacheId, pageId);
+ setTagAt(foundIdx, tag);
if (res != OUTDATED)
incrementSize();
- return foundIndex;
+ return foundIdx;
}
throw new IgniteOutOfMemoryException("No room for a new key");
@@ -305,6 +290,7 @@ public class FullPageIdTable {
/**
* @param cacheId Cache ID.
* @param pageId Page ID.
+ * @param refresh Refresh.
* @return Key index.
*/
private int getKey(int cacheId, long pageId, int tag, boolean refresh) {
@@ -335,22 +321,97 @@ public class FullPageIdTable {
}
/**
+ * @param grpId Cache group ID.
+ * @param pageId Page ID.
+ * @return {@code true} if group & page id indicates cell has state 'Removed'.
+ */
+ private boolean isRemoved(int grpId, long pageId) {
+ return pageId == REMOVED_PAGE_ID && grpId == REMOVED_CACHE_GRP_ID;
+ }
+
+ /**
+ * @param idx cell index, normalized.
+ * @return {@code true} if cell with index idx has state 'Empty'.
+ */
+ private boolean isRemoved(int idx) {
+ long base = entryBase(idx);
+
+ int grpId = GridUnsafe.getInt(base);
+ long pageId = GridUnsafe.getLong(base + PAGE_ID_OFFSET);
+
+ return isRemoved(grpId, pageId);
+ }
+
+ /**
+ * Sets cell state to 'Removed' or to 'Empty' if next cell is already 'Empty'.
+ * @param idx cell index, normalized.
+ */
+ private void setRemoved(int idx) {
+ setKeyAt(idx, REMOVED_CACHE_GRP_ID, REMOVED_PAGE_ID);
+
+ setValueAt(idx, 0);
+ }
+
+ /**
+ * @param grpId Cache group ID.
+ * @param pageId Page ID.
+ * @return {@code true} if group & page id indicates cell has state 'Empty'.
+ */
+ private boolean isEmpty(int grpId, long pageId) {
+ return pageId == EMPTY_PAGE_ID && grpId == EMPTY_CACHE_GRP_ID;
+ }
+
+ /**
+ * @param idx cell index, normalized.
+ * @return {@code true} if cell with index idx has state 'Empty'.
+ */
+ private boolean isEmpty(int idx) {
+ long base = entryBase(idx);
+
+ int grpId = GridUnsafe.getInt(base);
+ long pageId = GridUnsafe.getLong(base + PAGE_ID_OFFSET);
+
+ return isEmpty(grpId, pageId);
+ }
+
+ /**
+ * Sets cell state to 'Empty'.
+ *
+ * @param idx cell index, normalized.
+ */
+ private void setEmpty(int idx) {
+ setKeyAt(idx, EMPTY_CACHE_GRP_ID, EMPTY_PAGE_ID);
+
+ setValueAt(idx, 0);
+ }
+
+ /**
+ * @param i index probably outsize internal array of cells.
+ * @return corresponding index inside cells array.
+ */
+ private int normalizeIndex(int i) {
+ assert i < 2 * capacity;
+
+ return i < capacity ? i : i - capacity;
+ }
+
+ /**
* @param cacheId Cache ID.
* @param pageId Page ID.
* @return Key index.
*/
- private int removeKey(int cacheId, long pageId, int tag) {
+ private int removeKey(int cacheId, long pageId) {
int step = 1;
- int index = U.safeAbs(FullPageId.hashCode(cacheId, pageId)) % capacity;
+ int idx = U.safeAbs(FullPageId.hashCode(cacheId, pageId)) % capacity;
- int foundIndex = -1;
+ int foundIdx = -1;
do {
- long res = testKeyAt(index, cacheId, pageId, tag);
+ long res = testKeyAt(idx, cacheId, pageId, -1);
if (res == EQUAL || res == OUTDATED) {
- foundIndex = index;
+ foundIdx = idx;
break;
}
@@ -359,20 +420,20 @@ public class FullPageIdTable {
else
assert res == REMOVED || res == NOT_EQUAL;
- index++;
+ idx++;
- if (index >= capacity)
- index -= capacity;
+ if (idx >= capacity)
+ idx -= capacity;
}
while (++step <= maxSteps);
- if (foundIndex != -1) {
- setKeyAt(foundIndex, REMOVED_CACHE_GRP_ID, REMOVED_PAGE_ID);
+ if (foundIdx != -1) {
+ setRemoved(foundIdx);
decrementSize();
}
- return foundIndex;
+ return foundIdx;
}
/**
@@ -383,16 +444,16 @@ public class FullPageIdTable {
long base = entryBase(index);
int grpId = GridUnsafe.getInt(base);
- int tag = GridUnsafe.getInt(base + 4);
- long pageId = GridUnsafe.getLong(base + 8);
+ int tag = GridUnsafe.getInt(base + TAG_OFFSET);
+ long pageId = GridUnsafe.getLong(base + PAGE_ID_OFFSET);
- if (pageId == REMOVED_PAGE_ID && grpId == REMOVED_CACHE_GRP_ID)
+ if (isRemoved(grpId, pageId))
return REMOVED;
else if (pageId == testPageId && grpId == testCacheId && tag >= testTag)
return EQUAL;
else if (pageId == testPageId && grpId == testCacheId && tag < testTag)
return OUTDATED;
- else if (pageId == EMPTY_PAGE_ID && grpId == EMPTY_CACHE_GRP_ID)
+ else if (isEmpty(grpId, pageId))
return EMPTY;
else
return NOT_EQUAL;
@@ -406,10 +467,9 @@ public class FullPageIdTable {
long base = entryBase(idx);
int grpId = GridUnsafe.getInt(base);
- long pageId = GridUnsafe.getLong(base + 8);
+ long pageId = GridUnsafe.getLong(base + PAGE_ID_OFFSET);
- return !((pageId == REMOVED_PAGE_ID && grpId == REMOVED_CACHE_GRP_ID)
- || (pageId == EMPTY_PAGE_ID && grpId == EMPTY_CACHE_GRP_ID));
+ return !isRemoved(grpId, pageId) && !isEmpty(grpId, pageId);
}
/**
@@ -425,15 +485,15 @@ public class FullPageIdTable {
}
/**
- * @param index Entry index.
+ * @param idx Entry index.
* @param grpId Cache group ID to write.
* @param pageId Page ID to write.
*/
- private void setKeyAt(int index, int grpId, long pageId) {
- long base = entryBase(index);
+ private void setKeyAt(int idx, int grpId, long pageId) {
+ long base = entryBase(idx);
GridUnsafe.putInt(base, grpId);
- GridUnsafe.putLong(base + 8, pageId);
+ GridUnsafe.putLong(base + PAGE_ID_OFFSET, pageId);
}
/**
@@ -478,21 +538,17 @@ public class FullPageIdTable {
return found ? scans : -scans;
}
- /**
- * Scans all the elements in this table.
- *
- * @param visitor Visitor.
- */
- public void visitAll(IgniteBiInClosure<FullPageId, Long> visitor) {
+ /** {@inheritDoc} */
+ @Override public void forEach(BiConsumer<FullPageId, Long> act) {
for (int i = 0; i < capacity; i++) {
if (isValuePresentAt(i)) {
long base = entryBase(i);
int cacheId = GridUnsafe.getInt(base);
- long pageId = GridUnsafe.getLong(base + 8);
- long val = GridUnsafe.getLong(base + 16);
+ long pageId = GridUnsafe.getLong(base + PAGE_ID_OFFSET);
+ long val = GridUnsafe.getLong(base + VALUE_OFFSET);
- visitor.apply(new FullPageId(pageId, cacheId), val);
+ act.accept(new FullPageId(pageId, cacheId), val);
}
}
}
@@ -502,7 +558,7 @@ public class FullPageIdTable {
* @return Value.
*/
private long valueAt(int index) {
- return GridUnsafe.getLong(entryBase(index) + 16);
+ return GridUnsafe.getLong(entryBase(index) + VALUE_OFFSET);
}
/**
@@ -510,27 +566,31 @@ public class FullPageIdTable {
* @param value Value.
*/
private void setValueAt(int index, long value) {
- GridUnsafe.putLong(entryBase(index) + 16, value);
+ GridUnsafe.putLong(entryBase(index) + VALUE_OFFSET, value);
}
- private long entryBase(int index) {
- return valPtr + 8 + (long)index * BYTES_PER_ENTRY;
+ /**
+ * @param idx Entry index.
+ * @return address of entry.
+ */
+ private long entryBase(int idx) {
+ return valPtr + 8 + (long)idx * BYTES_PER_ENTRY;
}
/**
- * @param index Index to get tag for.
+ * @param idx Index to get tag for.
* @return Tag at the given index.
*/
- private int tagAt(int index) {
- return GridUnsafe.getInt(entryBase(index) + 4);
+ private int tagAt(int idx) {
+ return GridUnsafe.getInt(entryBase(idx) + TAG_OFFSET);
}
/**
- * @param index Index to set tag for.
+ * @param idx Index to set tag for.
* @param tag Tag to set at the given index.
*/
- private void setTagAt(int index, int tag) {
- GridUnsafe.putInt(entryBase(index) + 4, tag);
+ private void setTagAt(int idx, int tag) {
+ GridUnsafe.putInt(entryBase(idx) + TAG_OFFSET, tag);
}
/**
http://git-wip-us.apache.org/repos/asf/ignite/blob/1f8ec79d/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/LoadedPagesMap.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/LoadedPagesMap.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/LoadedPagesMap.java
new file mode 100644
index 0000000..1b23238
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/LoadedPagesMap.java
@@ -0,0 +1,137 @@
+/*
+ * 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.ignite.internal.processors.cache.persistence.pagemem;
+
+import java.util.function.BiConsumer;
+import org.apache.ignite.internal.pagemem.FullPageId;
+import org.apache.ignite.internal.util.GridLongList;
+
+/**
+ * Interface for storing correspondence of page ID in a cache group to long value (address in offheap segment). <br>
+ * Map support versioning of entries. Outdated entry (entry having version lower than requested),
+ * is not provided in case of get, outdated return value is provided instead.<br>
+ *
+ * This mapping is not thread safe. Operations should be protected by outside locking.<br>
+ */
+public interface LoadedPagesMap {
+ /**
+ * Gets value associated with the given key.
+ *
+ * @param grpId Cache Group ID. First part of the key.
+ * @param pageId Page ID. Second part of the key.
+ * @param reqVer Requested entry version, counter associated with value.
+ * @param absent return if provided page is not presented in map.
+ * @param outdated return if provided {@code reqVer} version is greater than value in map (was used for put).
+ * @return A value associated with the given key.
+ */
+ public long get(int grpId, long pageId, int reqVer, long absent, long outdated);
+
+ /**
+ * Associates the given key with the given value.
+ *
+ * @param grpId Cache Group ID. First part of the key.
+ * @param pageId Page ID. Second part of the key.
+ * @param val Value to set.
+ * @param ver Version/counter associated with value, can be used to check if value is outdated.
+ */
+ public void put(int grpId, long pageId, long val, int ver);
+
+ /**
+ * Refresh outdated value. Sets provided version to value associated with cache and page.
+ * Method should be called only for key present and only if version was outdated.
+ * Method may be called in case {@link #get(int, long, int, long, long)} returned {@code outdated} return value.
+ *
+ * @param grpId First part of the key. Cache Group ID.
+ * @param pageId Second part of the key. Page ID.
+ * @param ver Partition tag.
+ * @return A value associated with the given key.
+ * @throws IllegalArgumentException if method is called for absent key or key with fresh version.
+ */
+ public long refresh(int grpId, long pageId, int ver);
+
+ /**
+ * Removes key-value association for the given key.
+ * @param grpId First part of the key. Cache Group ID.
+ * @param pageId Second part of the key. Page ID.
+ * @return {@code True} if value was actually found and removed.
+ */
+ public boolean remove(int grpId, long pageId);
+
+ /**
+ * @return Maximum number of entries in the map. This maximum can not be always reached.
+ */
+ public int capacity();
+
+ /**
+ * @return Current number of entries in the map.
+ */
+ public int size();
+
+ /**
+ * Find nearest presented value from specified position to the right.
+ *
+ * @param idxStart Index to start searching from. Bounded with {@link #capacity()}.
+ * @return Closest value to the index and it's partition tag or {@code null} value that will
+ * be returned if no values present.
+ */
+ public ReplaceCandidate getNearestAt(int idxStart);
+
+
+ /**
+ * Removes entities matching provided predicate at specified mapping range.
+ *
+ * @param startIdxToClear Index to clear value at, inclusive. Bounded with {@link #capacity()}.
+ * @param endIdxToClear Index to clear value at, inclusive. Bounded with {@link #capacity()}.
+ * @param keyPred Test predicate for (cache group ID, page ID).
+ * @return List with removed values, value is not added to list for empty cell or if key is not matching to
+ * predicate.
+ */
+ public GridLongList removeIf(int startIdxToClear, int endIdxToClear, KeyPredicate keyPred);
+
+
+ /**
+ * Removes entities matching provided predicate.
+ *
+ * @param keyPred Test predicate for (cache group ID, page ID).
+ * @return List with removed values, value is not added to list for empty cell or if key is not matching to
+ * predicate.
+ */
+ default GridLongList removeIf(KeyPredicate keyPred) {
+ return removeIf(0, capacity(), keyPred);
+ }
+
+ /**
+ * Scans all the elements in this table.
+ *
+ * @param act Visitor/action to be applied to each not empty cell.
+ */
+ public void forEach(BiConsumer<FullPageId, Long> act);
+
+ /**
+ * Interface describing a predicate for Key (cache group ID, page ID). Usage of this predicate prevents odd object
+ * creation.
+ */
+ @FunctionalInterface public interface KeyPredicate {
+ /**
+ * Predicate body.
+ *
+ * @param grpId Cache group ID.
+ * @param pageId Page ID.
+ */
+ boolean test(int grpId, long pageId);
+ }
+}
http://git-wip-us.apache.org/repos/asf/ignite/blob/1f8ec79d/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/PageMemoryEx.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/PageMemoryEx.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/PageMemoryEx.java
index 9c37508..e889fc5 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/PageMemoryEx.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/PageMemoryEx.java
@@ -117,7 +117,7 @@ public interface PageMemoryEx extends PageMemory {
* the {@link #beginCheckpoint()} method call.
* @param outBuf Temporary buffer to write changes into.
* @param tracker Checkpoint metrics tracker.
- * @return {@code Partition tag} if data was read, {@code null} otherwise (data already saved to storage).
+ * @return {@code Partition generation} if data was read, {@code null} otherwise (data already saved to storage).
* @throws IgniteException If failed to obtain page data.
*/
@Nullable public Integer getForCheckpoint(FullPageId pageId, ByteBuffer outBuf, CheckpointMetricsTracker tracker);
@@ -127,7 +127,7 @@ public interface PageMemoryEx extends PageMemory {
*
* @param grpId Group ID.
* @param partId Partition ID.
- * @return New partition tag (growing 1-based partition file version).
+ * @return New partition generation (growing 1-based partition file version).
*/
public int invalidate(int grpId, int partId);
@@ -141,9 +141,9 @@ public interface PageMemoryEx extends PageMemory {
/**
* Asynchronously clears pages satisfying the given predicate.
*
- * @param pred Predicate for cache group id, pageId and partition tag.
+ * @param pred Predicate for cache group id, pageId.
* @param cleanDirty Flag indicating that dirty pages collection should be cleaned.
* @return Future that will be completed when all pages are cleared.
*/
- public IgniteInternalFuture<Void> clearAsync(GridPredicate3<Integer, Long, Integer> pred, boolean cleanDirty);
+ public IgniteInternalFuture<Void> clearAsync(LoadedPagesMap.KeyPredicate pred, boolean cleanDirty);
}
http://git-wip-us.apache.org/repos/asf/ignite/blob/1f8ec79d/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/PageMemoryImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/PageMemoryImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/PageMemoryImpl.java
index 27c9b38..fa10a1f 100755
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/PageMemoryImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/PageMemoryImpl.java
@@ -23,7 +23,6 @@ import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -38,6 +37,7 @@ import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteException;
import org.apache.ignite.IgniteLogger;
+import org.apache.ignite.IgniteSystemProperties;
import org.apache.ignite.configuration.DataRegionConfiguration;
import org.apache.ignite.configuration.DataStorageConfiguration;
import org.apache.ignite.internal.IgniteInternalFuture;
@@ -62,6 +62,7 @@ import org.apache.ignite.internal.processors.cache.persistence.CheckpointLockSta
import org.apache.ignite.internal.processors.cache.persistence.CheckpointWriteProgressSupplier;
import org.apache.ignite.internal.processors.cache.persistence.DataRegionMetricsImpl;
import org.apache.ignite.internal.processors.cache.persistence.freelist.io.PagesListMetaIO;
+import org.apache.ignite.internal.processors.cache.persistence.partstate.GroupPartitionId;
import org.apache.ignite.internal.processors.cache.persistence.tree.io.DataPageIO;
import org.apache.ignite.internal.processors.cache.persistence.tree.io.PageIO;
import org.apache.ignite.internal.processors.cache.persistence.tree.io.PagePartitionCountersIO;
@@ -76,9 +77,7 @@ import org.apache.ignite.internal.util.GridUnsafe;
import org.apache.ignite.internal.util.OffheapReadWriteLock;
import org.apache.ignite.internal.util.future.CountDownFuture;
import org.apache.ignite.internal.util.lang.GridInClosure3X;
-import org.apache.ignite.internal.util.lang.GridPredicate3;
import org.apache.ignite.internal.util.offheap.GridOffHeapOutOfMemoryException;
-import org.apache.ignite.internal.util.typedef.T2;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteBiTuple;
import org.jetbrains.annotations.Nullable;
@@ -157,7 +156,7 @@ public class PageMemoryImpl implements PageMemoryEx {
/** Page lock offset. */
public static final int PAGE_LOCK_OFFSET = 32;
- /** Page lock offset. */
+ /** Page temp copy buffer relative pointer offset. */
public static final int PAGE_TMP_BUF_OFFSET = 40;
/**
@@ -189,6 +188,10 @@ public class PageMemoryImpl implements PageMemoryEx {
/** Number of used pages in checkpoint buffer. */
private final AtomicInteger cpBufPagesCntr = new AtomicInteger(0);
+ /** Use new implementation of loaded pages table: 'Robin Hood hashing: backward shift deletion'. */
+ private final boolean useBackwardShiftMap
+ = IgniteSystemProperties.getBoolean(IgniteSystemProperties.IGNITE_LOADED_PAGES_BACKWARD_SHIFT_MAP, true);
+
/** */
private ExecutorService asyncRunner = new ThreadPoolExecutor(
0,
@@ -483,7 +486,7 @@ public class PageMemoryImpl implements PageMemoryEx {
long relPtr = seg.loadedPages.get(
cacheId,
PageIdUtils.effectivePageId(pageId),
- seg.partTag(cacheId, partId),
+ seg.partGeneration(cacheId, partId),
INVALID_REL_PTR,
OUTDATED_REL_PTR
);
@@ -536,7 +539,7 @@ public class PageMemoryImpl implements PageMemoryEx {
}
}
- seg.loadedPages.put(cacheId, PageIdUtils.effectivePageId(pageId), relPtr, seg.partTag(cacheId, partId));
+ seg.loadedPages.put(cacheId, PageIdUtils.effectivePageId(pageId), relPtr, seg.partGeneration(cacheId, partId));
}
catch (IgniteOutOfMemoryException oom) {
DataRegionConfiguration dataRegionCfg = getDataRegionConfiguration();
@@ -628,7 +631,7 @@ public class PageMemoryImpl implements PageMemoryEx {
long relPtr = seg.loadedPages.get(
cacheId,
PageIdUtils.effectivePageId(pageId),
- seg.partTag(cacheId, partId),
+ seg.partGeneration(cacheId, partId),
INVALID_REL_PTR,
INVALID_REL_PTR
);
@@ -659,7 +662,7 @@ public class PageMemoryImpl implements PageMemoryEx {
long relPtr = seg.loadedPages.get(
cacheId,
PageIdUtils.effectivePageId(pageId),
- seg.partTag(cacheId, partId),
+ seg.partGeneration(cacheId, partId),
INVALID_REL_PTR,
OUTDATED_REL_PTR
);
@@ -688,7 +691,7 @@ public class PageMemoryImpl implements PageMemoryEx {
cacheId,
PageIdUtils.effectivePageId(pageId),
relPtr,
- seg.partTag(cacheId, partId)
+ seg.partGeneration(cacheId, partId)
);
long pageAddr = absPtr + PAGE_OVERHEAD;
@@ -788,7 +791,7 @@ public class PageMemoryImpl implements PageMemoryEx {
private long refreshOutdatedPage(Segment seg, int cacheId, long pageId, boolean rmv) {
assert seg.writeLock().isHeldByCurrentThread();
- int tag = seg.partTag(cacheId, PageIdUtils.partId(pageId));
+ int tag = seg.partGeneration(cacheId, PageIdUtils.partId(pageId));
long relPtr = seg.loadedPages.refresh(cacheId, PageIdUtils.effectivePageId(pageId), tag);
@@ -812,7 +815,7 @@ public class PageMemoryImpl implements PageMemoryEx {
}
if (rmv)
- seg.loadedPages.remove(cacheId, PageIdUtils.effectivePageId(pageId), tag);
+ seg.loadedPages.remove(cacheId, PageIdUtils.effectivePageId(pageId));
if (seg.segCheckpointPages != null)
seg.segCheckpointPages.remove(new FullPageId(pageId, cacheId));
@@ -1026,7 +1029,7 @@ public class PageMemoryImpl implements PageMemoryEx {
int tag;
- boolean tmpBuffer = false;
+ boolean pageSingleAcquire = false;
seg.readLock().lock();
@@ -1034,7 +1037,7 @@ public class PageMemoryImpl implements PageMemoryEx {
if (!isInCheckpoint(fullId))
return null;
- tag = seg.partTag(fullId.groupId(), PageIdUtils.partId(fullId.pageId()));
+ tag = seg.partGeneration(fullId.groupId(), PageIdUtils.partId(fullId.pageId()));
relPtr = seg.loadedPages.get(
fullId.groupId(),
@@ -1055,7 +1058,7 @@ public class PageMemoryImpl implements PageMemoryEx {
if (PageHeader.tempBufferPointer(absPtr) == INVALID_REL_PTR)
PageHeader.acquirePage(absPtr);
else
- tmpBuffer = true;
+ pageSingleAcquire = true;
}
}
finally {
@@ -1070,7 +1073,7 @@ public class PageMemoryImpl implements PageMemoryEx {
relPtr = seg.loadedPages.get(
fullId.groupId(),
PageIdUtils.effectivePageId(fullId.pageId()),
- seg.partTag(
+ seg.partGeneration(
fullId.groupId(),
PageIdUtils.partId(fullId.pageId())
),
@@ -1099,19 +1102,22 @@ public class PageMemoryImpl implements PageMemoryEx {
}
}
else
- return copyPageForCheckpoint(absPtr, fullId, outBuf, tmpBuffer, tracker) ? tag : null;
+ return copyPageForCheckpoint(absPtr, fullId, outBuf, pageSingleAcquire, tracker) ? tag : null;
}
/**
* @param absPtr Absolute ptr.
* @param fullId Full id.
- * @param tmpBuf Tmp buffer.
+ * @param outBuf Output buffer to write page content into.
+ * @param pageSingleAcquire Page is acquired only once. We don't pin the page second time (until page will not be
+ * copied) in case checkpoint temporary buffer is used.
+ * @param tracker Checkpoint statistics tracker.
*/
private boolean copyPageForCheckpoint(
long absPtr,
FullPageId fullId,
- ByteBuffer tmpBuf,
- boolean tmpBuffer,
+ ByteBuffer outBuf,
+ boolean pageSingleAcquire,
CheckpointMetricsTracker tracker
) {
assert absPtr != 0;
@@ -1131,7 +1137,7 @@ public class PageMemoryImpl implements PageMemoryEx {
long tmpAbsPtr = checkpointPool.absolute(tmpRelPtr);
- copyInBuffer(tmpAbsPtr, tmpBuf);
+ copyInBuffer(tmpAbsPtr, outBuf);
GridUnsafe.setMemory(tmpAbsPtr + PAGE_OVERHEAD, pageSize(), (byte)0);
@@ -1145,12 +1151,12 @@ public class PageMemoryImpl implements PageMemoryEx {
// Need release again because we pin page when resolve abs pointer,
// and page did not have tmp buffer page.
- if (!tmpBuffer)
+ if (!pageSingleAcquire)
PageHeader.releasePage(absPtr);
}
else {
- copyInBuffer(absPtr, tmpBuf);
+ copyInBuffer(absPtr, outBuf);
PageHeader.dirty(absPtr, false);
@@ -1158,8 +1164,8 @@ public class PageMemoryImpl implements PageMemoryEx {
PageHeader.releasePage(absPtr);
}
- assert PageIO.getType(tmpBuf) != 0 : "Invalid state. Type is 0! pageId = " + U.hexLong(fullId.pageId());
- assert PageIO.getVersion(tmpBuf) != 0 : "Invalid state. Version is 0! pageId = " + U.hexLong(fullId.pageId());
+ assert PageIO.getType(outBuf) != 0 : "Invalid state. Type is 0! pageId = " + U.hexLong(fullId.pageId());
+ assert PageIO.getVersion(outBuf) != 0 : "Invalid state. Version is 0! pageId = " + U.hexLong(fullId.pageId());
return true;
}
@@ -1199,7 +1205,7 @@ public class PageMemoryImpl implements PageMemoryEx {
seg.writeLock().lock();
try {
- int newTag = seg.incrementPartTag(grpId, partId);
+ int newTag = seg.incrementPartGeneration(grpId, partId);
if (tag == 0)
tag = newTag;
@@ -1220,7 +1226,7 @@ public class PageMemoryImpl implements PageMemoryEx {
seg.writeLock().lock();
try {
- seg.resetPartTags(grpId);
+ seg.resetGroupPartitionsGeneration(grpId);
}
finally {
seg.writeLock().unlock();
@@ -1230,7 +1236,7 @@ public class PageMemoryImpl implements PageMemoryEx {
/** {@inheritDoc} */
@Override public IgniteInternalFuture<Void> clearAsync(
- GridPredicate3<Integer, Long, Integer> pred,
+ LoadedPagesMap.KeyPredicate pred,
boolean cleanDirty
) {
CountDownFuture completeFut = new CountDownFuture(segments.length);
@@ -1811,16 +1817,22 @@ public class PageMemoryImpl implements PageMemoryEx {
/** */
private static final double FULL_SCAN_THRESHOLD = 0.4;
+ /** Pointer to acquired pages integer counter. */
+ private static final int ACQUIRED_PAGES_SIZEOF = 4;
+
+ /** Padding to read from word beginning. */
+ private static final int ACQUIRED_PAGES_PADDING = 4;
+
/** Page ID to relative pointer map. */
- private FullPageIdTable loadedPages;
+ private LoadedPagesMap loadedPages;
- /** */
+ /** Pointer to acquired pages integer counter. */
private long acquiredPagesPtr;
/** */
private PagePool pool;
- /** */
+ /** Bytes required to store {@link #loadedPages}. */
private long memPerTbl;
/** Pages marked as dirty since the last checkpoint. */
@@ -1832,8 +1844,11 @@ public class PageMemoryImpl implements PageMemoryEx {
/** */
private final int maxDirtyPages;
- /** Maps partition (cacheId, partId) to its tag. Tag is 1-based incrementing partition file counter */
- private final Map<T2<Integer, Integer>, Integer> partTagMap = new HashMap<>();
+ /** Initial partition generation. */
+ private static final int INIT_PART_GENERATION = 1;
+
+ /** Maps partition (cacheId, partId) to its generation. Generation is 1-based incrementing partition counter. */
+ private final Map<GroupPartitionId, Integer> partGenerationMap = new HashMap<>();
/** */
private boolean closed;
@@ -1847,15 +1862,23 @@ public class PageMemoryImpl implements PageMemoryEx {
int pages = (int)(totalMemory / sysPageSize);
- memPerTbl = requiredSegmentTableMemory(pages);
-
acquiredPagesPtr = region.address();
GridUnsafe.putIntVolatile(null, acquiredPagesPtr, 0);
- loadedPages = new FullPageIdTable(region.address() + 8, memPerTbl, true);
+ int ldPagesMapOffInRegion = ACQUIRED_PAGES_SIZEOF + ACQUIRED_PAGES_PADDING;
+
+ long ldPagesAddr = region.address() + ldPagesMapOffInRegion;
+
+ memPerTbl = useBackwardShiftMap
+ ? RobinHoodBackwardShiftHashMap.requiredMemory(pages)
+ : requiredSegmentTableMemory(pages);
- DirectMemoryRegion poolRegion = region.slice(memPerTbl + 8);
+ loadedPages = useBackwardShiftMap
+ ? new RobinHoodBackwardShiftHashMap(ldPagesAddr, memPerTbl)
+ : new FullPageIdTable(ldPagesAddr, memPerTbl, true);
+
+ DirectMemoryRegion poolRegion = region.slice(memPerTbl + ldPagesMapOffInRegion);
pool = new PagePool(idx, poolRegion, null);
@@ -1980,7 +2003,7 @@ public class PageMemoryImpl implements PageMemoryEx {
saveDirtyPage.writePage(
fullPageId,
wrapPointer(absPtr + PAGE_OVERHEAD, pageSize()),
- partTag(
+ partGeneration(
fullPageId.groupId(),
PageIdUtils.partId(fullPageId.pageId())
)
@@ -2102,13 +2125,13 @@ public class PageMemoryImpl implements PageMemoryEx {
// We need to lookup for pages only in current segment for thread safety,
// so peeking random memory will lead to checking for found page segment.
// It's much faster to check available pages for segment right away.
- EvictCandidate nearest = loadedPages.getNearestAt(rnd.nextInt(cap), INVALID_REL_PTR);
+ ReplaceCandidate nearest = loadedPages.getNearestAt(rnd.nextInt(cap));
assert nearest != null && nearest.relativePointer() != INVALID_REL_PTR;
long rndAddr = nearest.relativePointer();
- int partTag = nearest.tag();
+ int partGen = nearest.generation();
final long absPageAddr = absolute(rndAddr);
@@ -2118,7 +2141,7 @@ public class PageMemoryImpl implements PageMemoryEx {
assert fullId.equals(nearest.fullId()) : "Invalid page mapping [tableId=" + nearest.fullId() +
", actual=" + fullId + ", nearest=" + nearest;
- boolean outdated = partTag < partTag(fullId.groupId(), PageIdUtils.partId(fullId.pageId()));
+ boolean outdated = partGen < partGeneration(fullId.groupId(), PageIdUtils.partId(fullId.pageId()));
if (outdated)
return refreshOutdatedPage(this, fullId.groupId(), fullId.pageId(), true);
@@ -2184,11 +2207,7 @@ public class PageMemoryImpl implements PageMemoryEx {
loadedPages.remove(
fullPageId.groupId(),
- PageIdUtils.effectivePageId(fullPageId.pageId()),
- partTag(
- fullPageId.groupId(),
- PageIdUtils.partId(fullPageId.pageId())
- )
+ PageIdUtils.effectivePageId(fullPageId.pageId())
);
return relRmvAddr;
@@ -2231,19 +2250,19 @@ public class PageMemoryImpl implements PageMemoryEx {
int failToPrepare = 0;
for (int i = 0; i < cap; i++) {
- final EvictCandidate nearest = loadedPages.getNearestAt(i, INVALID_REL_PTR);
+ final ReplaceCandidate nearest = loadedPages.getNearestAt(i);
assert nearest != null && nearest.relativePointer() != INVALID_REL_PTR;
final long addr = nearest.relativePointer();
- int partTag = nearest.tag();
+ int partGen = nearest.generation();
final long absPageAddr = absolute(addr);
FullPageId fullId = PageHeader.fullPageId(absPageAddr);
- if (partTag < partTag(fullId.groupId(), PageIdUtils.partId(fullId.pageId())))
+ if (partGen < partGeneration(fullId.groupId(), PageIdUtils.partId(fullId.pageId())))
return refreshOutdatedPage(this, fullId.groupId(), fullId.pageId(), true);
boolean pinned = PageHeader.isAcquired(absPageAddr);
@@ -2261,11 +2280,7 @@ public class PageMemoryImpl implements PageMemoryEx {
if (preparePageRemoval(fullPageId, absEvictAddr, saveDirtyPage)) {
loadedPages.remove(
fullPageId.groupId(),
- PageIdUtils.effectivePageId(fullPageId.pageId()),
- partTag(
- fullPageId.groupId(),
- PageIdUtils.partId(fullPageId.pageId())
- )
+ PageIdUtils.effectivePageId(fullPageId.pageId())
);
return addr;
@@ -2309,64 +2324,55 @@ public class PageMemoryImpl implements PageMemoryEx {
/**
* @param grpId Cache group ID.
* @param partId Partition ID.
- * @return Partition tag. Growing 1 based partition file version
+ * @return Partition generation. Growing, 1-based partition version. Changed
*/
- private int partTag(int grpId, int partId) {
+ private int partGeneration(int grpId, int partId) {
assert getReadHoldCount() > 0 || getWriteHoldCount() > 0;
- Integer tag = partTagMap.get(new T2<>(grpId, partId));
-
- if (tag == null)
- return 1;
+ Integer tag = partGenerationMap.get(new GroupPartitionId(grpId, partId));
- return tag;
+ return tag == null ? INIT_PART_GENERATION : tag;
}
/**
+ * Increments partition generation due to partition invalidation (e.g. partition was rebalanced to other node
+ * and evicted).
+ *
* @param grpId Cache group ID.
* @param partId Partition ID.
- * @return New partition tag.
+ * @return New partition generation.
*/
- private int incrementPartTag(int grpId, int partId) {
+ private int incrementPartGeneration(int grpId, int partId) {
assert getWriteHoldCount() > 0;
- T2<Integer, Integer> t = new T2<>(grpId, partId);
+ GroupPartitionId grpPart = new GroupPartitionId(grpId, partId);
- Integer tag = partTagMap.get(t);
+ Integer gen = partGenerationMap.get(grpPart);
- if (tag == null) {
- partTagMap.put(t, 2);
+ if (gen == null)
+ gen = INIT_PART_GENERATION;
- return 2;
- }
- else if (tag == Integer.MAX_VALUE) {
+ if (gen == Integer.MAX_VALUE) {
U.warn(log, "Partition tag overflow [grpId=" + grpId + ", partId=" + partId + "]");
- partTagMap.put(t, 0);
+ partGenerationMap.put(grpPart, 0);
return 0;
}
else {
- partTagMap.put(t, tag + 1);
+ partGenerationMap.put(grpPart, gen + 1);
- return tag + 1;
+ return gen + 1;
}
}
/**
* @param grpId Cache group id.
*/
- private void resetPartTags(int grpId) {
+ private void resetGroupPartitionsGeneration(int grpId) {
assert getWriteHoldCount() > 0;
- Iterator<T2<Integer, Integer>> iter = partTagMap.keySet().iterator();
-
- while (iter.hasNext()) {
- T2<Integer, Integer> t = iter.next();
-
- if (t.get1() == grpId)
- iter.remove();
- }
+ partGenerationMap.keySet().removeIf(grpPart -> grpPart.getGroupId() == grpId);
}
}
@@ -2552,14 +2558,19 @@ public class PageMemoryImpl implements PageMemoryEx {
}
/**
+ * Sets pointer to checkpoint buffer.
+ *
* @param absPtr Page absolute pointer.
- * @param tmpRelPtr Temp buffer relative pointer.
+ * @param tmpRelPtr Temp buffer relative pointer or {@link #INVALID_REL_PTR} if page is not copied to checkpoint
+ * buffer.
*/
private static void tempBufferPointer(long absPtr, long tmpRelPtr) {
GridUnsafe.putLong(absPtr + PAGE_TMP_BUF_OFFSET, tmpRelPtr);
}
/**
+ * Gets pointer to checkpoint buffer or {@link #INVALID_REL_PTR} if page is not copied to checkpoint buffer.
+ *
* @param absPtr Page absolute pointer.
* @return Temp buffer relative pointer.
*/
@@ -2637,8 +2648,8 @@ public class PageMemoryImpl implements PageMemoryEx {
/** */
private Segment seg;
- /** */
- private GridPredicate3<Integer, Long, Integer> clearPred;
+ /** Clear element filter for (cache group ID, page ID). */
+ LoadedPagesMap.KeyPredicate clearPred;
/** */
private CountDownFuture doneFut;
@@ -2651,12 +2662,12 @@ public class PageMemoryImpl implements PageMemoryEx {
/**
* @param seg Segment.
- * @param clearPred Clear predicate.
+ * @param clearPred Clear predicate for (cache group ID, page ID).
* @param doneFut Completion future.
*/
private ClearSegmentRunnable(
Segment seg,
- GridPredicate3<Integer, Long, Integer> clearPred,
+ LoadedPagesMap.KeyPredicate clearPred,
boolean rmvDirty,
CountDownFuture doneFut,
int pageSize
@@ -2682,14 +2693,11 @@ public class PageMemoryImpl implements PageMemoryEx {
seg.writeLock().lock();
try {
- while (base < boundary) {
- long ptr = seg.loadedPages.clearAt(base, clearPred, INVALID_REL_PTR);
+ GridLongList list = seg.loadedPages.removeIf(base, boundary, clearPred);
- if (ptr != INVALID_REL_PTR)
- ptrs.add(ptr);
+ ptrs.addAll(list);
- base++;
- }
+ base = boundary;
}
finally {
seg.writeLock().unlock();
http://git-wip-us.apache.org/repos/asf/ignite/blob/1f8ec79d/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/ReplaceCandidate.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/ReplaceCandidate.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/ReplaceCandidate.java
new file mode 100644
index 0000000..d760f07
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/ReplaceCandidate.java
@@ -0,0 +1,78 @@
+/*
+ * 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.ignite.internal.processors.cache.persistence.pagemem;
+
+import org.apache.ignite.internal.pagemem.FullPageId;
+import org.apache.ignite.internal.util.tostring.GridToStringExclude;
+import org.apache.ignite.internal.util.tostring.GridToStringInclude;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ * Replacement removal candidate. Class represents some page from loaded pages table. Usually candidate is found during
+ * random {@link LoadedPagesMap} touch.
+ */
+public class ReplaceCandidate {
+ /** Partition generation saved in map, too old value means page may be safely cleared. */
+ private int gen;
+
+ /** */
+ @GridToStringExclude
+ private long relPtr;
+
+ /** */
+ @GridToStringInclude
+ private FullPageId fullId;
+
+ /**
+ * @param gen Partition generation.
+ * @param relPtr Relative pointer to page.
+ * @param fullId Full page ID.
+ */
+ public ReplaceCandidate(int gen, long relPtr, FullPageId fullId) {
+ this.gen = gen;
+ this.relPtr = relPtr;
+ this.fullId = fullId;
+ }
+
+ /**
+ * @return Partition generation saved in map, too old value means page may be safely cleared.
+ */
+ public int generation() {
+ return gen;
+ }
+
+ /**
+ * @return Relative pointer to page.
+ */
+ public long relativePointer() {
+ return relPtr;
+ }
+
+ /**
+ * @return Index.
+ */
+ public FullPageId fullId() {
+ return fullId;
+ }
+
+ /** {@inheritDoc} */
+ @Override public String toString() {
+ return S.toString(ReplaceCandidate.class, this, "relPtr", U.hexLong(relPtr));
+ }
+}