001/*
002 * HA-JDBC: High-Availability JDBC
003 * Copyright (C) 2012  Paul Ferraro
004 *
005 * This program is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU Lesser General Public License as published by
007 * the Free Software Foundation, either version 3 of the License, or
008 * (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013 * GNU Lesser General Public License for more details.
014 *
015 * You should have received a copy of the GNU Lesser General Public License
016 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
017 */
018package net.sf.hajdbc.tx;
019
020import java.nio.ByteBuffer;
021import java.util.concurrent.atomic.AtomicLong;
022
023/**
024 * Simple transaction identifier factory using an incrementing counter.
025 * This implementation is *not* safe for <distributable/> clusters, since the identifiers are only unique within a single DatabaseCluster instance.
026 * @author Paul Ferraro
027 */
028public class SimpleTransactionIdentifierFactory implements TransactionIdentifierFactory<Long>
029{
030        private final AtomicLong counter = new AtomicLong(0);
031        
032        /**
033         * {@inheritDoc}
034         * @see net.sf.hajdbc.tx.TransactionIdentifierFactory#createTransactionIdentifier()
035         */
036        @Override
037        public Long createTransactionIdentifier()
038        {
039                return this.counter.incrementAndGet();
040        }
041
042        /**
043         * {@inheritDoc}
044         * @see net.sf.hajdbc.tx.TransactionIdentifierFactory#serialize(java.lang.Object)
045         */
046        @Override
047        public byte[] serialize(Long transactionId)
048        {
049                return ByteBuffer.allocate(this.size()).putLong(transactionId).array();
050        }
051
052        /**
053         * {@inheritDoc}
054         * @see net.sf.hajdbc.tx.TransactionIdentifierFactory#deserialize(byte[])
055         */
056        @Override
057        public Long deserialize(byte[] bytes)
058        {
059                return ByteBuffer.wrap(bytes).getLong();
060        }
061
062        /**
063         * {@inheritDoc}
064         * @see net.sf.hajdbc.tx.TransactionIdentifierFactory#size()
065         */
066        @Override
067        public int size()
068        {
069                return Long.SIZE;
070        }
071}