Mutex: Difference between revisions

1,020 bytes added ,  14 years ago
Added Java
(Grammar)
(Added Java)
Line 181:
 
<code>when</code> blocks and <code>Ref.whenResolved</code> return a ''promise'' for the result of the deferred action, so the mutex here waits for the gratuitously complicated increment to complete before becoming available for the next action.
=={{header|Java}}==
{{works with|Java|1.5+}}
 
Java 5 added a <code>Semaphore</code> class which can act as a mutex (as stated above, a mutex is "a variant of semaphore with ''k''=1").
<lang java5>import java.util.concurrent.Semaphore;
 
public class VolatileClass{
public Semaphore mutex = new Semaphore(1); //also a "fair" boolean may be passed which,
//when true, queues requests for the lock
public void needsToBeSynched(){
//...
}
//delegate methods could be added for acquiring and releasing the mutex
}</lang>
Using the mutex:
<lang java5>public class TestVolitileClass{
public static void main(String[] args){
VolatileClass vc = new VolatileClass();
vc.mutex.acquire(); //will wait automatically if another class has the mutex
//can be interrupted similarly to a Thread
//use acquireUninterruptibly() to avoid that
vc.needsToBeSynched();
vc.mutex.release();
}
}</lang>
=={{header|Objective-C}}==
 
Anonymous user