by
2
7
2,597
0
Top 1% !
Popular
Famous
Tagged
Specified
Debate
OpenSource
Popularity: 6341st place

Published on:

LanguageJava
LicenseMIT_X11

safe use of locks in Java

This class shows how to safely implement a lock to manage a crucial variable, accessed by several threads in concurrency.
Just a notes on the use of ReentrantLock: its use may be replaced by a simple synchronized block where no huge concurrency issues are forecasted (say, less than 700 concurrent threads)
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/38564/safe-use-of-locks-in-Java?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
import java.util.concurrent.locks.ReentrantLock; public abstract class LockedClass { /** * Determines whether or not a call (i.e. a particular method of the class) * should be always sent, without depending from the implementation * of isChildSendable() in the children classes */ private boolean isAlwaysSendable = true; /** * Lock for the guard of sending mechanism. */ private ReentrantLock lock = new ReentrantLock(); public LockedClass(boolean isAlwaysendable) { this.isAlwaysendable = isAlwaysendable; } protected boolean isChildSendable(){ //override this behavior in children classes if you need... return true; } public final boolean isSendable(){ if (isAlwaysSendable) return true; boolean b; lock.lock(); b = isChildSendable(); if (b) setChildSendable(false); lock.unlock(); return b; } protected void setChildSendable(boolean sendable){ //put something here or override in children classes if you want to //customize } public final void setSendable(boolean sendable){ if (isAlwaysSendable) return; lock.lock(); setChildSendable(sendable); lock.unlock(); } }
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus