Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Concurrency Pattern: Object that switches between Blocking and Non-Blocking Under Certain Conditions
- private AtomicBoolean mSyncMode;
- private AtomicBoolean mOutOfAsyncZone;
- private AtomicInteger mAsyncThreads;
- public MyObject()
- {
- mSyncMode.set(false);
- mOutOfAsyncZone.set(false);
- mAsyncThreads=0;
- }
- //this method must always run synchronized...
- public synchronized void SyncMethod()
- {
- if(!mSyncMode.get())
- SetSyncMode(true);
- if(mSyncThreads > 0)
- wait();
- //do stuff....
- SetSyncMode(false);
- }
- //this method is used to toggle this object between sync and async mode.
- public void SetSyncMode(boolean b)
- {
- mSyncMode.set(b);
- }
- public void DoStuff()
- {
- //do stuff...
- }
- public void DoOtherStuff()
- {
- }
- //this method can run safely
- public void SyncAndAsyncMethod()
- {
- if(mSyncMode.get())
- {
- synchronized(this)
- {
- if(mAsyncThreads > 0)
- wait();
- DoStuff();
- }
- }
- else
- {
- mAsyncThreads++;
- DoStuff();
- mAsyncThreads--;
- if(mSyncMode.get() && mAsyncThreads <= 0)
- {
- synchronized(this)
- {
- notifyAll();
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment