locking - Why not using a try with lock in java? -
I've read, and about try with resources locks, heads. But in reality, what I would like to do, will be try with lock , I mean without logic. This will release us from Verbose
lock.lock (); Try {// throwing some syncing operation exceptions} in the end {// unlock even if the exception lock is thrown. Unlock (); }
Look like this:
? Applies unlock lock; ... try (lock) // Call Lock permanently. Lock () {// Some synchronized actions throwing exceptions} // will eventually {lock.unlock ();}
then this will not be TWR , But just cleaning some boilerplate?
Do you have any technical reasons why why will not be a fair idea?
EDIT: To explain the difference between what I proposed and a simple synchronize (lock) {}
block, check this snippet:
will result in IllegalMonitorStateException
as a result, therefore lock () and unlock () methods It is not called within the synchronized
block.
If you had to deal with a simple matter, then the pattern of locking / unlocking is thus limited to a If you are limited to scope, then you probably do not want to use more complex squares, and instead you should only use the synchronized
keyword instead of saying that, if for some reason you have more It is needed with a complex lock object, so it's around a lock The cover should be relatively straight-forward, which enables the interface to do just that. Example:
Class AutoOnLack Tool Automatic Closable {Private Final Lock Lock; Public static auto lock (lock lock) {lock.lock (); Return new AutoUlok (lock); } Public static AutoUnlock tryLock (lock lock) {if Lock! (Lock Lock) (New LockNotAcquiredException (); } Return new auto-lock (lock); } @ Override Public Zero Close () {lock.unlock (); } Private AutoLock (lock lock) {this.lock = lock; }}
With a wrapper like above, you can do this:
try (AutoUnlock autoUnlock = AutoUnlock.lock (lock)) { // ... which lock is necessary ...}
As it is said, the lock class is usually used for very complex locking scenarios where it is special For example, Lock Objects can be locked in a function in class and can be unlocked later in any other function (such as an Inkmee Locking a line in the database in response to a remote process call, and then unlocking that row in response to an RPC) and thus to make such a cover or lock automatically, to use it manually, to actually use it Ways to have limited access to the way. For more simple scenarios, this is more common to use or synchronize the existing concurrent data structure.
Comments
Post a Comment