Don't get stuck in the loop.

If we get an exception from the iterator don't catch it and re-try, this makes our loop safer from getting stuck and never returning.
This commit is contained in:
Matthew Buckett 2014-01-14 10:15:22 +00:00
parent 76bf626795
commit 034fb3dd93
2 changed files with 22 additions and 11 deletions

View file

@ -105,8 +105,8 @@ public class License {
if (found == null && uri.startsWith("http://") && uri.toLowerCase().indexOf("creativecommons.org") != -1) {
final Iterator it = License.lookupLicense.keySet().iterator();
while (it.hasNext() && found == null) {
final String key = (String) it.next();
try {
final String key = (String) it.next();
if (key.startsWith(CC_START)) {
final String licensePath = key.substring(CC_START.length(), key.length());
final StringTokenizer tok = new StringTokenizer(licensePath, "/");

View file

@ -24,18 +24,24 @@ public class LicenseTest {
public void testConcurrent() throws InterruptedException {
final AtomicBoolean run = new AtomicBoolean(true);
final AtomicLong type = new AtomicLong(0);
// Tracking any problems.
final AtomicBoolean hadProblem = new AtomicBoolean(false);
final AtomicBoolean hadException = new AtomicBoolean(false);
// This thread keeps on adding new licenses (not very realistic but shows the bug)
Thread addNew = new Thread(){
@Override
public void run() {
while(run.get()) {
License license = License.findByValue("http://creativecommons.org/licenses/"+
type.incrementAndGet()+ "/1");
if (license == null) {
hadProblem.set(true);
try {
while(run.get()) {
License license = License.findByValue("http://creativecommons.org/licenses/"+
type.incrementAndGet()+ "/1");
if (license == null) {
hadProblem.set(true);
}
}
} catch (Exception e) {
hadException.set(true);
}
}
};
@ -45,12 +51,16 @@ public class LicenseTest {
@Override
public void run() {
Random rnd = new Random();
while(run.get()) {
License license = License.findByValue("http://creativecommons.org/licenses/"+
rnd.nextInt(type.intValue())+"/1");
if (license == null) {
hadProblem.set(true);
try {
while(run.get()) {
License license = License.findByValue("http://creativecommons.org/licenses/"+
rnd.nextInt(type.intValue())+"/1");
if (license == null) {
hadProblem.set(true);
}
}
} catch (Exception e) {
hadException.set(true);
}
}
};
@ -66,6 +76,7 @@ public class LicenseTest {
getExisting.join(50);
// Check we didn't have any problems and they have both stopped.
assertFalse(hadProblem.get());
assertFalse(hadException.get());
assertFalse(addNew.isAlive());
assertFalse(getExisting.isAlive());
}