views:

131

answers:

4

I was pondering language features and I was wondering if the following feature had been implemented in any languages.

A way of declaring that an object may only be accessed within a Mutex. SO for example in java you would only be able to access an object if it was in a synchrnoised block and in C# a Lock.

A compiler error would ensue if the object was used outside of a Mutex block.

Any thoughts?

UPDATE

I think some people have misunderstood the question, I'm not asking if you can lock objects, I'm asking if there is a mechanism to state at declaration of an object that it may only be accessed from within a lock/synchronised statement.

A: 

In Java you can add the synchronized keyword to a method, but that is only syntactic sugar to wrapping the entire method body in a synchronized(this)-block (for non-static methods).

So for Java there is no language construct that enforces that behavior. You can try to .wait() on this with a zero timeout to ensure that the calling code has acquired the monitor, but that's just checking after-the-fact

Joachim Sauer
A: 

In Objective-C, you can use the @property and @synthesize directives to let the compiler generate the code for accessors. By default they are protected by mutex.

mouviciel
+1  A: 

There are two ways to do that.

Your program either refuses to run a method unless the protecting mutex is locked by the calling thread (that's a runtime check); or it refuses to compile (that's a compile time check).

First way is what C# lock does.

Second method requires a compiler able to evaluate every execution path possible. It's hardly feasible.

Quassnoi
A: 

Demanding locks on everything as you describe would create the potential for deadlocks, as one might be forced to take a lock sooner than one would otherwise.

That said, there are approaches similar to what you describe - Software Transactional Memory, in particular, avoids the deadlock issue by allowing rollbacks and retries.

bdonlan