两种分布式锁实现方案

详解ReID的各部分组成及Trick——基于FastReID 这一系列博客将基于京东开源的FastReID进行扩充,详细介绍了ReID的各个组成部分,一些有用的Trick,评价指标,常用数据集等,详细内容见下方的链接,总结不易,如有理解不正确之处,麻烦各位批评指正。 一、FastReID的中的baseline文件配置 二、Training strategy 三、Pre-processing 四、Backbone 五、Aggregation 六、Head 七、Loss 八、Distance Metric 九、Post-processing 十、Evaluation 十一 阅读详情

 摘要: 两种分布式锁实现方案(一)
一。为何使用分布式锁?
当应用服务器数量超过1台,对相同数据的访问可能造成访问冲突(特别是写冲突)。单纯使用关系数据库比如MYSQL的应用可以借助于事务来实现锁,也可以使用版本号等实现乐观锁,最大的缺陷就是可用性降低(性能差)。对于GLEASY这种满足大规模并发访问请求的应用来说,使用数据库事务来实现数据库就有些捉襟见肘了。另外对于一些不依赖数据库的应用,比如分布式文件系统,为了保证同一文件在大量读写操作情况下的正确性,必须引入分布式锁来约束对同一文件的并发操作。
二。对分布式锁的要求
1.高性能(分布式锁不能成为系统的性能瓶颈)
2.避免死锁(拿到锁的结点挂掉不会导致其它结点永远无法继续)
3.支持锁重入
三。方案1,基于zookeeper的分布式锁
/**
* DistributedLockUtil.java
* 分布式锁工厂类,所有分布式请求都由该工厂类负责
**/
public class DistributedLockUtil {
private static Object schemeLock = new Object();
private static Object mutexLock = new Object();
private static Map<String,Object> mutexLockMap = new ConcurrentHashMap();
private String schema;
private Map<String,DistributedReentrantLock> cache  = new ConcurrentHashMap<String,DistributedReentrantLock>();

private static Map<String,DistributedLockUtil> instances = new ConcurrentHashMap();
public static DistributedLockUtil getInstance(String schema){
DistributedLockUtil u = instances.get(schema);
if(u==null){
synchronized(schemeLock){
u = instances.get(schema);
if(u == null){
u = new DistributedLockUtil(schema);
instances.put(schema, u);
}
}
}
return u;
}

private DistributedLockUtil(String schema){
this.schema = schema;
}

private Object getMutex(String key){
Object mx = mutexLockMap.get(key);
if(mx == null){
synchronized(mutexLock){
mx = mutexLockMap.get(key);
if(mx==null){
mx = new Object();
mutexLockMap.put(key,mx);
}
}
}
return mx;
}

private DistributedReentrantLock getLock(String key){
DistributedReentrantLock lock = cache.get(key);
if(lock == null){
synchronized(getMutex(key)){
lock = cache.get(key);
if(lock == null){
lock = new DistributedReentrantLock(key,schema);
cache.put(key, lock);
}
}
}
return lock;
}

public void reset(){
for(String s : cache.keySet()){
getLock(s).unlock();
}
}

/**
 * 尝试加锁
 * 如果当前线程已经拥有该锁的话,直接返回false,表示不用再次加锁,此时不应该再调用unlock进行解锁
 * 
 * @param key
 * @return
 * @throws InterruptedException
 * @throws KeeperException
 */
public LockStat lock(String key) throws InterruptedException, KeeperException{
if(getLock(key).isOwner()){
return LockStat.NONEED;
}
getLock(key).lock();
return LockStat.SUCCESS;
}

public void clearLock(String key) throws InterruptedException, KeeperException{
synchronized(getMutex(key)){
DistributedReentrantLock l = cache.get(key);
l.clear();
cache.remove(key);
}
}

public void unlock(String key,LockStat stat) throws InterruptedException, KeeperException{
unlock(key,stat,false);
}

public void unlock(String key,LockStat stat,boolean keepalive) throws InterruptedException, KeeperException{
if(stat == null) return;
if(LockStat.SUCCESS.equals(stat)){
DistributedReentrantLock lock =  getLock(key);
boolean hasWaiter = lock.unlock();
if(!hasWaiter && !keepalive){
synchronized(getMutex(key)){
lock.clear();
cache.remove(key);
}
}
}
}

public static enum LockStat{
NONEED,
SUCCESS
}
}
/**
*DistributedReentrantLock.java
*本地线程之间锁争用,先使用虚拟机内部锁机制,减少结点间通信开销
*/
public class DistributedReentrantLock {
private static final Logger logger =  Logger.getLogger(DistributedReentrantLock.class);
    private ReentrantLock reentrantLock = new ReentrantLock();

    private WriteLock writeLock;
    private long timeout = 3*60*1000;
    
    private final Object mutex = new Object();
    private String dir;
    private String schema;
    
    private final ExitListener exitListener = new ExitListener(){
@Override
public void execute() {
initWriteLock();
}
};

private synchronized void initWriteLock(){
logger.debug("初始化writeLock");
writeLock = new WriteLock(dir,new LockListener(){

@Override
public void lockAcquired() {
synchronized(mutex){
mutex.notify();
}
}
@Override
public void lockReleased() {
}
    
     },schema);

if(writeLock != null && writeLock.zk != null){
writeLock.zk.addExitListener(exitListener);
}

synchronized(mutex){
mutex.notify();
}
}

    public DistributedReentrantLock(String dir,String schema) {
     this.dir = dir;
     this.schema = schema;
     initWriteLock();
    }

    public void lock(long timeout) throws InterruptedException, KeeperException {
        reentrantLock.lock();//多线程竞争时,先拿到第一层锁
        try{
         boolean res = writeLock.trylock();
         if(!res){
         synchronized(mutex){
mutex.wait(timeout);
}
         if(writeLock == null || !writeLock.isOwner()){
         throw new InterruptedException("锁超时");
         }
         }
        }catch(InterruptedException e){
         reentrantLock.unlock();
         throw e;
        }catch(KeeperException e){
         reentrantLock.unlock();
         throw e;
        }
    }
    
    public void lock() throws InterruptedException, KeeperException {
     lock(timeout);
    }

    public void destroy()  throws KeeperException {
     writeLock.unlock();
    }
    

    public boolean unlock(){
     if(!isOwner()) return false;
        try{
         writeLock.unlock();
         reentrantLock.unlock();//多线程竞争时,释放最外层锁
        }catch(RuntimeException e){
         reentrantLock.unlock();//多线程竞争时,释放最外层锁
         throw e;
        }
        
        return reentrantLock.hasQueuedThreads();
    }



    public boolean isOwner() {
        return reentrantLock.isHeldByCurrentThread() && writeLock.isOwner();
    }

public void clear() {
writeLock.clear();
}

}
/**
*WriteLock.java
*基于zk的锁实现
*一个最简单的场景如下:
*1.结点A请求加锁,在特定路径下注册自己(会话自增结点),得到一个ID号1
*2.结点B请求加锁,在特定路径下注册自己(会话自增结点),得到一个ID号2
*3.结点A获取所有结点ID,判断出来自己是最小结点号,于是获得锁
*4.结点B获取所有结点ID,判断出来自己不是最小结点,于是监听小于自己的最大结点(结点A)变更事件
*5.结点A拿到锁,处理业务,处理完,释放锁(删除自己)
*6.结点B收到结点A变更事件,判断出来自己已经是最小结点号,于是获得锁。
*/
public class WriteLock extends ZkPrimative {
   private static final Logger LOG =  Logger.getLogger(WriteLock.class);

    private final String dir;
    private String id;
    private LockNode idName;
    private String ownerId;
    private String lastChildId;
    private byte[] data = {0x12, 0x34};
    private LockListener callback;
    
    public WriteLock(String dir,String schema) {
        super(schema,true);
        this.dir = dir;
    }
    
    public WriteLock(String dir,LockListener callback,String schema) {
     this(dir,schema);
        this.callback = callback;
    }

    public LockListener getLockListener() {
        return this.callback;
    }
    
    public void setLockListener(LockListener callback) {
        this.callback = callback;
    }

    public synchronized void unlock() throws RuntimeException {
     if(zk == null || zk.isClosed()){
     return;
     }
        if (id != null) {
            try {
              zk.delete(id, -1);   
            } catch (InterruptedException e) {
                LOG.warn("Caught: " + e, e);
                /t that we have been interrupted.
               Thread.currentThread().interrupt();
            } catch (KeeperException.NoNodeException e) {
                // do nothing
            } catch (KeeperException e) {
                LOG.warn("Caught: " + e, e);
                throw (RuntimeException) new RuntimeException(e.getMessage()).
                    initCause(e);
            }finally {
                if (callback != null) {
                    callback.lockReleased();
                }
                id = null;
            }
        }
    }
    
    private class LockWatcher implements Watcher {
        public void process(WatchedEvent event) {
            LOG.debug("Watcher fired on path: " + event.getPath() + " state: " + 
                    event.getState() + " type " + event.getType());
            try {
                trylock();
            } catch (Exception e) {
                LOG.warn("Failed to acquire lock: " + e, e);
            }
        }
    }
    
    private void findPrefixInChildren(String prefix, ZooKeeper zookeeper, String dir) 
        throws KeeperException, InterruptedException {
        List<String> names = zookeeper.getChildren(dir, false);
        for (String name : names) {
            if (name.startsWith(prefix)) {
                id = dir + "/" + name;
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found id created last time: " + id);
                }
                break;
            }
        }
        if (id == null) {
            id = zookeeper.create(dir + "/" + prefix, data, 
                    acl, EPHEMERAL_SEQUENTIAL);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Created id: " + id);
            }
        }

    }

public void clear() {
if(zk == null || zk.isClosed()){
     return;
     }
try {
zk.delete(dir, -1);
} catch (Exception e) {
 LOG.error("clear error: " + e,e);
} 
}

    public synchronized boolean trylock() throws KeeperException, InterruptedException {
     if(zk == null){
     LOG.info("zk 是空");
     return false;
     }
        if (zk.isClosed()) {
         LOG.info("zk 已经关闭");
            return false;
        }
        ensurePathExists(dir);
        
        LOG.debug("id:"+id);
        do {
            if (id == null) {
                long sessionId = zk.getSessionId();
                String prefix = "x-" + sessionId + "-";
                idName = new LockNode(id);
                LOG.debug("idName:"+idName);
            }
            if (id != null) {
                List<String> names = zk.getChildren(dir, false);
                if (names.isEmpty()) {
                    LOG.warn("No children in: " + dir + " when we've just " +
                    "created one! Lets recreate it...");
                    id = null;
                } else {
                    SortedSet<LockNode> sortedNames = new TreeSet<LockNode>();
                    for (String name : names) {
                        sortedNames.add(new LockNode(dir + "/" + name));
                    }
                    ownerId = sortedNames.first().getName();
                    LOG.debug("all:"+sortedNames);
                    SortedSet<LockNode> lessThanMe = sortedNames.headSet(idName);
                    LOG.debug("less than me:"+lessThanMe);
                    if (!lessThanMe.isEmpty()) {
                     LockNode lastChildName = lessThanMe.last();
                        lastChildId = lastChildName.getName();
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("watching less than me node: " + lastChildId);
                        }
                        Stat stat = zk.exists(lastChildId, new LockWatcher());
                        if (stat != null) {
                            return Boolean.FALSE;
                        } else {
                            LOG.warn("Could not find the" +
                             " stats for less than me: " + lastChildName.getName());
                        }
                    } else {
                        if (isOwner()) {
                            if (callback != null) {
                                callback.lockAcquired();
                            }
                            return Boolean.TRUE;
                        }
                    }
                }
            }
        }
        while (id == null);
        return Boolean.FALSE;
    }

    public String getDir() {
        return dir;
    }

    public boolean isOwner() {
        return id != null && ownerId != null && id.equals(ownerId);
    }

    public String getId() {
       return this.id;
    }
}
使用本方案实现的分布式锁,可以很好地解决锁重入的问题,而且使用会话结点来避免死锁;性能方面,根据笔者自测结果,加锁解锁各一次算是一个操作,本方案实现的分布式锁,TPS大概为2000-3000,性能比较一般;


四。方案2,基于redis的分布式锁
/**
*分布式锁工厂类
*/
public class RedisLockUtil {
private static final Logger logger =  Logger.getLogger(RedisLockUtil.class);
private static Object schemeLock = new Object();
private static Map<String,RedisLockUtil> instances = new ConcurrentHashMap();
public static RedisLockUtil getInstance(String schema){
RedisLockUtil u = instances.get(schema);
if(u==null){
synchronized(schemeLock){
u = instances.get(schema);
if(u == null){
LockObserver lo = new LockObserver(schema);
u = new RedisLockUtil(schema,lo);
instances.put(schema, u);
}
}
}
return u;
}

private Object mutexLock = new Object();
private Map<String,Object> mutexLockMap = new ConcurrentHashMap();
private Map<String,RedisReentrantLock> cache  = new ConcurrentHashMap<String,RedisReentrantLock>();
private DelayQueue<RedisReentrantLock> dq = new DelayQueue<RedisReentrantLock>();
private AbstractLockObserver lo;
public RedisLockUtil(String schema, AbstractLockObserver lo){
Thread th = new Thread(lo);
th.setDaemon(false);
th.setName("Lock Observer:"+schema);
th.start();
clearUselessLocks(schema);
this.lo = lo;
}

public void clearUselessLocks(String schema){
Thread th = new Thread(new Runnable(){
@Override
public void run() {
while(!SystemExitListener.isOver()){
try {
RedisReentrantLock t = dq.take();
if(t.clear()){
String key = t.getKey();
synchronized(getMutex(key)){
cache.remove(key);
}
}
t.resetCleartime();
} catch (InterruptedException e) {
}
}
}

});
th.setDaemon(true);
th.setName("Lock cleaner:"+schema);
th.start();
}

private Object getMutex(String key){
Object mx = mutexLockMap.get(key);
if(mx == null){
synchronized(mutexLock){
mx = mutexLockMap.get(key);
if(mx==null){
mx = new Object();
mutexLockMap.put(key,mx);
}
}
}
return mx;
}

private RedisReentrantLock getLock(String key,boolean addref){
RedisReentrantLock lock = cache.get(key);
if(lock == null){
synchronized(getMutex(key)){
lock = cache.get(key);
if(lock == null){
lock = new RedisReentrantLock(key,lo);
cache.put(key, lock);
}
}
}
if(addref){
if(!lock.incRef()){
synchronized(getMutex(key)){
lock = cache.get(key);
if(!lock.incRef()){
lock = new RedisReentrantLock(key,lo);
cache.put(key, lock);
}
}
}
}
return lock;
}

public void reset(){
for(String s : cache.keySet()){
getLock(s,false).unlock();
}
}

/**
 * 尝试加锁
 * 如果当前线程已经拥有该锁的话,直接返回,表示不用再次加锁,此时不应该再调用unlock进行解锁
 * 
 * @param key
 * @return
 * @throws Exception 
 * @throws InterruptedException
 * @throws KeeperException
 */
public LockStat lock(String key) {
return lock(key,-1);
}

public LockStat lock(String key,int timeout) {
RedisReentrantLock ll = getLock(key,true);
ll.incRef();
try{
if(ll.isOwner(false)){
ll.descrRef();
return LockStat.NONEED;
}
if(ll.lock(timeout)){
return LockStat.SUCCESS;
}else{
ll.descrRef();
if(ll.setCleartime()){
dq.put(ll);
}
return null;
}
}catch(LockNotExistsException e){
ll.descrRef();
return lock(key,timeout);
}catch(RuntimeException e){
ll.descrRef();
throw e;
}
}

public void unlock(String key,LockStat stat) {
unlock(key,stat,false);
}

public void unlock(String key,LockStat stat,boolean keepalive){
if(stat == null) return;
if(LockStat.SUCCESS.equals(stat)){
RedisReentrantLock lock =  getLock(key,false);
boolean candestroy = lock.unlock();
if(candestroy && !keepalive){
if(lock.setCleartime()){
dq.put(lock);
}
}
}
}

public static enum LockStat{
NONEED,
SUCCESS
}
}
/**
*分布式锁本地代理类
*/
public class RedisReentrantLock implements Delayed{
private static final Logger logger =  Logger.getLogger(RedisReentrantLock.class);
    private ReentrantLock reentrantLock = new ReentrantLock();

    private RedisLock redisLock;
    private long timeout = 3*60;
    private CountDownLatch lockcount = new CountDownLatch(1);

    private String key;
    private AbstractLockObserver observer;

    private int ref = 0;
    private Object refLock = new Object();
    private boolean destroyed = false;

    private long cleartime = -1;

    public RedisReentrantLock(String key,AbstractLockObserver observer) {
     this.key = key;
     this.observer = observer;
     initWriteLock();
    }

public boolean isDestroyed() {
return destroyed;
}

private synchronized void initWriteLock(){
redisLock = new RedisLock(key,new LockListener(){
@Override
public void lockAcquired() {
lockcount.countDown();
}
@Override
public long getExpire() {
return 0;
}

@Override
public void lockError() {
/*synchronized(mutex){
mutex.notify();
}*/
lockcount.countDown();
}
     },observer);
}

public boolean incRef(){
synchronized(refLock){
if(destroyed) return false;
     ref ++;
     }
return true;
}

public void descrRef(){
synchronized(refLock){
     ref --;
     }
}

public boolean clear() {
if(destroyed) return true;
synchronized(refLock){
     if(ref > 0){
     return false;
     }
     destroyed = true;
     redisLock.clear();
     redisLock = null;
     return true;
     }
}

    public boolean lock(long timeout) throws LockNotExistsException{
     if(timeout <= 0) timeout = this.timeout;
     //incRef();
        reentrantLock.lock();//多线程竞争时,先拿到第一层锁
        if(redisLock == null){
         reentrantLock.unlock();
         //descrRef();
         throw new LockNotExistsException();
        }
        try{
         lockcount = new CountDownLatch(1);
         boolean res = redisLock.trylock(timeout);
         if(!res){    
         lockcount.await(timeout, TimeUnit.SECONDS);
//mutex.wait(timeout*1000);
         if(!redisLock.doExpire()){
         reentrantLock.unlock();
return false;
}
         }
         return true;
        }catch(InterruptedException e){
         reentrantLock.unlock();
         return false;
        }
    }

    public boolean lock() throws LockNotExistsException {
     return lock(timeout);
    }

    public boolean unlock(){   
     if(!isOwner(true)) {
     try{
     throw new RuntimeException("big ================================================ error.key:"+key);
     }catch(Exception e){
     logger.error("err:"+e,e);
     }
     return false;
     }
        try{
         redisLock.unlock();
         reentrantLock.unlock();//多线程竞争时,释放最外层锁
        }catch(RuntimeException e){
         reentrantLock.unlock();//多线程竞争时,释放最外层锁
         throw e;
        }finally{
         descrRef();
        }
        return canDestroy();
    }

    public boolean canDestroy(){
     synchronized(refLock){
     return ref <= 0;
     }
    }

    public String getKey() {
return key;
}

public void setKey(String key) {
this.key = key;
}

public boolean isOwner(boolean check) {
     synchronized(refLock){
     if(redisLock == null) {
     logger.error("reidsLock is null:key="+key);
     return false;
     }
     boolean a = reentrantLock.isHeldByCurrentThread();
     boolean b = redisLock.isOwner();
     if(check){
     if(!a || !b){
     logger.error(key+";a:"+a+";b:"+b);
     }
     }
     return a && b;
     }
    }

public boolean setCleartime() {
synchronized(this){
if(cleartime>0) return false;
this.cleartime = System.currentTimeMillis() + 10*1000; 
return true;
}
}

public void resetCleartime(){
synchronized(this){
this.cleartime = -1;
}
}

@Override
public int compareTo(Delayed object) {
if(object instanceof RedisReentrantLock){
RedisReentrantLock t = (RedisReentrantLock)object;
        long l = this.cleartime - t.cleartime;

if(l > 0) return 1 ; //比当前的小则返回1,比当前的大则返回-1,否则为0
else if(l < 0 ) return -1;
else return 0;
}
return 0;
}

@Override
public long getDelay(TimeUnit unit) {
 long d = unit.convert(cleartime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
     return d;
}

}
/**
*使用Redis实现的分布式锁
*基本工作原理如下:
*1. 使用setnx(key,时间戮+超时),如果设置成功,则直接拿到锁
*2. 如果设置不成功,获取key的值v1(它的到期时间戮),跟当前时间对比,看是否已经超时
*3. 如果超时(说明拿到锁的结点已经挂掉),v2=getset(key,时间戮+超时+1),判断v2是否等于v1,如果相等,加锁成功,否则加锁失败,等过段时间再重试(200MS)
*/
public class RedisLock implements LockListener{
private String key;
private boolean owner = false;
private AbstractLockObserver observer = null;
private LockListener lockListener = null;
private boolean waiting = false;
private long expire;//锁超时时间,以秒为单位
private boolean expired = false;

public RedisLock(String key, LockListener lockListener, AbstractLockObserver observer) {
this.key = key;
this.lockListener = lockListener;
this.observer = observer;
}

public boolean trylock(long expire) {
synchronized(this){
if(owner){
return true;
}
this.expire = expire;
this.expired = false;
if(!waiting){
owner = observer.tryLock(key,expire);
if(!owner){
waiting = true;
observer.addLockListener(key, this);
}
}
return owner;
}
}

public boolean isOwner() {
return owner;
}

public void unlock() {
synchronized(this){
observer.unLock(key);
owner = false;
}
}

public void clear() {
synchronized(this){
if(waiting) {
observer.removeLockListener(key);
waiting = false;
}
}
}

public boolean doExpire(){
synchronized(this){
if(owner) return true;
if(expired) return false;
expired =  true;
clear();
}
return false;
}

@Override
public void lockAcquired() {
synchronized(this){
if(expired){
unlock();
return;
}
owner = true;
waiting = false;
}
lockListener.lockAcquired();
}

@Override
public long getExpire() {
return this.expire;
}

@Override
public void lockError() {
synchronized(this){
owner = false;
waiting = false;
lockListener.lockError();
}
}

}
public class LockObserver extends AbstractLockObserver implements Runnable{
private CacheRedisClient client;
private Object mutex = new Object();
private Map<String,LockListener> lockMap = new ConcurrentHashMap();
private boolean stoped = false;
private long interval = 500;
private boolean terminated = false;
private CountDownLatch doneSignal = new CountDownLatch(1);

public LockObserver(String schema){
client = new CacheRedisClient(schema);

SystemExitListener.addTerminateListener(new ExitHandler(){
public void run() {
stoped = true;
try {
doneSignal.await();
} catch (InterruptedException e) {
}
}
});
}


public void addLockListener(String key,LockListener listener){
if(terminated){
listener.lockError();
return;
}
synchronized(mutex){
lockMap.put(key, listener);
}
}

public void removeLockListener(String key){
synchronized(mutex){
lockMap.remove(key);
}
}

@Override
public void run() {
while(!terminated){
long p1 = System.currentTimeMillis();
Map<String,LockListener> clone = new HashMap();
synchronized(mutex){
clone.putAll(lockMap);
}
Set<String> keyset = clone.keySet();
if(keyset.size() > 0){
ConnectionFactory.setSingleConnectionPerThread(keyset.size());
for(String key : keyset){
LockListener ll = clone.get(key);
try{
    if(tryLock(key,ll.getExpire())) {
     ll.lockAcquired();
     removeLockListener(key);
    }
}catch(Exception e){
ll.lockError();
removeLockListener(key);
}
}
ConnectionFactory.releaseThreadConnection();
}else{
if(stoped){
terminated = true;
doneSignal.countDown();
return;
}
}
try {
long p2 = System.currentTimeMillis();
long cost = p2 - p1;
if(cost <= interval){
Thread.sleep(interval - cost);
}else{
Thread.sleep(interval*2);
}
} catch (InterruptedException e) {
}
}

}


/**
 * 超时时间单位为s!!!
 * @param key
 * @param expire
 * @return
 */
public boolean tryLock(final String key,final long expireInSecond){
if(terminated) return false;
final long tt = System.currentTimeMillis();
final long expire = expireInSecond * 1000;
final Long ne = tt + expire;
List<Object> mm = client.multi(key, new MultiBlock(){
@Override
public void execute() {
transaction.setnxObject(key, ne);
transaction.get(SafeEncoder.encode(key));
}
});
Long res = (Long)mm.get(0);
    if(new Long(1).equals(res)) {
     return true;
    }else{
     byte[] bb = (byte[])mm.get(1);
Long ex = client.deserialize(bb);
     if(ex == null || tt > ex){
     Long old = client.getSet(key, new Long(ne+1));
     if(old == null || (ex == null&&old==null) || (ex!=null&&ex.equals(old))){
     return true;
     }
     }
    }
    return false;
}

public void unLock(String key){
client.del(key);
}
}
使用本方案实现的分布式锁,可以完美地解决锁重入问题;通过引入超时也避免了死锁问题;性能方面,笔者自测试结果如下:

500线程 tps = 35000
[root@DB1 benchtest-util]# target/benchtest/bin/TestFastRedis /data/config/util/config_0_11.properties lock 500 500000
线程总时间:6553466;平均:13.106932
实际总时间:13609; 平均:0.027218

TPS达到35000,比方案1强了整整一个数量级;
五。总结
本文介绍了两种分布式锁的实现方案;方案1最大的优势在于避免结点挂掉后导致的死锁;方案2最大的优势在于性能超强;在实际生产过程中,结合自身情况来决定最适合的分布式锁方案是架构师的必修课。
http://rdc.gleasy.com/%E4%B8%A4%E7%A7%8D%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81%E5%AE%9E%E7%8E%B0%E6%96%B9%E6%A1%882.html

四。方案2,基于redis的分布式锁
/**
*分布式锁工厂类
*/
public class RedisLockUtil {
private static final Logger logger =  Logger.getLogger(RedisLockUtil.class);
private static Object schemeLock = new Object();
private static Map<String,RedisLockUtil> instances = new ConcurrentHashMap();
public static RedisLockUtil getInstance(String schema){
RedisLockUtil u = instances.get(schema);
if(u==null){
synchronized(schemeLock){
u = instances.get(schema);
if(u == null){
LockObserver lo = new LockObserver(schema);
u = new RedisLockUtil(schema,lo);
instances.put(schema, u);
}
}
}
return u;
}

private Object mutexLock = new Object();
private Map<String,Object> mutexLockMap = new ConcurrentHashMap();
private Map<String,RedisReentrantLock> cache  = new ConcurrentHashMap<String,RedisReentrantLock>();
private DelayQueue<RedisReentrantLock> dq = new DelayQueue<RedisReentrantLock>();
private AbstractLockObserver lo;
public RedisLockUtil(String schema, AbstractLockObserver lo){
Thread th = new Thread(lo);
th.setDaemon(false);
th.setName("Lock Observer:"+schema);
th.start();
clearUselessLocks(schema);
this.lo = lo;
}

public void clearUselessLocks(String schema){
Thread th = new Thread(new Runnable(){
@Override
public void run() {
while(!SystemExitListener.isOver()){
try {
RedisReentrantLock t = dq.take();
if(t.clear()){
String key = t.getKey();
synchronized(getMutex(key)){
cache.remove(key);
}
}
t.resetCleartime();
} catch (InterruptedException e) {
}
}
}

});
th.setDaemon(true);
th.setName("Lock cleaner:"+schema);
th.start();
}

private Object getMutex(String key){
Object mx = mutexLockMap.get(key);
if(mx == null){
synchronized(mutexLock){
mx = mutexLockMap.get(key);
if(mx==null){
mx = new Object();
mutexLockMap.put(key,mx);
}
}
}
return mx;
}

private RedisReentrantLock getLock(String key,boolean addref){
RedisReentrantLock lock = cache.get(key);
if(lock == null){
synchronized(getMutex(key)){
lock = cache.get(key);
if(lock == null){
lock = new RedisReentrantLock(key,lo);
cache.put(key, lock);
}
}
}
if(addref){
if(!lock.incRef()){
synchronized(getMutex(key)){
lock = cache.get(key);
if(!lock.incRef()){
lock = new RedisReentrantLock(key,lo);
cache.put(key, lock);
}
}
}
}
return lock;
}

public void reset(){
for(String s : cache.keySet()){
getLock(s,false).unlock();
}
}

/**
 * 尝试加锁
 * 如果当前线程已经拥有该锁的话,直接返回,表示不用再次加锁,此时不应该再调用unlock进行解锁
 * 
 * @param key
 * @return
 * @throws Exception 
 * @throws InterruptedException
 * @throws KeeperException
 */
public LockStat lock(String key) {
return lock(key,-1);
}

public LockStat lock(String key,int timeout) {
RedisReentrantLock ll = getLock(key,true);
ll.incRef();
try{
if(ll.isOwner(false)){
ll.descrRef();
return LockStat.NONEED;
}
if(ll.lock(timeout)){
return LockStat.SUCCESS;
}else{
ll.descrRef();
if(ll.setCleartime()){
dq.put(ll);
}
return null;
}
}catch(LockNotExistsException e){
ll.descrRef();
return lock(key,timeout);
}catch(RuntimeException e){
ll.descrRef();
throw e;
}
}

public void unlock(String key,LockStat stat) {
unlock(key,stat,false);
}

public void unlock(String key,LockStat stat,boolean keepalive){
if(stat == null) return;
if(LockStat.SUCCESS.equals(stat)){
RedisReentrantLock lock =  getLock(key,false);
boolean candestroy = lock.unlock();
if(candestroy && !keepalive){
if(lock.setCleartime()){
dq.put(lock);
}
}
}
}

public static enum LockStat{
NONEED,
SUCCESS
}
}
/**
*分布式锁本地代理类
*/
public class RedisReentrantLock implements Delayed{
private static final Logger logger =  Logger.getLogger(RedisReentrantLock.class);
    private ReentrantLock reentrantLock = new ReentrantLock();

    private RedisLock redisLock;
    private long timeout = 3*60;
    private CountDownLatch lockcount = new CountDownLatch(1);

    private String key;
    private AbstractLockObserver observer;

    private int ref = 0;
    private Object refLock = new Object();
    private boolean destroyed = false;

    private long cleartime = -1;

    public RedisReentrantLock(String key,AbstractLockObserver observer) {
     this.key = key;
     this.observer = observer;
     initWriteLock();
    }

public boolean isDestroyed() {
return destroyed;
}

private synchronized void initWriteLock(){
redisLock = new RedisLock(key,new LockListener(){
@Override
public void lockAcquired() {
lockcount.countDown();
}
@Override
public long getExpire() {
return 0;
}

@Override
public void lockError() {
/*synchronized(mutex){
mutex.notify();
}*/
lockcount.countDown();
}
     },observer);
}

public boolean incRef(){
synchronized(refLock){
if(destroyed) return false;
     ref ++;
     }
return true;
}

public void descrRef(){
synchronized(refLock){
     ref --;
     }
}

public boolean clear() {
if(destroyed) return true;
synchronized(refLock){
     if(ref > 0){
     return false;
     }
     destroyed = true;
     redisLock.clear();
     redisLock = null;
     return true;
     }
}

    public boolean lock(long timeout) throws LockNotExistsException{
     if(timeout <= 0) timeout = this.timeout;
     //incRef();
        reentrantLock.lock();//多线程竞争时,先拿到第一层锁
        if(redisLock == null){
         reentrantLock.unlock();
         //descrRef();
         throw new LockNotExistsException();
        }
        try{
         lockcount = new CountDownLatch(1);
         boolean res = redisLock.trylock(timeout);
         if(!res){    
         lockcount.await(timeout, TimeUnit.SECONDS);
//mutex.wait(timeout*1000);
         if(!redisLock.doExpire()){
         reentrantLock.unlock();
return false;
}
         }
         return true;
        }catch(InterruptedException e){
         reentrantLock.unlock();
         return false;
        }
    }

    public boolean lock() throws LockNotExistsException {
     return lock(timeout);
    }

    public boolean unlock(){   
     if(!isOwner(true)) {
     try{
     throw new RuntimeException("big ================================================ error.key:"+key);
     }catch(Exception e){
     logger.error("err:"+e,e);
     }
     return false;
     }
        try{
         redisLock.unlock();
         reentrantLock.unlock();//多线程竞争时,释放最外层锁
        }catch(RuntimeException e){
         reentrantLock.unlock();//多线程竞争时,释放最外层锁
         throw e;
        }finally{
         descrRef();
        }
        return canDestroy();
    }

    public boolean canDestroy(){
     synchronized(refLock){
     return ref <= 0;
     }
    }

    public String getKey() {
return key;
}

public void setKey(String key) {
this.key = key;
}

public boolean isOwner(boolean check) {
     synchronized(refLock){
     if(redisLock == null) {
     logger.error("reidsLock is null:key="+key);
     return false;
     }
     boolean a = reentrantLock.isHeldByCurrentThread();
     boolean b = redisLock.isOwner();
     if(check){
     if(!a || !b){
     logger.error(key+";a:"+a+";b:"+b);
     }
     }
     return a && b;
     }
    }

public boolean setCleartime() {
synchronized(this){
if(cleartime>0) return false;
this.cleartime = System.currentTimeMillis() + 10*1000; 
return true;
}
}

public void resetCleartime(){
synchronized(this){
this.cleartime = -1;
}
}

@Override
public int compareTo(Delayed object) {
if(object instanceof RedisReentrantLock){
RedisReentrantLock t = (RedisReentrantLock)object;
        long l = this.cleartime - t.cleartime;

if(l > 0) return 1 ; //比当前的小则返回1,比当前的大则返回-1,否则为0
else if(l < 0 ) return -1;
else return 0;
}
return 0;
}

@Override
public long getDelay(TimeUnit unit) {
 long d = unit.convert(cleartime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
     return d;
}

}
/**
*使用Redis实现的分布式锁
*基本工作原理如下:
*1. 使用setnx(key,时间戮+超时),如果设置成功,则直接拿到锁
*2. 如果设置不成功,获取key的值v1(它的到期时间戮),跟当前时间对比,看是否已经超时
*3. 如果超时(说明拿到锁的结点已经挂掉),v2=getset(key,时间戮+超时+1),判断v2是否等于v1,如果相等,加锁成功,否则加锁失败,等过段时间再重试(200MS)
*/
public class RedisLock implements LockListener{
private String key;
private boolean owner = false;
private AbstractLockObserver observer = null;
private LockListener lockListener = null;
private boolean waiting = false;
private long expire;//锁超时时间,以秒为单位
private boolean expired = false;

public RedisLock(String key, LockListener lockListener, AbstractLockObserver observer) {
this.key = key;
this.lockListener = lockListener;
this.observer = observer;
}

public boolean trylock(long expire) {
synchronized(this){
if(owner){
return true;
}
this.expire = expire;
this.expired = false;
if(!waiting){
owner = observer.tryLock(key,expire);
if(!owner){
waiting = true;
observer.addLockListener(key, this);
}
}
return owner;
}
}

public boolean isOwner() {
return owner;
}

public void unlock() {
synchronized(this){
observer.unLock(key);
owner = false;
}
}

public void clear() {
synchronized(this){
if(waiting) {
observer.removeLockListener(key);
waiting = false;
}
}
}

public boolean doExpire(){
synchronized(this){
if(owner) return true;
if(expired) return false;
expired =  true;
clear();
}
return false;
}

@Override
public void lockAcquired() {
synchronized(this){
if(expired){
unlock();
return;
}
owner = true;
waiting = false;
}
lockListener.lockAcquired();
}

@Override
public long getExpire() {
return this.expire;
}

@Override
public void lockError() {
synchronized(this){
owner = false;
waiting = false;
lockListener.lockError();
}
}

}
public class LockObserver extends AbstractLockObserver implements Runnable{
private CacheRedisClient client;
private Object mutex = new Object();
private Map<String,LockListener> lockMap = new ConcurrentHashMap();
private boolean stoped = false;
private long interval = 500;
private boolean terminated = false;
private CountDownLatch doneSignal = new CountDownLatch(1);

public LockObserver(String schema){
client = new CacheRedisClient(schema);

SystemExitListener.addTerminateListener(new ExitHandler(){
public void run() {
stoped = true;
try {
doneSignal.await();
} catch (InterruptedException e) {
}
}
});
}


public void addLockListener(String key,LockListener listener){
if(terminated){
listener.lockError();
return;
}
synchronized(mutex){
lockMap.put(key, listener);
}
}

public void removeLockListener(String key){
synchronized(mutex){
lockMap.remove(key);
}
}

@Override
public void run() {
while(!terminated){
long p1 = System.currentTimeMillis();
Map<String,LockListener> clone = new HashMap();
synchronized(mutex){
clone.putAll(lockMap);
}
Set<String> keyset = clone.keySet();
if(keyset.size() > 0){
ConnectionFactory.setSingleConnectionPerThread(keyset.size());
for(String key : keyset){
LockListener ll = clone.get(key);
try{
    if(tryLock(key,ll.getExpire())) {
     ll.lockAcquired();
     removeLockListener(key);
    }
}catch(Exception e){
ll.lockError();
removeLockListener(key);
}
}
ConnectionFactory.releaseThreadConnection();
}else{
if(stoped){
terminated = true;
doneSignal.countDown();
return;
}
}
try {
long p2 = System.currentTimeMillis();
long cost = p2 - p1;
if(cost <= interval){
Thread.sleep(interval - cost);
}else{
Thread.sleep(interval*2);
}
} catch (InterruptedException e) {
}
}

}


/**
 * 超时时间单位为s!!!
 * @param key
 * @param expire
 * @return
 */
public boolean tryLock(final String key,final long expireInSecond){
if(terminated) return false;
final long tt = System.currentTimeMillis();
final long expire = expireInSecond * 1000;
final Long ne = tt + expire;
List<Object> mm = client.multi(key, new MultiBlock(){
@Override
public void execute() {
transaction.setnxObject(key, ne);
transaction.get(SafeEncoder.encode(key));
}
});
Long res = (Long)mm.get(0);
    if(new Long(1).equals(res)) {
     return true;
    }else{
     byte[] bb = (byte[])mm.get(1);
Long ex = client.deserialize(bb);
     if(ex == null || tt > ex){
     Long old = client.getSet(key, new Long(ne+1));
     if(old == null || (ex == null&&old==null) || (ex!=null&&ex.equals(old))){
     return true;
     }
     }
    }
    return false;
}

public void unLock(String key){
client.del(key);
}
}
使用本方案实现的分布式锁,可以完美地解决锁重入问题;通过引入超时也避免了死锁问题;性能方面,笔者自测试结果如下:

500线程 tps = 35000
[root@DB1 benchtest-util]# target/benchtest/bin/TestFastRedis /data/config/util/config_0_11.properties lock 500 500000
线程总时间:6553466;平均:13.106932
实际总时间:13609; 平均:0.027218

TPS达到35000,比方案1强了整整一个数量级;
五。总结
本文介绍了两种分布式锁的实现方案;方案1最大的优势在于避免结点挂掉后导致的死锁;方案2最大的优势在于性能超强;在实际生产过程中,结合自身情况来决定最适合的分布式锁方案是架构师的必修课。

https://my.oschina.net/gaowm/blog/522479
http://rdc.gleasy.com/%E4%B8%A4%E7%A7%8D%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81%E5%AE%9E%E7%8E%B0%E6%96%B9%E6%A1%882.html 

PyTorch强化学习实战(1)——强化学习(Reinforcement Learning,RL)详解 在本节中,开始进入探索强化学习 (Reinforcement Learning, RL) 之旅,首先剖析了强化学习的独特之处及其与监督学习、无监督学习范式的关系。随后系统学习了强化学习的基础形式化框架及其内部关联机制,并深入讲解了马尔可夫过程 (Markov Process, MP)、马尔可夫奖励过程 (Markov Reward Process, MRP) 和马尔可夫决策过程 (Markov Decision Process, MDP),为后续学习奠定基础。 阅读详情

相关推荐

链式中介效应结果解读:从Bootstrap置信区间到实践意义

本文深入解析链式中介效应结果的解读方法,从Bootstrap置信区间的应用到实践意义的阐述。通过实际案例展示如何分析总效应、直接效应和间接效应,并强调效应量评估的重要性。文章还提供了构建逻辑解释的三步法,以及敏感性分析和报告撰写的实用技巧,帮助研究者准确解读链式中介效应。

weixin_33690367的博客 720

两种分布式锁实现方案(一)

一。为何使用分布式锁? 当应用服务器数量超过1台,对相同数据的访问可能造成访问冲突(特别是写冲突)。单纯使用关系数据库比如MYSQL的应用可以借助于事务来实现锁,也可以使用版本号等实现乐观锁,最大的缺陷就是可用性降低(性能差)。对于GLEASY这种满足大规模并发访问请求的应用来说,使用数据库事务来实现数据库就有些捉襟见肘了。另外对于一些不依赖数据库的应用,比如分布式文件系统,为了保证同一文件在大

z69183787的专栏 6005

SAP PI实战:5分钟搞定REST适配器同步接口配置(含Postman测试技巧)

本文详细介绍了如何在SAP PI中快速配置REST适配器同步接口,包括ESR设计、集成流配置及Postman测试技巧。通过实战步骤和关键参数设置,帮助开发者高效实现系统集成,特别适合需要实时数据交互的业务场景。

weixin_33738555的博客 492

两种分布式锁实现方案一(13)

一。为何使用分布式锁? 当应用服务器数量超过1台,对相同数据的访问可能造成访问冲突(特别是写冲突)。单纯使用关系数据库比如MySQL的应用可以借助于事务来实现锁,也可以使用版本号等实现乐观锁,最大的缺陷就是可用性降低(性能差)。对于GLEASY这种满足大规模并发访问请求的应用来说,使用数据库事务来实现数据库就有些捉襟见肘了。另外对于一些不依赖数据库的应用,比如分布式文件系统,为了保证同一文件在大

Jason的专栏 525

大语言模型在构建UNSPSC 分类数据中的应用

UNSPSC 是联合国标准产品和服务代码。本文研究如何利用大语言模型生成分类系统的分析

姚家湾博客 1913

基于Ventoy制作单个U盘引导Windows+Linux+黑苹果macOS

一款国内高手开发的一个名为Ventoy的开源多系统启动U盘制作工具,官方链接:https://www.ventoy.net/cn/index.html Ventoy 特点 不影响U盘日常普通使用 直接从ISO文件启动,无需解开 支持MBR和GPT分区格式(1.0.15+) 支持超过4GB的ISO文件 支持大部分常见操作系统, 已测试650+ 个ISO文件 不仅仅是启动,而是完整的安装过程 版本升级时数据不会丢失 Ventoy 待改进 不支持macOS和ChromeOS 准备2个空的U.

wybarcelona的博客 3万+

分布式锁(Distributed Lock)理论介绍

在多线程环境中,线程之间通常使用互斥锁实现共享资源的独占访问。在多进程环境,特别是分布式环境,常使用分布式锁来实现共享资源的独占访问。简单来说,分布式锁就是指在分布式环境下,通过加解锁实现多节点对共享资源的互斥访问。

云原生Java Web领域技术博客 6846

麒麟V10安装图形化界面

在配置VNC时发现,原本麒麟V10系统最小化安装,导致无图形化界面,先需要对其进行安装。 首先确保无图形化界面,可以在终端输入startX命令查看是否报错。 安装介绍: 1、 安装图形化界面 yum grouplist //查看可用yum安装组 注:这里一般会有缺少包或者出现包不符合的问题 导入软件包分组信息文件xxxx-comps.xml arm: 将此文件传送到源服务器, 然后createrepo -g导入到arm的base目录和updates目录 createrepo -g e33dc

Pro_jhf的博客 8079

分布式锁的应用

之前说到redis队列的场景使用lua脚本可以解决高并发的原子性问题,但是redis集群并不支持lua脚本,因此想要实现原子性防止高并发的问题就需要使用分布式锁。         这里总结两种分布式锁的实现,使用Redisson和Zookeeper。 一、场景回顾 先回顾一下场景,我们假设两个线程分别为不同jvm上的两个程序,一个服务在入队,一个服务在出队,看看判断入队的逻辑是否可靠 pu

guduyishuai的博客 495

vue3 - vite报错TypeError: crypto.hash is not a function(vue3+vite启动运行提示错误,项目无法启动且打包报错失败,详细解决排查方案教程)

vue3 vite 报错,vue3+vite启动报错:TypeError: crypto.hash is not a function,创建vue3+vite项目时报错TypeError: crypto.hash is not a function,如何解决这个问题,VUE3+VITE报错crypto.hash,vue3运行报错,vite运行报错,vue3打包报错,vite打包报错,vue3新建项目无法运行,vue3 vite创建项目直接报错了,node版本不兼容,修改了node版本还是不行,依旧报错,一直

✅ 精选推荐文章 1万+

基于Simulink雷达系统建模仿真(附源码)

此示例显示如何设置由发射器、带目标的信道和接收器组成的雷达系统仿真。一、系统架构该系统包括:雷达脉冲发生器,以 2% 占空比(导通时间 = 2 ms,周期 = 100 ms)输出功率为 1 mW 的啁啾声。RF发射器部分由滤波器和组成,使用RF模块集电路包络库模块实现。由于滤波器是线性器件,放大器是非线性器件,因此它们被分成两个独立的子系统。这种分离允许在每个子系统中使用不同的仿真频率集。这种分离还允许在更快的仿真速度和级联链中可用的级间负载效应损失之间进行权衡。

珞瑜的博客 4586

ReentrantLock实战:典型应用场景与避坑指南

本文将从典型应用场景 、 实战避坑指南 、 性能优化最佳实践三个维度,结合真实业务案例,帮大家打通 “理论” 到 “实战” 的最后一公里,让 ReentrantLock 真正成为解决并发问题的利器。

y245166349的专栏 1192

通用抓取算法AnyGrasp(Graspnet)——本地部署并测试自定义输入数据

背景:GraspNet在数据采集方面,首先将相机固定到机械臂末端,对同一个场景拍摄256个不同的角度,同时场景中的每个物体都会提前采集好3D模型,之后将其投射到仿真环境中,在仿真环境中,对抓取位姿进行打标签,如此完成数据的采集。在运行官方的测试示例时,使用的是路径下的输入数据,可以分析下。color.png(输入):rgb图像(输出):输出的生成抓取位姿的图像depth.png(输入):和当前rgb图像对应的深度图像(保存格式是单通道uint16)meta.mat。

boss-dog 1344

Zookeeper实现分布式锁的两种方案

就是一旦发生了加锁失败,大量的客户端都来watch同一个节点,这样可能会导致一旦锁被释放也就是临时节点被删除,那么zk就会通知所有的监听者。因为zk提供了watch监听机制,且zk同一个目录下的节点名字是不能重复的,基于这两个特性可以用来做分布式锁。这种方式相比于第一种而言,可以优化羊群效应。但是这种方式是一种公平锁的实现方式。但是这种实现方式有一个缺陷,类似于。...

Minor的Java技术博客 765

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

两种分布式锁实现方案(二)

为什么80%的码农都做不了架构师?>>> ...

weixin_34220623的博客 80

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

两种分布式锁实现方案一

一。为何使用分布式锁?当应用服务器数量超过1台,对相同数据的访问可能造成访问冲突(特别是写冲突)。单纯使用关系数据库比如MYSQL的应用可以借助于事务来实现锁,也可以使用版本号等实现乐观锁,最大的缺陷就是可用性降低(性能差)。对于GLEASY这种满足大规模并发访问请求的应用来说,使用数据库事务来实现数据库就有些捉襟见肘了。另外对于一些不依赖数据库的应用,比如分布式文件系统,为了保证同一文件在大...

青年IT男 222

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

使用Redis或Zookeeper实现分布式锁的两种方案比较

先贴上石杉大神的原文连接: 分布式锁用Redis还是Zookeeper? 方案实现 基于Redis实现分布式锁可以使用Redisson综合中间件框架, 基于Zookeeper实现分布式锁可以使用Curator框架 两种方案的优缺点比较 对于 Redis 的分布式锁而言,它有以下缺点: 它获取锁的方式简单粗暴,获取不到锁直接不断尝试获取锁,比较消耗性能。 另外来说的话,Redis 的设计定位决定了它的数据并不是强一致性的,在某些极端情况下,可能会出现问题。锁的模型不够健壮。 即便使用 Redlock 算法

Kainx 539

分布式锁实现--基于zookeeper和redis的两种方案

前言:  最近项目中需要一个定时任务,由于是集群环境,自然而然想到需要通过分布式锁来保证单台执行。查阅相关资料总结了一下实现分布式锁的两种实现方案。分布式锁的由来:在程序开发过程中不得不考虑的就是并发问题。在java中对于同一个jvm而言,jdk已经提供了lock和同步等。但是在分布式情况下,往往存在多个进程对一些资源产生竞争关系,而这些进程往往在不同的机器上,这个时候jdk中提供的...

qq_38363255的博客 1463

两种分布式锁实现方案二(14)

四。方案2,基于Redis的分布式锁 [java] view plain copy /**  * 分布式锁工厂类  */  public class RedisLockUtil {      private static final Logger logger = Logger.getLogger(RedisLockUtil.class);      privat

Jason的专栏 408
上一篇: 迄今为止最优的Eclipse运行性能调优 ,含eclipse.ini
下一篇: Gleasy首席架构师薛珂:以开源为基础实现分布式框架及中间件
琅琊山二当家
博客等级 码龄18年 447粉丝 322原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值