You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@ignite.apache.org by "Semyon Danilov (Jira)" <ji...@apache.org> on 2022/05/30 10:10:00 UTC

[jira] [Commented] (IGNITE-17043) Performance degradation in Marshaller

    [ https://issues.apache.org/jira/browse/IGNITE-17043?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=17543868#comment-17543868 ] 

Semyon Danilov commented on IGNITE-17043:
-----------------------------------------

A little benchmark for fill vs. unsafe implementation of GridHandleTable shows that there is no any reason to use unsafe instead of fill. That's why spineEmpty and nextEmpty arrays were removed.

JmhGridHandleTableBenchmark.safe    thrpt    5  6,941 ± 0,949  ops/s
JmhGridHandleTableBenchmark.unsafe  thrpt    5  6,495 ± 2,140  ops/s


{code:java}
/*
 * 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.benchmarks.jmh.misc;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.apache.ignite.internal.processors.cache.PartitionUpdateCounterTrackingImpl;
import org.apache.ignite.internal.util.GridHandleTable;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

/**
 * Benchmarks {@link PartitionUpdateCounterTrackingImpl} class.
 */
@State(Scope.Benchmark)
@Fork(1)
@Threads(1)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
@Warmup(iterations = 3, time = 5)
@Measurement(iterations = 5, time = 10)
public class JmhGridHandleTableBenchmark {
    /** Buffer size to store testing gaps. */
    private GridHandleTable table;

    private List<Integer> lst = new ArrayList<>();

    /**
     * Setup.
     */
    @Setup(Level.Iteration)
    public void setupIteration() {
        lst = IntStream.range(0, 1_000_000).boxed().collect(Collectors.toList());
    }

    @Setup(Level.Invocation)
    public void setupInvocation() {
        table = new GridHandleTable(10, 3.00f);
    }

    /**
     * Update partition update counter with random gap.
     */
    @Benchmark
    public void unsafe() {
        GridHandleTable.USE_UNSAFE = true;

        put();
    }

    @Benchmark
    public void safe() {
        GridHandleTable.USE_UNSAFE = false;

        put();
    }

    private void put() {
        lst.forEach(table::putIfAbsent);

        table.clear();
        table.putIfAbsent(1337);
        table.clear();
        table.putIfAbsent(1337);
        table.clear();
        table.putIfAbsent(1337);
        table.clear();
        table.putIfAbsent(1337);
        table.clear();
        table.putIfAbsent(1337);
        table.clear();
        table.putIfAbsent(1337);
        table.clear();
        table.putIfAbsent(1337);
        table.clear();
        table.putIfAbsent(1337);
        table.clear();
    }

    /**
     *
     * @param args Args.
     * @throws Exception Exception.
     */
    public static void main(String[] args) throws Exception {
        final Options options = new OptionsBuilder()
            .include(JmhGridHandleTableBenchmark.class.getSimpleName())
            .build();

        new Runner(options).run();
    }
}

/*
 * 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.util;

import java.util.Arrays;

/**
 * Lightweight identity hash table which maps objects to integer handles,
 * assigned in ascending order.
 */
public class GridHandleTable {
    public static boolean USE_UNSAFE = false;

    private static final byte[] MINUS_ONES = new byte[80 * GridUnsafe.pageSize()];

    static {
        Arrays.fill(MINUS_ONES, (byte) 0xFF);
    }

    /** Initial size. */
    private final int initCap;

    /** Factor for computing size threshold. */
    private final float loadFactor;

    /** Number of mappings in table/next available handle. */
    private int size;

    /** Size threshold determining when to expand hash spine. */
    private int threshold;

    /** Maps hash value -> candidate handle value. */
    private int[] spine;

    /** Maps handle value -> next candidate handle value. */
    private int[] next;

    /** Maps handle value -> associated object. */
    private Object[] objs;

    /**
     * Creates new HandleTable with given capacity and load factor.
     *
     * @param initCap Initial capacity.
     * @param loadFactor Load factor.
     */
    public GridHandleTable(int initCap, float loadFactor) {
        this.initCap = initCap;
        this.loadFactor = loadFactor;

        init(initCap, initCap);
    }

    /**
     * Initialize hash table.
     *
     * @param spineLen Spine array length.
     * @param size Hash table length.
     */
    private void init(int spineLen, int size) {
        spine = new int[spineLen];
        next = new int[size];
        objs = new Object[size];

        if (USE_UNSAFE)
            minusOne(spine);
        else
            Arrays.fill(spine, -1);

        threshold = (int)(spineLen * loadFactor);
    }

    /**
     * Looks up and returns handle associated with the given object. If the given object was not found,
     * puts it into the table and returns {@code -1}.
     *
     * @param obj Object.
     * @return Object's handle or {@code -1} if it was not in the table.
     */
    public int putIfAbsent(Object obj) {
        int idx = hash(obj) % spine.length;

        if (size > 0) {
            for (int i = spine[idx]; i >= 0; i = next[i])
                if (objs[i] == obj)
                    return i;
        }

        if (size >= next.length)
            growEntries();

        if (size >= threshold) {
            growSpine();

            idx = hash(obj) % spine.length;
        }

        insert(obj, size, idx);

        size++;

        return -1;
    }

    /**
     * Resets table to its initial (empty) state.
     */
    public void clear() {
        if (size < objs.length) {
            if (shrink()) {
                size = 0;

                return;
            }
        }

        if (USE_UNSAFE)
            minusOne(spine);
        else
            Arrays.fill(spine, -1);

        Arrays.fill(objs, 0, size, null);

        size = 0;
    }

    /**
     * @return Returns objects that were added to handles table.
     */
    public Object[] objects() {
        return objs;
    }

    /**
     * Inserts mapping object -> handle mapping into table. Assumes table
     * is large enough to accommodate new mapping.
     *
     * @param obj Object.
     * @param handle Handle.
     * @param idx Index.
     */
    private void insert(Object obj, int handle, int idx) {
        objs[handle] = obj;
        next[handle] = spine[idx];
        spine[idx] = handle;
    }

    /**
     * Expands the hash "spine" - equivalent to increasing the number of
     * buckets in a conventional hash table.
     */
    private void growSpine() {
        int size = (spine.length << 1) + 1;

        spine = new int[size];
        threshold = (int)(spine.length * loadFactor);

        if (USE_UNSAFE)
            minusOne(spine);
        else
            Arrays.fill(spine, -1);

        for (int i = 0; i < this.size; i++) {
            Object obj = objs[i];

            int idx = hash(obj) % spine.length;

            insert(objs[i], i, idx);
        }
    }

    /**
     * Increases hash table capacity by lengthening entry arrays.
     */
    private void growEntries() {
        int newLen = (next.length << 1) + 1;
        int[] newNext = new int[newLen];

        System.arraycopy(next, 0, newNext, 0, size);

        next = newNext;

        Object[] newObjs = new Object[newLen];

        System.arraycopy(objs, 0, newObjs, 0, size);

        objs = newObjs;
    }

    /**
     * Tries to gradually shrink hash table by factor of two when it's cleared.
     *
     * @return {@code true} if shrinked the table, {@code false} otherwise.
     */
    private boolean shrink() {
        int newSize = Math.max((objs.length - 1) / 2, initCap);

        if (newSize >= size && newSize < objs.length) {
            int newSpine = spine.length;

            if (spine.length > initCap) {
                int prevSpine = (spine.length - 1) / 2;
                int prevThreshold = (int)(prevSpine * loadFactor);

                if (newSize < prevThreshold)
                    newSpine = prevSpine;
            }

            init(newSpine, newSize);

            return true;
        }

        return false;
    }

    /**
     * Returns hash value for given object.
     *
     * @param obj Object.
     * @return Hash value.
     */
    private int hash(Object obj) {
        return System.identityHashCode(obj) & 0x7FFFFFFF;
    }

    private static final long INT_ARR_OFF = GridUnsafe.INT_ARR_OFF;

    private void minusOne(int[] array) {
        int sz = MINUS_ONES.length;
        int len = array.length * Integer.BYTES;
        long off = 0;

        for (; off + sz <= len; off += sz) {
            GridUnsafe.copyMemory(MINUS_ONES, GridUnsafe.BYTE_ARR_OFF, array, INT_ARR_OFF + off, sz);
        }

        if (len != off) {
            GridUnsafe.copyMemory(MINUS_ONES, GridUnsafe.BYTE_ARR_OFF, array, INT_ARR_OFF + off, len - off);
        }
    }
}

{code}


> Performance degradation in Marshaller
> -------------------------------------
>
>                 Key: IGNITE-17043
>                 URL: https://issues.apache.org/jira/browse/IGNITE-17043
>             Project: Ignite
>          Issue Type: Bug
>          Components: cache
>    Affects Versions: 2.13, 2.14
>            Reporter: Sergey Kosarev
>            Assignee: Semyon Danilov
>            Priority: Major
>          Time Spent: 3h
>  Remaining Estimate: 0h
>
> There is a problem in ignite-core code in GridHandleTable used inside OptimizedMarshaller where the internal buffers grow in size and does not shrink back.
> What problematic is in GridHandleTable? This is its reset() method that fills arrays in memory. Done once, it's not a big deal. Done a million times for a long buffer, it becomes really long and CPU-consuming.
> Here is simple reproducer (omitting imports for brevity):
> Marshalling of the same object at first takes about 50ms, and then after degradation more than 100 seconds.
> {code:title=DegradationReproducer.java|borderStyle=solid}
> public class DegradationReproducer extends BinaryMarshallerSelfTest {
>     @Test
>     public void reproduce() throws Exception {
>         List<List<Integer>> obj = IntStream.range(0, 100000).mapToObj(Collections::singletonList).collect(Collectors.toList());
>         for (int i = 0; i < 50; i++) {
>             Assert.assertThat(measureMarshal(obj), Matchers.lessThan(1000L));
>         }
>         binaryMarshaller().marshal(
>                 Collections.singletonList(IntStream.range(0, 1000_000).mapToObj(String::valueOf).collect(Collectors.toList()))
>         );
>         Assert.assertThat(measureMarshal(obj), Matchers.lessThan(1000L));
>     }
>     private long measureMarshal(List<List<Integer>> obj) throws IgniteCheckedException {
>         info("marshalling started ");
>         long millis = System.currentTimeMillis();
>         binaryMarshaller().marshal(obj);
>         millis = System.currentTimeMillis() - millis;
>         info("marshalling finished in " + millis + " ms");
>         return millis;
>     }
> }
> {code}
> on my machine reslust is:
> {quote}
> .....
> [2022-05-26 20:58:27,178][INFO ][test-runner-#1%binary.DegradationReproducer%][root] marshalling finished in 39 ms
> [2022-05-26 20:58:27,769][INFO ][test-runner-#1%binary.DegradationReproducer%][root] marshalling started 
> [2022-05-26 21:02:03,588][INFO ][test-runner-#1%binary.DegradationReproducer%][root] marshalling finished in 215819 ms
> [2022-05-26 21:02:03,593][ERROR][main][root] Test failed [test=DegradationReproducer#reproduce[useBinaryArrays = true], duration=218641]
> java.lang.AssertionError: 
> Expected: a value less than <1000L>
>      but: <*215819L*> was greater than <1000L>
> 	at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
> 	at org.junit.Assert.assertThat(Assert.java:956)
> 	at org.junit.Assert.assertThat(Assert.java:923)
> 	at org.apache.ignite.internal.binary.DegradationReproducer.reproduce(DegradationReproducer.java:27)
> {quote}



--
This message was sent by Atlassian Jira
(v8.20.7#820007)