当前位置: 首页 > Java > 正文

cpu sy高排查的case(二)

1 星2 星3 星4 星5 星 (2 次投票, 评分: 5.00, 总分: 5)
Loading ... Loading ...
baidu_share

关于前一篇的cpu sy high的那个case,问题的代码为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
private Semaphore sp = new Semaphore(1);
 
private AtomicBoolean readyFlag = new AtomicBoolean(true);
 
public long next(){
    while (!this.readyFlag.get())
    {
      Thread.yield();
    }
 
    long m = this.max.get();
    long rtn = this.idGenerator.next();
 
    if (rtn > m) {
      if (!this.readyFlag.get())
        return next();
      try
      {
        this.sp.acquire();
        this.readyFlag.set(false);
 
        do sth...
 
        this.readyFlag.set(true);
      }
      catch (InterruptedException e) {
        e.printStackTrace();
      } 
      finally {
        println("released");
        this.sp.release();
      }
 
      return next();
    }
    return rtn;
}

这段代码除了Thread.yield这个地方需要吐槽外,还有好几个地方要吐槽…

首先要吐槽的是目前这样的写法,如代码执行到do sth…那个部分,然后触发了InterruptedException,就会直接导致readyFlag永远为false,于是之后的代码只要调用到next(),就永远会陷入Thread.yield,cpu sy很快就会很high。

第二个要稍微吐槽的是检查readyFlag的那段代码在sp.acquire之以后也应该放下。

这段代码我写的话,会改造成类似如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
private AtomicBoolean readyFlag = new AtomicBoolean(true);
 
private ReentrantLock lock = new ReentrantLock();
 
private Condition waitReadyFlag = lock.newCondition();
 
public long next(){
    while(!readyFlag.get()){
    try{
        lock.lock();
        if(!readyFlag.get())
        waitReadyFlag.await();
    }
    catch(InterruptedException  e){
        // IGNORE
    }
    finally{
        lock.unlock();
    }
    }
 
    long m = this.max.get();
    long rtn = this.idGenerator.next();
 
    if (rtn > m) {
      try{
      lock.lock();
      if(readyFlag.get()){
              return next();
      }
      readyFlag.set(false);
      // do sth...
      }
      finally{
      if(!readyFlag.get()){
          readyFlag.set(true);
          waitReadyFlag.signalAll();
      }
      lock.unlock();
      }
      return next();
    }
 
    return rtn;
}

本文固定链接: http://www.chepoo.com/cpu-sy-high-case-two.html | IT技术精华网

cpu sy高排查的case(二):等您坐沙发呢!

发表评论