multithreading - How to release all permits for a Java Semaphore -



multithreading - How to release all permits for a Java Semaphore -

so code:

int usedpermits = totalpermits - semaphore.availablepermits(); semaphore.release(usedpermits);

isn't threadsafe, because if between 2 lines thread releases permit, semaphore's capacity increment above original maximum.

this works in situation since strip of code 1) single-threaded , 2) place permits released, may illustrate fact "release all" , "acquire/release" 2 incompatible design patterns on same object.

however, want inquire if there preferred pattern less subtle thread synchronization policy.

as explained in other answers, there solution create piece of code atomic. however, there no guarantee solve problem, in general setting, because code cannot right in situations.

either permits released activities using them, in case code superfluous: semaphore replenished naturally, or don't, in case need piece of code, , safe, long don't weird it.

note state wish limit rate of activities per time quantum (here minute), must take in business relationship activities may lastly longer minute. there 2 different things can limit here:

the number of activities starting per quantum, the number of activities running in quantum

if wish limit first, need code refill permits, , allow activites maintain permits. if want handle sec case, must forcefulness activities acquire , release permit when starting , terminating respectively.

if afraid misuse of semaphore activities, forbid utilize in activity code itself. indeed, rate limiting orthogonal activity semantics, , it's improve separate functionality activity main code. hence should wrap scheduled activity code handle semaphore:

class ratelimitedrunnable implements runnable { runnable runnable; ratelimitedrunnable(runnable r) { runnable = r; } void run() { semaphore.acquire(); runnable.run(); semaphore.release(); // remove if limiting starts } }

the sample (untested) code above describe possible handling of utilize of semaphore away real activity, removing potential misuse. if inner activity needs access semaphore, should retrieve current state, , ad-hoc interface can certainly designed provide limited access.

note: utilize "activity" term here mean threads or processes, since give-and-take on uses of semaphores more general context of java.

java multithreading semaphore

Comments

Popular posts from this blog

javascript - mongodb won't find my schema method in nested container -

Hibernate criteria by a list of natural ids -

ios - Lagging ScrollView with UIWebview inside -