Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

代码建议:Lock的使用 #943

Closed
237chenhao opened this issue Feb 20, 2019 · 4 comments
Closed

代码建议:Lock的使用 #943

237chenhao opened this issue Feb 20, 2019 · 4 comments
Assignees

Comments

@237chenhao
Copy link

237chenhao commented Feb 20, 2019

image
jdk源代码:
image
阿里爸爸的码出高效里有提到这个问题.

为什么一开始就要去获取锁呢?
我的想法是先获取accessToken,如果获取不到或者已经过期,则再获取锁去刷新access_token.

@binarywang
Copy link
Owner

建议不错,稍后优化处理一下

@binarywang
Copy link
Owner

3.3.5.B 测试版本已优化

@CuriousRookie
Copy link

现在还能回复吗。。。Lock.lock()应该是不会抛异常的,只会阻塞当前线程直到线程获得锁吧?如果只给刷新accesstoken的方法加锁,如果多个线程运行到这里竞争锁,应该会导致这几个线程依次排队向微信请求刷新accesstoken。所以个人感觉类似单例模式的双重检查应该还是有必要的

@Xiongwenger
Copy link

现在还能回复吗。。。Lock.lock()应该是不会抛异常的,只会阻塞当前线程直到线程获得锁吧?如果只给刷新accesstoken的方法加锁,如果多个线程运行到这里竞争锁,应该会导致这几个线程依次排队向微信请求刷新accesstoken。所以个人感觉类似单例模式的双重检查应该还是有必要的

同上,Lock.lock()只会阻塞吧,然后造成的结果是多个阻塞的线程都会去刷新accesstoken。无法达到注释里说的“在多线程同时刷新时只刷新一次”的效果。反而之前的版本,Lock.lock()在检察accesstoken是否失效之前,能达到“在多线程同时刷新时只刷新一次”的效果。感觉修改之前的版本才是对的。或者可以考虑用lock.tryLock进行优化。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants