-
-
Notifications
You must be signed in to change notification settings - Fork 8.7k
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
获取accessToken先加锁,会导致后续的请求需要很长时间才能拿到锁 #1582
Comments
目前确实会存在这样的问题, 后续使用 |
lkqm
added a commit
to lkqm/WxJava
that referenced
this issue
May 31, 2020
binarywang
pushed a commit
that referenced
this issue
May 31, 2020
已修复 |
请问一下把 |
如果用lock这里有上万个请求会导致最后一个请求会等待前面9999个人的时间。而实际上只希望请求tencent获取accessToen只有一个线程,而使用tryLock会在某个线程更新accessToken后,其余线程只需要短暂等待后即可获取有效的accessToekn. |
在做测试之前,看你的说明后我理解是 private Lock lock = new ReentrantLock();
static boolean flag = false;
static long x = System.currentTimeMillis();
@Test
public void testLock() throws IOException {
for (int i = 0; i < 1000; i++) {
new Thread(() -> doSome()).start();
}
System.in.read();
}
public void doSome() {
lock.lock();
try {
if (flag) {
return;
}
System.out.println(Thread.currentThread().getName() + "得到了锁" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss:SSS"));
//模拟耗时操作
Thread.sleep(1000);
flag = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
System.out.println(System.currentTimeMillis() - x);
}
}
public void doSome2() {
boolean locked = false;
try {
do {
locked = lock.tryLock(100,TimeUnit.MICROSECONDS);
if (flag) {
return;
}
} while (!locked);
System.out.println(Thread.currentThread().getName() + "得到了锁" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss:SSS"));
//模拟耗时操作
Thread.sleep(1000);
flag = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (locked) {
lock.unlock();
}
System.out.println(System.currentTimeMillis() - x);
}
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: