001/* 002 * (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Nuxeo - initial API and implementation 018 * 019 * $Id$ 020 */ 021 022package org.nuxeo.ecm.core.utils; 023 024/** 025 * Generate session IDs. 026 * <p> 027 * Session IDs are long values that must be unique on the same JVM. Each call of the {@link SIDGenerator#next()} method 028 * returns an unique ID (unique relative to the current running JVM). 029 * 030 * @author <a href="mailto:[email protected]">Bogdan Stefanescu</a> 031 */ 032public final class SIDGenerator { 033 034 private static int count = 0; 035 036 private static final int COUNT_OFFSET = 32; 037 038 private SIDGenerator() { 039 } 040 041 /** 042 * The long unique id is generated as follow: 043 * <p> 044 * On the first 32 bits we put an integer value incremented at each call and that is reset to 0 when the it reaches 045 * the max integer range. 046 * <p> 047 * On the last 32 bits the most significant part of the current timestamp in milliseconds. 048 * 049 * @return the next unique id in this JVM 050 */ 051 public static synchronized long next() { 052 if (count == Integer.MAX_VALUE) { 053 count = 0; 054 } 055 long ms = System.currentTimeMillis(); 056 long id = (int) ms; 057 id = Long.rotateLeft(id, COUNT_OFFSET); 058 return id + count++; 059 } 060 061}