All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.trino.operator.IdRegistry Maven / Gradle / Ivy

There is a newer version: 465
Show newest version
/*
 * Licensed 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 io.trino.operator;

import io.airlift.slice.SizeOf;
import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;

import java.util.function.IntFunction;

import static io.airlift.slice.SizeOf.instanceSize;

/**
 * Object registration system that allows looking up objects via stable IDs.
 * 

* This class may recycle deallocated IDs for new allocations. */ public final class IdRegistry { private static final long INSTANCE_SIZE = instanceSize(IdRegistry.class); private final ObjectList objects = new ObjectList<>(); private final IntFIFOQueue emptySlots = new IntFIFOQueue(); /** * Provides a new ID referencing the provided object. * * @return ID referencing the provided object */ public T allocateId(IntFunction factory) { T result; if (!emptySlots.isEmpty()) { int id = emptySlots.dequeueInt(); result = factory.apply(id); objects.set(id, result); } else { result = factory.apply(objects.size()); objects.add(result); } return result; } public void deallocate(int id) { objects.set(id, null); emptySlots.enqueue(id); } public T get(int id) { return objects.get(id); } /** * Does not include the sizes of the referenced objects themselves. */ public long sizeOf() { return INSTANCE_SIZE + objects.sizeOf() + emptySlots.sizeOf(); } private static class IntFIFOQueue extends IntArrayFIFOQueue { private static final long INSTANCE_SIZE = instanceSize(IntFIFOQueue.class); public long sizeOf() { return INSTANCE_SIZE + SizeOf.sizeOf(array); } } private static class ObjectList extends ObjectArrayList { private static final long INSTANCE_SIZE = instanceSize(ObjectList.class); public long sizeOf() { return INSTANCE_SIZE + SizeOf.sizeOf(a); } } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy