All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.wj0410.cloudbox.tools.lock.SpinLock Maven / Gradle / Ivy

The newest version!
package io.github.wj0410.cloudbox.tools.lock;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 自定义自旋锁
 * 使用场景:并发度不高,临界代码执行时间不长的场景。
 * @author wangjie
 */
@Slf4j
@Component
public class SpinLock {
    private AtomicReference owner = new AtomicReference<>();
    /**
     *  重入次数
     */
    private int count = 0;

    public void lock() {
        Thread cur = Thread.currentThread();
        if (owner.get() == cur) {
            // 重入
            count++;
            return;
        }
        // 自旋获取锁 如果 owner = 期望值null,则将 owner 修改为 cur
        while (!owner.compareAndSet(null, cur)) {
            log.info("Thread:{} 自旋等待中...", cur.getName());
        }
    }

    public void unlock() {
        Thread cur = Thread.currentThread();
        if (owner.get() == cur) {
            if (count > 0) {
                count--;
            } else {
                owner.set(null);
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy