精华内容
下载资源
问答
  • 2021-02-25 18:47:51

    自己看着讲解的视频,敲了一边代码。

    public class MyLock {

    private Sync sync;

    class Sync extends AbstractQueuedSynchronizer{

    @Override

    protected boolean tryAcquire(int acquires) {

    //当前线程

    final Thread current = Thread.currentThread();

    int c = getState();

    /**

    * 0:当前锁是空闲

    * 1:有锁

    */

    if(c == 0){

    if(compareAndSetState(0,acquires)){

    setExclusiveOwnerThread(current);

    return true;

    }

    }else if(current == getExclusiveOwnerThread()){

    int next = c + acquires;

    setState(next);

    return true;

    }

    return false;

    }

    @Override

    protected boolean tryRelease(int releases) {

    int c = getState() - releases;

    if(Thread.currentThread() != getExclusiveOwnerThread()){

    throw new IllegalMonitorStateException();

    }

    boolean free = false;

    if (c == 0){

    free = true;

    setExclusiveOwnerThread(null);

    }

    setState(c);

    return free;

    }

    /**

    * 显示当前持有锁的线程

    */

    public void showExclusiveThread(){

    if (getExclusiveOwnerThread() != null) {

    System.out.println("currentThread is "+getExclusiveOwnerThread().getName());

    }

    }

    }

    public MyLock(){

    sync = new Sync();

    }

    public void lock(){

    sync.acquire(1);

    }

    public void unLock(){

    sync.release(1);

    }

    public void showLockThread(){

    sync.showExclusiveThread();

    }

    public static void main(String[] args) throws InterruptedException {

    final MyLock lock = new MyLock();

    Thread t1 = new Thread(()->{

    try{

    System.out.println("t1 start................");

    lock.lock();

    System.out.println("t1 get lock................");

    Thread.sleep(5000);

    System.out.println("t1 return................");

    } catch (InterruptedException e) {

    e.printStackTrace();

    } finally {

    lock.unLock();

    }

    });

    t1.setName("t1");

    Thread t2 = new Thread(()->{

    try{

    System.out.println("t2 start................");

    lock.lock();

    System.out.println("t2 get lock................");

    Thread.sleep(5000);

    System.out.println("t2 return...............");

    } catch (InterruptedException e) {

    e.printStackTrace();

    } finally {

    lock.unLock();

    }

    });

    t2.setName("t2");

    t1.start();

    t2.start();

    Thread.sleep(2000);

    lock.showLockThread();

    }

    }

    更多相关内容
  • 自定义Lock显示锁 public interface Lock { class TimeOutException extends Exception { public TimeOutException(String message) { super(message); } } /** * 加锁 * * @throws ...

    自定义Lock显示锁

    public interface Lock {
    	class TimeOutException extends Exception {
    		public TimeOutException(String message) {
    			super(message);
    		}
    	}
    
    	/**
    	 * 加锁
    	 *
    	 * @throws InterruptedException 打断异常
    	 */
    	void lock() throws InterruptedException;
    
    	/**
    	 * 加锁
    	 *
    	 * @param mills 加锁时间
    	 * @throws InterruptedException 打断异常
    	 * @throws TimeOutException     超时异常
    	 */
    	void lock(long mills) throws InterruptedException, TimeOutException;
    
    	/**
    	 * 解锁
    	 */
    	void unlock();
    
    	/**
    	 * 获取争抢锁时被阻塞的线程
    	 *
    	 * @return 被阻塞线程的集合
    	 */
    	Collection<Thread> getBlockedThread();
    
    	/**
    	 * 获取争抢锁时被阻塞的线程的数量
    	 *
    	 * @return 被阻塞的线程的数量
    	 */
    	int getBlockedSize();
    }
    
    
    public class BooleanLock implements Lock {
    	/**
    	 * The initValue is true indicated the lock has been get.
    	 * The initValue is false indicated the lock is free (other thread can get this).
    	 */
    	private boolean initValue;
    
    	private Collection<Thread> blockedThreadCollection = new ArrayList<>();
    
    	private Thread currentThread;
    
    	public BooleanLock() {
    		this.initValue = false;
    	}
    
    	@Override
    	public synchronized void lock() throws InterruptedException {
    		// 锁已经被其他线程使用
    		while (initValue) {
    			blockedThreadCollection.add(Thread.currentThread());
    			this.wait();
    		}
    		// 锁未被使用,抢到锁立即设置initValue的值
    		this.initValue = true;
    		this.currentThread = Thread.currentThread();
    		blockedThreadCollection.remove(Thread.currentThread());
    	}
    
    	@Override
    	public synchronized void lock(long mills) throws InterruptedException, TimeOutException {
    		if (mills <= 0) {
    			lock();
    		}
    
    		long hasRemaining = mills;
    		long endTime = System.currentTimeMillis() + mills;
    		while (initValue) {
    			if (hasRemaining <= 0) {
    				throw new TimeOutException("Time Out");
    			}
    			blockedThreadCollection.add(Thread.currentThread());
    			this.wait(mills);
    			hasRemaining = endTime - System.currentTimeMillis();
    			// System.out.println(Thread.currentThread().getName() + ">>" + hasRemaining);
    		}
    		this.initValue = true;
    		this.currentThread = Thread.currentThread();
    	}
    
    	@Override
    	public synchronized void unlock() {
    		// 释放锁
    		if (Thread.currentThread() == currentThread) {
    			this.initValue = false;
    			Optional.of(Thread.currentThread().getName() + " release the lock monitor.").ifPresent(System.out::println);
    			this.notifyAll();
    		}
    	}
    
    	@Override
    	public Collection<Thread> getBlockedThread() {
    		// 可以直接返回,但是不安全。此处返回的是一个实例,调用者可以随意更改(null,clear()等操作)。
    		return Collections.unmodifiableCollection(blockedThreadCollection);
    	}
    
    	@Override
    	public int getBlockedSize() {
    		return blockedThreadCollection.size();
    	}
    }
    
    public class LockTest {
    	public static void main(String[] args) throws InterruptedException {
    		final BooleanLock booleanLock = new BooleanLock();
    		Stream.of("T1", "T2", "T3", "T4").forEach(name -> {
    			new Thread(() -> {
    				try {
    					booleanLock.lock(5000L);
    					Optional.of(Thread.currentThread().getName() + " have the lock Monitor.").ifPresent(System.out::println);
    					work();
    				} catch (InterruptedException e) {
    					e.printStackTrace();
    				} catch (Lock.TimeOutException e) {
    					Optional.of(Thread.currentThread().getName() + " time out.").ifPresent(System.out::println);
    				} finally {
    					booleanLock.unlock();
    				}
    			}, name).start();
    		});
    
    		// 问题:违规非法操作。导致运行混乱
            /*Thread.sleep(100);
            booleanLock.unlock();*/
    	}
    
    	private static void work() throws InterruptedException {
    		Optional.of(Thread.currentThread().getName() + " is working...").ifPresent(System.out::println);
    		Thread.sleep(10_000);
    	}
    }
    
    展开全文
  • Java并发编程——自定义Lock

    千次阅读 2019-03-30 23:56:30
    public interface Lock { class TimeOutException extends Exception { public TimeOutException(String message) { super(message); } } void lock() throws InterruptedException; void lock(...

    一、引言

    在学习JUC并发包的时,会介绍Lock锁。为了更深入的了解Lock锁的机制,我们可以自定义一个Lock锁,这样去读Lock源码可能好理解一点。

    二、自定义Lock锁

    1、定义Lock接口
    
    public interface Lock {
    
    	class TimeOutException extends Exception {
    		public TimeOutException(String message) {
    			super(message);
    		}
    	}
    
    	void lock() throws InterruptedException;
    
    	void lock(long mills) throws InterruptedException, TimeOutException;
    
    	void unlock();
    
    	Collection<Thread> getBlockedThread();
    
    	int getBlockedSize();
    }
    
    2、Lock实现类
    public class BooleanLock implements Lock {
    
    	// 表示对象的锁是否被占用,true表示对象锁已经被占用
    	private boolean initValue;
    
    	// 表示被阻塞线程的集合
    	private Collection<Thread> blockedThreadCollection = new ArrayList<>();
    
    	// 记录获得当前对象锁的线程
    	private Thread currentThread;
    
    	public BooleanLock() {
    		this.initValue = false;
    	}
    
    	/**
    	 * 加锁,使用synchronized实现同步
    	 */
    	@Override
    	public synchronized void lock() throws InterruptedException {
    		// 如果锁已经被占用,则阻塞当前线程
    		while (initValue) {
    			//将线程加入到阻塞线程集合
    			blockedThreadCollection.add(Thread.currentThread());
    			this.wait();
    		}
    
    		// 锁没有被占用,则当前线程获得锁
    		blockedThreadCollection.remove(Thread.currentThread());
    		this.initValue = true;
    		this.currentThread = Thread.currentThread();
    	}
    
    	/**
    	 * 当线程等待一定时间后,没有释放锁,则其他线程抛出超时异常
    	 */
    	@Override
    	public synchronized void lock(long mills) throws InterruptedException, TimeOutException {
    		if (mills <= 0)
    			lock();
    
    		long hasRemaining = mills;
    		long endTime = System.currentTimeMillis() + mills;
    		while (initValue) {
    			if (hasRemaining <= 0)
    				throw new TimeOutException("Time out");
    			blockedThreadCollection.add(Thread.currentThread());
    			this.wait(mills);
    			hasRemaining = endTime - System.currentTimeMillis();
    		}
    
    		this.initValue = true;
    		this.currentThread = Thread.currentThread();
    	}
    
    	/**
    	 * 释放锁
    	 */
    	@Override
    	public synchronized void unlock() {
    		// 只有占用锁对象的线程,才能释放锁。不然main线程释放锁,程序会有问题。
    		if (Thread.currentThread() == currentThread) {
    			this.initValue = false;
    			System.out.println(Thread.currentThread().getName() + " release the lock monitor.");
    			this.notifyAll();
    		}
    	}
    
    	@Override
    	public Collection<Thread> getBlockedThread() {
    		//保证更新集合操作安全,不存在安全问题
    		return Collections.unmodifiableCollection(blockedThreadCollection);
    	}
    
    	@Override
    	public int getBlockedSize() {
    		return blockedThreadCollection.size();
    	}
    }
    
    3、测试
    public class LockTest {
    
    	public static void main(String[] args) throws InterruptedException {
    
    		final BooleanLock booleanLock = new BooleanLock();
    
    		//创建4个线程
    		for (int i = 1; i < 5; i++) {
    
    			new Thread("T" + i) {
    				@Override
    				public void run() {
    					try {
    						booleanLock.lock(10000);
    						System.out.println(Thread.currentThread().getName() + " have the lock Monitor");
    						work();
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					} catch (Lock.TimeOutException e) {
    						System.out.println(Thread.currentThread().getName() + " time out");
    					} finally {
    						booleanLock.unlock();
    					}
    				};
    			}.start();
    		}
    
    	}
    
    	private static void work() throws InterruptedException {
    		System.out.println(Thread.currentThread().getName() + " is Working...");
    		Thread.sleep(40_000);
    	}
    }
    
    4、测试结果

    在这里插入图片描述

    三、小结

    自定义一个Lock锁,熟悉Synchronized的同时,深入理解JUC中的Lock。

    展开全文
  • java自定义注解运用

    2022-02-08 11:37:12
    java自定义注解运用 下面是用redis编写自定义注解实现进程锁:

    java自定义注解运用

    下面是用redis编写自定义注解实现进程锁:

    //
    // Source code recreated from a .class file by IntelliJ IDEA
    // (powered by FernFlower decompiler)
    //
    
    package com.hr360.redission.lock.aop.annonation;
    
    import java.lang.annotation.Documented;
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Inherited;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Target({ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Inherited
    @Documented
    public @interface UseRLock {
        long maxLockTime() default 5000L;
    
        String area() default "default";
    
        String clazz() default "default";
    
        String method() default "default";
    
        UseRLock.LockPolicy policy() default UseRLock.LockPolicy.REJECT;
    
        public static enum LockPolicy {
            WAIT,
            REJECT;
    
            private LockPolicy() {
            }
        }
    }
    
    //
    // Source code recreated from a .class file by IntelliJ IDEA
    // (powered by FernFlower decompiler)
    //
    
    package com.hr360.redission.lock.aop.annonation;
    
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Target({ElementType.TYPE, ElementType.PARAMETER})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface LockKey {
    }
    
    //
    // Source code recreated from a .class file by IntelliJ IDEA
    // (powered by FernFlower decompiler)
    //
    
    package com.hr360.redission.lock.aop;
    
    public class RLockException extends RuntimeException {
        public RLockException(String message) {
            super(message);
        }
    }
    
    //
    // Source code recreated from a .class file by IntelliJ IDEA
    // (powered by FernFlower decompiler)
    //
    
    package com.hr360.redission.lock.aop;
    
    import com.hr360.commons.exception.hr360Exception;
    import com.hr360.redission.lock.aop.annonation.LockKey;
    import com.hr360.redission.lock.aop.annonation.UseRLock;
    import com.hr360.redission.lock.aop.annonation.UseRLock.LockPolicy;
    import java.lang.annotation.Annotation;
    import java.lang.reflect.Method;
    import java.lang.reflect.Parameter;
    import java.util.concurrent.TimeUnit;
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.Signature;
    import org.aspectj.lang.annotation.AfterReturning;
    import org.aspectj.lang.annotation.AfterThrowing;
    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.reflect.MethodSignature;
    import org.redisson.api.RLock;
    import org.redisson.api.RedissonClient;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import org.springframework.transaction.support.TransactionSynchronizationAdapter;
    import org.springframework.transaction.support.TransactionSynchronizationManager;
    import org.springframework.util.StringUtils;
    
    @Aspect
    @Component
    public class UseRLockAspect {
        private static final String REDIS_NS = "rlock:";
        private static final String DEFAULT = "default";
        private final Logger log = LoggerFactory.getLogger(this.getClass());
        @Autowired
        private RedissonClient redissonClient;
    
        public UseRLockAspect() {
        }
    
        @AfterThrowing(
            value = "@annotation(com.hr360.redission.lock.aop.annonation.UseRLock)",
            throwing = "e"
        )
        public void afterThrowing(final JoinPoint joinPoint, Exception e) throws Throwable {
            if (!TransactionSynchronizationManager.isSynchronizationActive()) {
                this.unlock(joinPoint);
            } else {
                TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                    public void afterCompletion(int status) {
                        try {
                            UseRLockAspect.this.unlock(joinPoint);
                        } catch (NoSuchMethodException var3) {
                            UseRLockAspect.this.log.error("unlock:{}", var3);
                        }
    
                    }
                });
            }
    
        }
    
        @AfterReturning("@annotation(com.hr360.redission.lock.aop.annonation.UseRLock)")
        public void after(final JoinPoint joinPoint) throws Throwable {
            if (!TransactionSynchronizationManager.isSynchronizationActive()) {
                this.unlock(joinPoint);
            } else {
                TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                    public void afterCommit() {
                        try {
                            UseRLockAspect.this.unlock(joinPoint);
                        } catch (NoSuchMethodException var2) {
                            UseRLockAspect.this.log.error("unlock:{}", var2);
                        }
    
                    }
                });
            }
    
        }
    
        private void unlock(JoinPoint joinPoint) throws NoSuchMethodException {
            UseRLock annotation = this.getUseRLock(joinPoint);
            String lockKey = this.getLockKey(annotation.area(), annotation.clazz(), annotation.method(), joinPoint);
            RLock lock = this.redissonClient.getLock(lockKey);
            if (lock != null && lock.isHeldByCurrentThread() && lock.isLocked()) {
                lock.unlock();
            }
    
        }
    
        @Around("@annotation(com.hr360.redission.lock.aop.annonation.UseRLock)")
        public Object aroundMethod(ProceedingJoinPoint pjp) throws Throwable {
            this.lock(pjp);
            return pjp.proceed();
        }
    
        private void lock(ProceedingJoinPoint pjp) throws NoSuchMethodException {
            UseRLock annotation = this.getUseRLock(pjp);
            long maxLockTime = annotation.maxLockTime();
            String area = annotation.area();
            String clazz = annotation.clazz();
            String method = annotation.method();
            LockPolicy policy = annotation.policy();
            RLock lock = null;
            String lockKey = this.getLockKey(area, clazz, method, pjp);
            lock = this.redissonClient.getLock(lockKey);
            boolean locked = lock.isLocked();
            if (locked && LockPolicy.REJECT.equals(policy)) {
                throw new hr360Exception((String)null, "此业务调用仅允许一个并发处理");
            } else {
                lock.lock(maxLockTime, TimeUnit.MILLISECONDS);
            }
        }
    
        private UseRLock getUseRLock(JoinPoint pjp) throws NoSuchMethodException {
            Signature signature = pjp.getSignature();
            MethodSignature mSignature = (MethodSignature)signature;
            Class<?> declaringType = mSignature.getDeclaringType();
            Method method = declaringType.getDeclaredMethod(mSignature.getName(), mSignature.getParameterTypes());
            return (UseRLock)method.getAnnotation(UseRLock.class);
        }
    
        private String getLockKey(String area, String clazz, String methodName, JoinPoint pjp) throws NoSuchMethodException {
            Signature signature = pjp.getSignature();
            MethodSignature mSignature = (MethodSignature)signature;
            Class<?> declaringType = mSignature.getDeclaringType();
            Method method = declaringType.getDeclaredMethod(mSignature.getName(), mSignature.getParameterTypes());
            Annotation[][] parameterAnnotations = method.getParameterAnnotations();
            if (parameterAnnotations != null && parameterAnnotations.length != 0) {
                if ("default".equals(clazz)) {
                    clazz = declaringType.getName();
                }
    
                if ("default".equals(methodName)) {
                    methodName = method.getName();
                }
    
                Parameter[] parameters = method.getParameters();
                Object[] args = pjp.getArgs();
                StringBuilder lockKey = new StringBuilder();
                lockKey.append("rlock:");
                lockKey.append(area);
                lockKey.append(":");
                lockKey.append(clazz);
                lockKey.append(":");
                lockKey.append(methodName);
                lockKey.append(":");
                boolean hasLockKey = false;
    
                for(int index = 0; index < args.length; ++index) {
                    Parameter parameter = parameters[index];
                    LockKey annotation = (LockKey)parameter.getAnnotation(LockKey.class);
                    if (annotation != null) {
                        Object arg = args[index];
                        String argStr = arg.toString();
                        if (arg == null || StringUtils.isEmpty(argStr)) {
                            throw new RLockException("@LockKey parameter must not be null");
                        }
    
                        hasLockKey = true;
                        lockKey.append(argStr);
                    }
                }
    
                if (!hasLockKey) {
                    throw new RLockException("@LockKey must be assigned");
                } else {
                    return lockKey.toString();
                }
            } else {
                throw new RLockException("@LockKey must be assigned");
            }
        }
    }
    
    //
    // Source code recreated from a .class file by IntelliJ IDEA
    // (powered by FernFlower decompiler)
    //
    
    package com.hr360.redisson.autoconfigure;
    
    import java.time.Duration;
    import java.util.List;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    
    @ConfigurationProperties(
        prefix = "hr360.redission.redis"
    )
    public class RedissionProperties {
        private int database = 0;
        private String url;
        private String host = "localhost";
        private String password;
        private int port = 6379;
        private boolean ssl;
        private Duration timeout;
        private RedissionProperties.Sentinel sentinel;
        private RedissionProperties.Cluster cluster;
        private final RedissionProperties.Jedis jedis = new RedissionProperties.Jedis();
        private final RedissionProperties.Lettuce lettuce = new RedissionProperties.Lettuce();
    
        public RedissionProperties() {
        }
    
        public int getDatabase() {
            return this.database;
        }
    
        public void setDatabase(int database) {
            this.database = database;
        }
    
        public String getUrl() {
            return this.url;
        }
    
        public void setUrl(String url) {
            this.url = url;
        }
    
        public String getHost() {
            return this.host;
        }
    
        public void setHost(String host) {
            this.host = host;
        }
    
        public String getPassword() {
            return this.password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public int getPort() {
            return this.port;
        }
    
        public void setPort(int port) {
            this.port = port;
        }
    
        public boolean isSsl() {
            return this.ssl;
        }
    
        public void setSsl(boolean ssl) {
            this.ssl = ssl;
        }
    
        public void setTimeout(Duration timeout) {
            this.timeout = timeout;
        }
    
        public Duration getTimeout() {
            return this.timeout;
        }
    
        public RedissionProperties.Sentinel getSentinel() {
            return this.sentinel;
        }
    
        public void setSentinel(RedissionProperties.Sentinel sentinel) {
            this.sentinel = sentinel;
        }
    
        public RedissionProperties.Cluster getCluster() {
            return this.cluster;
        }
    
        public void setCluster(RedissionProperties.Cluster cluster) {
            this.cluster = cluster;
        }
    
        public RedissionProperties.Jedis getJedis() {
            return this.jedis;
        }
    
        public RedissionProperties.Lettuce getLettuce() {
            return this.lettuce;
        }
    
        public static class Pool {
            private int maxIdle = 8;
            private int minIdle = 0;
            private int maxActive = 8;
            private Duration maxWait = Duration.ofMillis(-1L);
    
            public Pool() {
            }
    
            public int getMaxIdle() {
                return this.maxIdle;
            }
    
            public void setMaxIdle(int maxIdle) {
                this.maxIdle = maxIdle;
            }
    
            public int getMinIdle() {
                return this.minIdle;
            }
    
            public void setMinIdle(int minIdle) {
                this.minIdle = minIdle;
            }
    
            public int getMaxActive() {
                return this.maxActive;
            }
    
            public void setMaxActive(int maxActive) {
                this.maxActive = maxActive;
            }
    
            public Duration getMaxWait() {
                return this.maxWait;
            }
    
            public void setMaxWait(Duration maxWait) {
                this.maxWait = maxWait;
            }
        }
    
        public static class Cluster {
            private List<String> nodes;
            private Integer maxRedirects;
    
            public Cluster() {
            }
    
            public List<String> getNodes() {
                return this.nodes;
            }
    
            public void setNodes(List<String> nodes) {
                this.nodes = nodes;
            }
    
            public Integer getMaxRedirects() {
                return this.maxRedirects;
            }
    
            public void setMaxRedirects(Integer maxRedirects) {
                this.maxRedirects = maxRedirects;
            }
        }
    
        public static class Sentinel {
            private String master;
            private List<String> nodes;
    
            public Sentinel() {
            }
    
            public String getMaster() {
                return this.master;
            }
    
            public void setMaster(String master) {
                this.master = master;
            }
    
            public List<String> getNodes() {
                return this.nodes;
            }
    
            public void setNodes(List<String> nodes) {
                this.nodes = nodes;
            }
        }
    
        public static class Jedis {
            private RedissionProperties.Pool pool;
    
            public Jedis() {
            }
    
            public RedissionProperties.Pool getPool() {
                return this.pool;
            }
    
            public void setPool(RedissionProperties.Pool pool) {
                this.pool = pool;
            }
        }
    
        public static class Lettuce {
            private Duration shutdownTimeout = Duration.ofMillis(100L);
            private RedissionProperties.Pool pool;
    
            public Lettuce() {
            }
    
            public Duration getShutdownTimeout() {
                return this.shutdownTimeout;
            }
    
            public void setShutdownTimeout(Duration shutdownTimeout) {
                this.shutdownTimeout = shutdownTimeout;
            }
    
            public RedissionProperties.Pool getPool() {
                return this.pool;
            }
    
            public void setPool(RedissionProperties.Pool pool) {
                this.pool = pool;
            }
        }
    }
    
    //
    // Source code recreated from a .class file by IntelliJ IDEA
    // (powered by FernFlower decompiler)
    //
    
    package com.hr360.redisson.autoconfigure;
    
    import com.hr360.redisson.autoconfigure.RedissionProperties.Sentinel;
    import java.lang.reflect.Method;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Iterator;
    import java.util.List;
    import org.redisson.Redisson;
    import org.redisson.api.RedissonClient;
    import org.redisson.config.ClusterServersConfig;
    import org.redisson.config.Config;
    import org.redisson.config.SentinelServersConfig;
    import org.redisson.config.SingleServerConfig;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.autoconfigure.AutoConfigureBefore;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
    import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.EnableAspectJAutoProxy;
    import org.springframework.data.redis.core.RedisOperations;
    import org.springframework.util.ReflectionUtils;
    
    @Configuration
    @EnableAspectJAutoProxy
    @ComponentScan(
        basePackages = {"com.hr360.redission.lock.aop"}
    )
    @ConditionalOnClass({Redisson.class, RedisOperations.class})
    @AutoConfigureBefore({RedisAutoConfiguration.class})
    @EnableConfigurationProperties({RedissionProperties.class})
    public class RedissonAutoConfiguration {
        private static final Logger log = LoggerFactory.getLogger(RedissonAutoConfiguration.class);
        @Autowired
        private RedissionProperties redissionProperties;
    
        public RedissonAutoConfiguration() {
            log.info("#### init RedissionAutoConfiguration success #### 20210306 Great");
        }
    
        @Bean(
            destroyMethod = "shutdown"
        )
        @ConditionalOnMissingBean({RedissonClient.class})
        public RedissonClient redisson() {
            Config config = null;
            Method clusterMethod = ReflectionUtils.findMethod(RedissionProperties.class, "getCluster");
            Method timeoutMethod = ReflectionUtils.findMethod(RedissionProperties.class, "getTimeout");
            Object timeoutValue = ReflectionUtils.invokeMethod(timeoutMethod, this.redissionProperties);
            int timeout;
            Method nodesMethod;
            if (null == timeoutValue) {
                timeout = 10000;
            } else if (!(timeoutValue instanceof Integer)) {
                nodesMethod = ReflectionUtils.findMethod(timeoutValue.getClass(), "toMillis");
                timeout = ((Long)ReflectionUtils.invokeMethod(nodesMethod, timeoutValue)).intValue();
            } else {
                timeout = (Integer)timeoutValue;
            }
    
            if (this.redissionProperties.getSentinel() != null) {
                nodesMethod = ReflectionUtils.findMethod(Sentinel.class, "getNodes");
                Object nodesValue = ReflectionUtils.invokeMethod(nodesMethod, this.redissionProperties.getSentinel());
                String[] nodes;
                if (nodesValue instanceof String) {
                    nodes = this.convert(Arrays.asList(((String)nodesValue).split(",")));
                } else {
                    nodes = this.convert((List)nodesValue);
                }
    
                config = new Config();
                ((SentinelServersConfig)config.useSentinelServers().setMasterName(this.redissionProperties.getSentinel().getMaster()).addSentinelAddress(nodes).setDatabase(this.redissionProperties.getDatabase()).setConnectTimeout(timeout)).setPassword(this.redissionProperties.getPassword());
            } else {
                Method method;
                if (clusterMethod != null && ReflectionUtils.invokeMethod(clusterMethod, this.redissionProperties) != null) {
                    Object clusterObject = ReflectionUtils.invokeMethod(clusterMethod, this.redissionProperties);
                    method = ReflectionUtils.findMethod(clusterObject.getClass(), "getNodes");
                    List<String> nodesObject = (List)ReflectionUtils.invokeMethod(method, clusterObject);
                    String[] nodes = this.convert(nodesObject);
                    config = new Config();
                    ((ClusterServersConfig)config.useClusterServers().addNodeAddress(nodes).setConnectTimeout(timeout)).setPassword(this.redissionProperties.getPassword());
                } else {
                    config = new Config();
                    String prefix = "redis://";
                    method = ReflectionUtils.findMethod(RedissionProperties.class, "isSsl");
                    if (method != null && (Boolean)ReflectionUtils.invokeMethod(method, this.redissionProperties)) {
                        prefix = "rediss://";
                    }
    
                    ((SingleServerConfig)((SingleServerConfig)config.useSingleServer().setAddress(prefix + this.redissionProperties.getHost() + ":" + this.redissionProperties.getPort()).setConnectTimeout(timeout)).setDatabase(this.redissionProperties.getDatabase()).setPassword(this.redissionProperties.getPassword())).setConnectionMinimumIdleSize(this.redissionProperties.getJedis().getPool().getMinIdle()).setConnectionPoolSize(this.redissionProperties.getJedis().getPool().getMaxActive());
                }
            }
    
            return Redisson.create(config);
        }
    
        private String[] convert(List<String> nodesObject) {
            List<String> nodes = new ArrayList(nodesObject.size());
            Iterator var3 = nodesObject.iterator();
    
            while(true) {
                while(var3.hasNext()) {
                    String node = (String)var3.next();
                    if (!node.startsWith("redis://") && !node.startsWith("rediss://")) {
                        nodes.add("redis://" + node);
                    } else {
                        nodes.add(node);
                    }
                }
    
                return (String[])nodes.toArray(new String[nodes.size()]);
            }
        }
    }
    
    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      
        <modelVersion>4.0.0</modelVersion>
        <artifactId>hr360-redisson-starter</artifactId>
        <packaging>jar</packaging>
        <version>2.8.221.fix</version>
    
        <properties>
            <org.redisson.version>3.12.4</org.redisson.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-actuator-autoconfigure</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
            </dependency>
            <dependency>
                <groupId>org.redisson</groupId>
                <artifactId>redisson</artifactId>
                <version>4.0.0</version>
            </dependency>
            <!--<dependency>-->
                <!--<groupId>org.springframework</groupId>-->
                <!--<artifactId>spring-web</artifactId>-->
            <!--</dependency>-->
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjrt</artifactId>
                <version>1.9.2</version>
                <scope>compile</scope>
            </dependency>
        </dependencies>
    </project>
    
    展开全文
  • Java 自定义锁实现

    2021-02-13 02:22:47
    Java中的并发常用到锁的实现常见的 ReentrantLock 可重入锁(公平和非公平锁)读写锁( 共享锁和独占锁)等下面模拟可重入锁动态实现之自定义锁的1 定义 类SelfLock 实现Lock接口public class SelfLockimplements Lock {...
  • 自定义Lock

    2021-09-02 23:20:26
    自定义Lock锁代码: import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic....
  • 前言 你知道自定义注解的魅力所在吗? 你知道自定义注解该怎么使用吗? 本文一开始的这两个问题,需要您仔细思考下,然后结合这两个问题来阅读下面的内容; 本文主线: ...实现一个自定义注解;...Java注解又称J
  • 本文参考自:Java并发编程:LockLock锁并不是java内置的功能,其应用场景是在多线程并发访问时,为了避免冲突,需要每个线程先获取锁,避免其他线程的进入,等线程执行完后释放锁,允许其他线程进入。 1. Lock锁...
  • 实现自定义Lock

    2018-11-30 07:22:06
    实现自定义Lock类准备工作实现过程工作原理扩展学习更多关注 锁是Java并发API提供的基本同步机制之一,每次只有一个线程可以执行代码块,因此用来保护代码的关键部分。锁机制提供如下两种操作: lock():当访问...
  • java中的Lock

    2020-07-15 02:42:43
    Lockjava.util.concurrent.locks 包 下的接口,Lock 实现提供了比 synchronized 关键字 更广泛的锁操作,它能以更优雅的方式处理线程同步问题。Lock提供了比synchronized更多的功能。 1.Lock和ReadWriteLock是...
  • 之前我写了篇博客: java自定义类加载器实现类隔离 ,里面介绍了如何自定义类加载器实现了类隔离。 通常情况下,在JSP,OSGI及其他一些支持热替换的库,都是需要进行类的卸载回收的,否则类在替换后,老的类就没用了...
  • Java自定义线程池

    千次阅读 2020-06-29 20:48:54
    学习自定义线程池之前大家应该先学习设计模式-享元模式 下面这张图就是自定义线程池原理: ThreadPool类就是我们的线程池; BlockQuene类是我们定义的阻塞队列,当线程池满了,我们把来的任务先放到阻塞队列中; ...
  • import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; //数据管理类 public class DataManager implements Runnable{ private final Lock lock = new ReentrantLock(); ...
  • import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks....
  • 自定义lock

    2019-06-23 17:06:39
    主要方法: lock(加锁) unlock(解除锁) package com.code.constructor.lock; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks...import java.util.concurrent.locks.Lock; public class ...
  • ReentrantLock作为一个jdk层面的锁,实现了lock接口,在自定义自己的reentrantLock时只需要重写tryacquire获取许可方法,tryRelease尝试释放锁逻辑方法,isHeldExclusively判断是否被占用,其中一个很重要的方法...
  • 一种情况是在程序中最后UI显示的时候一个一个异常捕获,然后 显示对应的ErrorMessage,有时候,程序因为业务逻辑的原因需要抛出异常,就需要自定义异常。如何将异常消息集中处理,以对应多语言话的要求 ,这些错误...
  • Java自定义实现自旋锁

    2021-04-20 20:20:56
    以下是通过尚硅谷-周阳老师对自旋锁的讲解,自己自定义实现的自旋锁 import java.util.concurrent.atomic.AtomicReference; /** * 通过CAS操作完成自旋锁,t1线程先进来调用lock方法,自己持有锁3秒钟,t2线程随后...
  • package com.code.constructor.lock; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.AbstractQueuedSynchronizer; import java.util.concurrent.locks.Condition; import java.util.co...
  • java 实现一个自定义Lock

    千次阅读 2015-05-11 14:47:48
    实现一个自定义Lock类锁是Java并发API提供的基本同步机制之一。它允许程序员保护代码的临界区,所以,在某个时刻只有一个线程能执行这个代码块。它提供以下两种操作: lock():当你想要访问一个临界区时,调用这个...
  • Java8 Lock锁详解(AQS,CAS)

    千次阅读 2020-07-01 15:04:32
    什么是Lock锁? Lock锁提供了的比synchronized关键字...非阻塞,可以被中断,未获取到则排队,中断,可以自定义超时时间 共享锁 不支持 读写锁ReadWriteLock支持 释放锁 必须在当前代码块中,因为synchronized是以{
  • 自定义Lock类、 实现abstractQueuedSynchronizer。
  • 通过实现Lock接口的lock()方法和unlock()方法来完成自定义实现 ps:主要思想就是设置一个状态量,根据状态量来判断是否锁被占用,如果被占用就wait(),如果没被占用就使用。 自定义互斥锁实现 public ...
  • 以下是自定义的同步组件类,一般我们将自定义同步器Sync定义为同步组件TwinsLock的静态内部类。实现同步器需要继承AbstractQueuedSynchronizer并覆盖相应的方法。package com.lock;import java.util.concurrent....
  • 先来一张图 主线程往阻塞队列中PUT 任务...我们自定义的线程池分为以下几个步骤 自定义阻塞队列 自定义拒绝策略 自定义工作者线程 自定义线程池 修改线程池参数,并进行测试 1 自定义一个阻塞队列 /** ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 62,018
精华内容 24,807
关键字:

java自定义lock

java 订阅
友情链接: lumit-sch-1.4.0.rar