Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
56f23683c6821527a168273cf0cb16295f014958
[simgrid.git] / org / simgrid / msg / Sem.java
1 /*\r
2  * Simple semaphore implementation, from Doug Lea (public domain)\r
3  *\r
4  * Copyright 2006,2007,2010 The SimGrid Team           \r
5  * All right reserved. \r
6  *\r
7  * This program is free software; you can redistribute \r
8  * it and/or modify it under the terms of the license \r
9  *(GNU LGPL) which comes with this package. \r
10  */  \r
11 \r
12 package org.simgrid.msg;\r
13 \r
14 \r
15 /**\r
16  *\r
17  * @author lbobelin\r
18  */\r
19 public class Sem {\r
20         /******************************************************************/ \r
21         /* Simple semaphore implementation, from Doug Lea (public domain) */ \r
22         /******************************************************************/ \r
23         private int permits_;\r
24 \r
25     /**\r
26      *\r
27      * @param i\r
28      */\r
29     public Sem(int i) {\r
30                 permits_ = i;\r
31         } \r
32 \r
33     /**\r
34      *\r
35      * @throws java.lang.InterruptedException\r
36      */\r
37     public void acquire() throws InterruptedException {\r
38                 if (Thread.interrupted())\r
39                         throw new InterruptedException();\r
40 \r
41                 synchronized(this) {\r
42                         try {\r
43                                 while (permits_ <= 0)\r
44                                         wait();\r
45                                 --permits_;\r
46                         }\r
47                         catch(InterruptedException ex) {\r
48                                 notify();\r
49                                 throw ex;\r
50                         }\r
51                 }\r
52         }\r
53 \r
54     /**\r
55      *\r
56      */\r
57     public synchronized void release() {\r
58                 ++(this.permits_);\r
59                 notify();\r
60         } \r
61\r