001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     Nuxeo - initial API and implementation
011 *
012 * $Id$
013 */
014
015package org.nuxeo.ecm.core.utils;
016
017/**
018 * Generate session IDs.
019 * <p>
020 * Session IDs are long values that must be unique on the same JVM. Each call of the {@link SIDGenerator#next()} method
021 * returns an unique ID (unique relative to the current running JVM).
022 *
023 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
024 */
025public final class SIDGenerator {
026
027    private static int count = 0;
028
029    private static final int COUNT_OFFSET = 32;
030
031    private SIDGenerator() {
032    }
033
034    /**
035     * The long unique id is generated as follow:
036     * <p>
037     * On the first 32 bits we put an integer value incremented at each call and that is reset to 0 when the it reaches
038     * the max integer range.
039     * <p>
040     * On the last 32 bits the most significant part of the current timestamp in milliseconds.
041     *
042     * @return the next unique id in this JVM
043     */
044    public static synchronized long next() {
045        if (count == Integer.MAX_VALUE) {
046            count = 0;
047        }
048        long ms = System.currentTimeMillis();
049        long id = (int) ms;
050        id = Long.rotateLeft(id, COUNT_OFFSET);
051        return id + count++;
052    }
053
054}