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

org.apache.flink.runtime.state.gemini.engine.utils.SeqIDUtils Maven / Gradle / Ivy

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

package org.apache.flink.runtime.state.gemini.engine.utils;

import org.apache.flink.runtime.state.gemini.engine.exceptions.GeminiRuntimeException;

/**
 * Utilities for sequence id.
 */
public class SeqIDUtils {

	/**
	 * Number of bits used for timestamp.
	 */
	public static final int BITS_FOR_TIMESTAMP = 48;

	public static final int BITS_FOR_COUNTER = Long.SIZE - BITS_FOR_TIMESTAMP;

	public static final long MAX_TIMESTAMP = (-1L << (BITS_FOR_COUNTER + 1)) >>> (BITS_FOR_COUNTER + 1);

	public static final long MAX_COUNTER = (-1L << (BITS_FOR_TIMESTAMP + 1)) >>> (BITS_FOR_TIMESTAMP + 1);

	/**
	 * An invalid seqID.
	 */
	public static final long INVALID_SEQID = 0;

	/**
	 * Mask used for counter.
	 */
	public static final long COUNTER_MASK = 0xFFFF;

	/**
	 * Get the timestamp from the seqID.
	 */
	public static long timestamp(long seqID) {
		return seqID >>> BITS_FOR_COUNTER;
	}

	/**
	 * Get the counter from the seqID.
	 */
	public static long counter(long seqID) {
		return seqID & COUNTER_MASK;
	}

	/**
	 * Get next seqID according to last seqID and timestamp.
	 */
	public static long nextSeqID(long lastSeqID, long ts) {
		long lastTime = timestamp(lastSeqID);
		if (ts < lastTime || ts > MAX_TIMESTAMP) {
			throw new GeminiRuntimeException("Unexpected timestamp: lastTime " + lastTime
				+ ", ts " + ts + ", please contact dev");
		}
		long c = counter(lastSeqID);
		long nc = 0;
		if (ts == lastTime) {
			if (c == MAX_COUNTER) {
				throw new GeminiRuntimeException("counter overflowed, please contact dev");
			}
			nc = c + 1;
		}
		return generateSeqID(ts, nc);
	}

	/**
	 * Generate seqID according to timestamp and counter.
	 */
	public static long generateSeqID(long ts, long counter) {
		return (ts << BITS_FOR_COUNTER) | counter;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy