Skip to content

Instantly share code, notes, and snippets.

@kishankg
Created July 22, 2023 08:58
Show Gist options
  • Save kishankg/2000ecd3e06db4967507367d59c7bd72 to your computer and use it in GitHub Desktop.
Save kishankg/2000ecd3e06db4967507367d59c7bd72 to your computer and use it in GitHub Desktop.
public class ClientWrapper {
int connectionState, requestingThreads; //-1 null, 1 init done, 2 closed
Lock lock;
Condition awaitRequest, awaitClose;
ClientWrapper2(){
//constructor
connectionState = -1;
requestingThreads = 0;
lock = new ReentrantLock();
awaitRequest = lock.newCondition();
awaitClose = lock.newCondition();
}
void init(){
lock.lock();
try {
if (connectionState != -1)
return;
connectionState = 1;
awaitClose.signalAll();
awaitRequest.signalAll();
}
catch(Exception e){}
finally{ lock.unlock(); }
}
void request(){
lock.lock();
try{
while(connectionState == -1){
awaitRequest.await();
}
if(connectionState == 2)
return;
}
catch(Exception e){}
finally{ lock.unlock(); }
if(connectionState == 1) {
lock.lock();
try{
requestingThreads++;
}
catch(Exception e){}
finally{ lock.unlock(); }
//make requests
lock.lock();
try{
requestingThreads--;
awaitClose.signalAll();
}
catch(Exception e){}
finally{ lock.unlock(); }
}
}
void close(){
lock.lock();
try{
while(connectionState == -1){
awaitClose.await();
}
if(connectionState == 2)
return;
}
catch(Exception e){}
finally{ lock.unlock(); }
lock.lock();
try{
while(requestingThreads > 0){
awaitClose.await();
}
}
catch(Exception e){}
finally{ lock.unlock(); }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment