与StampedLock的竞争条件?

问题描述 投票:0回答:2

我正在尝试为Hibernate实现我自己的序列生成器。开箱即用的方法有一个synchronized方法,这会在我的应用程序中引起太多争用(多个线程将数据并行插入Oracle数据库)。

我想我会试试StampedLock,但不幸的是我的测试用例(150个行,16个线程)总是在150.000次执行中产生5-15个id冲突。

附上我的代码,你知道我做错了什么,或者你可能建议一个更好的方法?谢谢。

import java.io.Serializable;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.StampedLock;

import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.IntegralDataTypeHolder;
import org.hibernate.id.SequenceGenerator;

public class HighConcurrencySequenceGenerator extends SequenceGenerator
{
  private StampedLock            lock   = new StampedLock();

  private AtomicLong             sequenceValue;   // the current generator value
  private IntegralDataTypeHolder lastSourceValue; // last value read from db
  private IntegralDataTypeHolder upperLimitValue; // the value to query the db again

  @Override
  public Serializable generate( SessionImplementor session, Object object )
  {
    long stamp = this.lock.readLock();
    try
    {
      while ( needsSequenceUpdate() )
      {
        long ws = this.lock.tryConvertToWriteLock( stamp );
        if ( ws != 0L )
        {
          stamp = ws;
          return fetchAndGetNextSequenceValue( session );
        }
        this.lock.unlockRead( stamp );
        stamp = this.lock.writeLock();
      }
      return getNextSequenceValue();
    }
    finally
    {
      this.lock.unlock( stamp );
    }
  }

  private long fetchAndGetNextSequenceValue( SessionImplementor session )
  {
    this.lastSourceValue = generateHolder( session );
    long lastSourceValue = this.lastSourceValue.makeValue()
                                               .longValue();
    this.sequenceValue = new AtomicLong( lastSourceValue );

    long nextVal = getNextSequenceValue();

    this.upperLimitValue = this.lastSourceValue.copy()
                                               .add( this.incrementSize );
    return nextVal;
  }

  private long getNextSequenceValue()
  {
    long nextVal = this.sequenceValue.getAndIncrement();
    return nextVal;
  }

  private boolean needsSequenceUpdate()
  {
    return ( this.sequenceValue == null ) || !this.upperLimitValue.gt( this.sequenceValue.get() );
  }
}
java oracle hibernate sequence java.util.concurrent
2个回答
1
投票

这段代码不是线程安全的

this.sequenceValue = new AtomicLong( lastSourceValue );

在最坏的情况下,您将得到具有相同值的q个qxxswpoi的N个实例,其中N是正在运行的线程数。


0
投票

我用一个AtomicLong替换了IntegralDataTypeHolder upperLimitValue,解决了这个问题。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.