java - Implement semaphores using the monitor concept -


i trying implement semaphores using monitor concept in java. i.e java class implements weak counting semaphore (using methods init, signal , wait)

can tell me if class correct (if not problem):

class mymonitor {     int counter = 0;      //init     public mymonitor( int init )     {         counter = init;     }      //signal     public synchronized void s()     {         counter++;         notify();     }      //wait     public synchronized void w()     {         if( counter == 0 )         {             try             {                 wait();             }             catch(interruptedexception e) { }         }          counter--;     } } 

if correct, give me idea of how can test class.

it should (with while, not if):

class yourmonitor {     int counter = 0;      //init     public mymonitor( int init )     {         counter = init;     }      //signal     public synchronized void s()     {         counter++;         notifyall();     }      //wait     public synchronized void w()  throws interruptedexception     {         while ( counter <= 0 )         {             wait();         }          counter--;     } } 

how test:

public class testyoursemaphore {     private static final int cnt = 100000;      private int x = 0;     private yoursemaphore s = new yoursemaphore();      public void run() throws interruptedexception     {         thread t1 = new thread(new myrunnable());         thread t2 = new thread(new myrunnable());         thread t2 = new thread(new myrunnable());          t1.start();         t2.start();         t3.start();          t1.join();         t2.join();         t3.join();           // verify, x has correct value         if (x != 3 * cnt)         {             throw new runtimeexception("race condition error!");         }         system.out.println("finished");     }      private class myrunnable implements runnable     {         @override         public void run()         {             (int = 0; < cnt; i++)             {                 //un-comment use semaphores                 //s.enter();                 x = x + 1;                 //s.leave();             }         }     } } 
  • without semaphore, exception thrown time (almost).
  • with suggested semaphore, exception not thrown.
  • with semaphore, exception thrown (but not without semaphores).

the problem semaphore is:

  1. thread 1 has lock
  2. thread 2 , thread 3 wait()ing
  3. thread 1 calls notifyall()
  4. thread 2 , 3 simultaneously enter critical section, bad :)

Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -