Proposal: Automatic Resource Management
Jeremy Manson
jeremy.manson at gmail.com
Tue Mar 3 23:49:39 PST 2009
On Tue, Mar 3, 2009 at 10:13 PM, Neal Gafter <neal at gafter.com> wrote:
> Can you please show me how to
> handle the following BGGA example using this proposal:
>
> lockWrite(lock) {
> clientCount++;
> }
> lockRead(lock) {
> return field.getValue();
> }
>
>
As a side note to this conversation, directed at any people who will
think you can't have this feature with this proposal, regardless of
your feelings about the particular merits of accomplishing the same
thing with closures, there *is* a way to handle this case:
class LockDisposer implements Disposable {
private final Lock lock;
public LockDisposer(Lock l) {
lock = l;
lock.lock();
}
public void close() {
lock.unlock();
}
}
try (LockDisposer l = new LockDisposer(lock.readLock())) {
clientCount++;
}
try (LockDisposer l = new LockDisposer(lock.writeLock())) {
return field.getValue();
}
I suspect a LOT of people will be doing something similar to this hack
if this proposal is adopted. To make it much cleaner, you could first
adjust this proposal so that the try statement can take an expression
that returns a Disposable, and then you could adjust the Lock classes
so that a) lock() returns this and b) they implement Disposable, at
which point you could have:
try (lock.readLock().lock()) {
clientCount++;
}
try (lock.writeLock().lock()) {
return field.getValue();
}
Which is pretty clean. Note that Josh mentioned the possibility of
try() taking an expression in his proposal. This is why.
Jeremy
More information about the coin-dev
mailing list