daily pastebin goal
31%
SHARE
TWEET

Untitled

a guest Sep 14th, 2018 55 Never
Upgrade to PRO!
ENDING IN00days00hours00mins00secs
  1. Concurrency Pattern: Object that switches between Blocking and Non-Blocking Under Certain Conditions
  2. private AtomicBoolean mSyncMode;
  3. private AtomicBoolean mOutOfAsyncZone;
  4. private AtomicInteger mAsyncThreads;
  5.  
  6. public MyObject()
  7. {
  8.     mSyncMode.set(false);
  9.     mOutOfAsyncZone.set(false);
  10.     mAsyncThreads=0;
  11. }
  12.  
  13. //this method must always run synchronized...
  14. public synchronized void SyncMethod()
  15. {
  16.     if(!mSyncMode.get())
  17.         SetSyncMode(true);
  18.  
  19.     if(mSyncThreads > 0)
  20.         wait();
  21.  
  22.     //do stuff....
  23.  
  24.     SetSyncMode(false);
  25. }
  26.  
  27. //this method is used to toggle this object between sync and async mode.
  28. public void SetSyncMode(boolean b)
  29. {
  30.     mSyncMode.set(b);
  31. }
  32.  
  33. public void DoStuff()
  34. {
  35.     //do stuff...
  36. }
  37.  
  38. public void DoOtherStuff()
  39. {
  40.  
  41. }
  42.  
  43. //this method can run safely
  44. public void SyncAndAsyncMethod()
  45. {
  46.     if(mSyncMode.get())
  47.     {
  48.         synchronized(this)
  49.         {
  50.             if(mAsyncThreads > 0)
  51.                 wait();
  52.  
  53.             DoStuff();
  54.         }
  55.     }
  56.     else
  57.     {
  58.         mAsyncThreads++;
  59.         DoStuff();
  60.         mAsyncThreads--;
  61.  
  62.         if(mSyncMode.get() && mAsyncThreads <= 0)
  63.         {
  64.             synchronized(this)
  65.             {
  66.                 notifyAll();
  67.             }
  68.         }
  69.     }
  70. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top