0

I am learning multithread about synchronization.

Require: Write mutex class in JAVA which has 2 methods

Class Mutex {

    acquire();

    release();
}

Can anybody help me for this. Thank in advance.

Hnib
  • 133
  • 9

2 Answers2

2

here Tanembaum at page 128 there is the mutex example from the inventor of semaphores. It's in C, but it's very simple and readable, it is not difficult to "translate" it in java

Object lock = new Object();
int queue = 0


    void acquire() throws InterruptedException{
    synchronized (lock){
        while (queue > 0) {
            lock.wait();
        }
        queue ++;
    }
}

void release(){
    synchronized (lock){
        queue --;
        lock.notify();
    }
}

this is a binary mutex; by changing the number in the while condition, you can choose the max number of concurrent accesses

Michele Da Ros
  • 856
  • 7
  • 21
1

Take a look here:

http://www.vogella.com/tutorials/JavaConcurrency/article.html#memorymodel_synchronized

I used it everytime I needed it. If you used shared variable between different threads you have to synchronize the modification.

chokdee
  • 446
  • 4
  • 13