Skip to content

Commit fa50e3d

Browse files
authored
Merge pull request #1588 from zliebowitz/fix-stringlocker-behavior
Fix StringLocker behavior.
2 parents 4ca3c15 + 2e7c91a commit fa50e3d

2 files changed

Lines changed: 44 additions & 11 deletions

File tree

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
package ucar.nc2;
22

3-
import java.util.ArrayList;
4-
import java.util.Collections;
5-
import java.util.List;
3+
import java.util.*;
4+
import java.util.concurrent.ConcurrentSkipListSet;
65

76
/**
87
* A list of strings that only allows one thread to use any given value at the same time.
@@ -13,32 +12,29 @@
1312
@Deprecated
1413
public class StringLocker {
1514

16-
private List<String> stringList = Collections.synchronizedList(new ArrayList<>());
17-
private boolean waiting;
15+
private final Set<String> stringSet = new ConcurrentSkipListSet<>();
1816

1917
public synchronized void control(String item) {
2018
// If the string is in use by another thread then wait() for the other thread
21-
waiting = stringList.contains(item);
22-
while (waiting) {
19+
while (stringSet.contains(item)) {
2320
try {
2421
wait();
2522
} catch (InterruptedException e) {
2623
Thread.currentThread().interrupt();
2724
}
2825
}
2926
// Finished waiting so the thread can have the string
30-
stringList.add(item);
27+
stringSet.add(item);
3128
}
3229

3330
public synchronized void release(String item) {
3431
// Tell StringLocker the thread is done with the string
35-
stringList.remove(item);
36-
waiting = false;
32+
stringSet.remove(item);
3733
notifyAll();
3834
}
3935

4036
public String toString() {
41-
return stringList.toString();
37+
return stringSet.toString();
4238
}
4339

4440
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package ucar.nc2;
2+
3+
import org.junit.Assert;
4+
import org.junit.Test;
5+
6+
import java.util.concurrent.atomic.AtomicReference;
7+
8+
public class StringLockerTest {
9+
@Test
10+
public void testNonconflicting() throws InterruptedException {
11+
Thread t = new Thread(() -> {
12+
StringLocker locker = new StringLocker();
13+
locker.control("first");
14+
locker.control("second");
15+
locker.release("first");
16+
locker.release("second");
17+
});
18+
t.start();
19+
t.join(500);
20+
Assert.assertFalse(t.isAlive());
21+
}
22+
23+
24+
@Test
25+
public void testNonconflictingOtherOrder() throws InterruptedException {
26+
Thread t = new Thread(() -> {
27+
StringLocker locker = new StringLocker();
28+
locker.control("first");
29+
locker.control("second");
30+
locker.release("second");
31+
locker.release("first");
32+
});
33+
t.start();
34+
t.join(500);
35+
Assert.assertFalse(t.isAlive());
36+
}
37+
}

0 commit comments

Comments
 (0)