Reputation: 97
I want to measure the contention times for different kinds of lock. This example is for a TAS Lock. I am unable to figure out how to go about it. I have used ctime to measure the amount of time a thread is waiting on a lock, but it seems that I am going about it in a wrong way. Since after ctime1 or before ctime2 if may switch and as a result I will not get the actual contention time. Am I approaching it in the right manner or is there some other way to go about it?
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);
}
}
}
Upvotes: 1
Views: 408
Reputation: 10717
As you wrote, you are measuring the execution time between two points, not the lock contention.
You'd better use the Threads tab on Visual VM.
Take a look at this:
http://visualvm.java.net/threads.html
Upvotes: 1