Wednesday, May 03, 2006

Java Lock class is great for test casing

OK, so while trying to understand Oracle's redo latching mechanisms (we have been experiencing a nightmare with log file sync since switching to a new DMX subsystem), I found that java 1.5 has a new Lock class. How cool is that?!!!

import java.io.*;
import java.util.concurrent.locks.*;

class MyThread implements Runnable {
static Lock l = new ReentrantLock();
Thread thrd;

MyThread(String name){
thrd = new Thread(this, name);
thrd.start(); // start the thread
}

public void run(){
System.out.println(thrd.getName() + " starting.");
try {
boolean b = l.tryLock(10000,java.util.concurrent.TimeUnit.MILLISECONDS);
if (b)
System.out.println("Got the lock for " + thrd.getName());
else
System.out.println("Didn't get the lock for " + thrd.getName());
//l.lock();
Thread.sleep(2000);
l.unlock();
}
catch(Exception e) {}
System.out.println(thrd.getName() + " terminating.");
}
}

class myLock {
public static void main(String args[]) {
for (int j = 1; j <= Integer.parseInt(args[0]); j++) {
MyThread mt1 = new MyThread("Child #" + j);
}
}
}
Locations of visitors to this page