Guest User

Untitled

a guest
Sep 14th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  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. }
Add Comment
Please, Sign In to add comment