Forum Discussion
M_McDonald
16 years agoSuper Contributor
New and improved version. This will let threads that are not interrupted wake up at close to the same time as the sleep time is now calculated from the time the thread set begins to accumulate.
Comments?
Comments?
if ( context.getProperty("LoadTestRunner") == null) {
// if no LoadTestRunner object we are single threaded
return 0
}
def testRunnerContext = context.getProperty("LoadTestRunner").context // get the context of the load test runner
ArrayList waitingThreads = testRunnerContext.getProperty("waitingThreads")
assert waitingThreads != null : "Missing arraylist for threads."
Integer waitTimeout = testRunnerContext.getProperty("waitTimeout") // max time for threads to sleep unless interrupted
assert waitTimeout >= 0 : "Wait timeout must be non-negative"
Integer threadSetSize = testRunnerContext.getProperty("threadSetSize") // number of threads to a set
assert threadSetSize >= 0 : "Thread set size must be non-negative"
def currentThread = Thread.currentThread()
def threadLimitReached = false
def waitStartTime = 0
def sleepTime = 0
synchronized( waitingThreads ) {
log.info "Thread " + currentThread.id + " starting, waiting threads = " + waitingThreads.size
if (waitingThreads.size >= threadSetSize - 1) {
// thread set filled, release all sleeping threads
threadLimitReached = true
for (def t = waitingThreads.size - 1; t >= 0; t--) {
waitingThreads.get(t).interrupt()
waitingThreads.remove(t)
}
} else {
// add this thread to waiting list
waitingThreads.add(currentThread)
if (waitingThreads.size == 1) {
// first thread in set, set the start time
testRunnerContext.setProperty("waitStartTime", System.currentTimeMillis())
}
waitStartTime = testRunnerContext.getProperty("waitStartTime") // get the wait start time for this thread set
// calculate how long this thread should sleep if not interrupted
def currTime = System.currentTimeMillis()
sleepTime = waitTimeout - (currTime - waitStartTime)
sleepTime = sleepTime > 0 ? sleepTime : 0 // if code is right shouldn't need this...
}
}
if (!threadLimitReached) { // don't sleep if this is the last thread in the set
try {
currentThread.sleep(sleepTime);
}
catch (InterruptedException ie) {
currentThread.interrupt()
}
}