测量锁定中的争用时间

时间:2014-03-16 19:22:36

标签: java multithreading locking profiling

我想测量不同类型锁的争用时间。这个例子 用于TAS锁。我无法弄清楚如何去做。我用 ctime 来衡量一个线程等待一个锁的时间,但似乎我要去 关于它以错误的方式。由于在ctime1之后或在ctime2之前如果可以切换,因此我将无法获得实际的争用时间。我是以正确的方式接近它还是还有其他方法可以解决这个问题?

class Stack{

    int stack[];
    int top, size;
    void push(int e);
    int pop();      
}

class Pusher implements Runnable{

Thread t;
Stack s;
TASLock lock;
long ctime, etime;

Pusher(Stack temp, TASLock tempLock){
    t = new Thread(this);
    s = temp;
    lock = tempLock;
    ctime = etime = 0;
    t.start();
} 

public void run(){
    long ctime1, ctime2, etime1, etime2;
    int id = (int)t.getId();
    int times = 10000;

    etime1 = System.nanoTime();

    while(times-->0){
        //System.out.println("Pushing - "+t.getName());

        ctime1 = System.nanoTime();     

        lock.lock();

        ctime2 = System.nanoTime();
        ctime += ctime2 - ctime1;

        try{
            s.push(id);
        } finally { lock.unlock(); }
    }

    etime2 = System.nanoTime();
    etime = etime2-etime1;

    System.out.println(t.getName()+" Waiting time : "+ctime);
    System.out.println(t.getName()+" Execution time : "+etime);
}
}

class Popper implements Runnable{
Works the same way as push...
}

class StackDriver{

public static void main(String[] args){

    Stack s = new Stack(1000);
    TASLock lock = new TASLock();
    int i, noOfThreads = Integer.parseInt(args[0]); 

    for(i=0; i<noOfThreads; i++){
        if(i%2 == 0)
            new Pusher(s,lock);
        else
            new Popper(s,lock);
    }
}
}

1 个答案:

答案 0 :(得分:1)

正如您所写,您正在测量两点之间的执行时间,而不是锁争用。

您最好使用Visual VM上的“线程”选项卡。

看看这个:

http://visualvm.java.net/threads.html

相关问题