File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11package 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.
1312@ Deprecated
1413public 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}
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments