PageRenderTime 54ms CodeModel.GetById 13ms app.highlight 36ms RepoModel.GetById 2ms app.codeStats 0ms

/hazelcast/src/test/java/com/hazelcast/core/SemaphoreTest.java

https://bitbucket.org/gabral6_gmailcom/hazelcast
Java | 303 lines | 266 code | 17 blank | 20 comment | 4 complexity | fad56151d1cd49ef8e7f429058a4eed1 MD5 | raw file
  1/*
  2 * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
  3 *
  4 * Licensed under the Apache License, Version 2.0 (the "License");
  5 * you may not use this file except in compliance with the License.
  6 * You may obtain a copy of the License at
  7 *
  8 * http://www.apache.org/licenses/LICENSE-2.0
  9 *
 10 * Unless required by applicable law or agreed to in writing, software
 11 * distributed under the License is distributed on an "AS IS" BASIS,
 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13 * See the License for the specific language governing permissions and
 14 * limitations under the License.
 15 */
 16package com.hazelcast.core;
 17
 18import com.hazelcast.config.Config;
 19import com.hazelcast.config.SemaphoreConfig;
 20import com.hazelcast.impl.GroupProperties;
 21import org.junit.*;
 22import org.junit.runner.RunWith;
 23
 24import java.util.Random;
 25import java.util.concurrent.*;
 26
 27import static org.junit.Assert.*;
 28
 29@RunWith(com.hazelcast.util.RandomBlockJUnit4ClassRunner.class)
 30public class SemaphoreTest {
 31
 32    @BeforeClass
 33    @AfterClass
 34    public static void init() throws Exception {
 35        System.setProperty(GroupProperties.PROP_WAIT_SECONDS_BEFORE_JOIN, "1");
 36        System.setProperty(GroupProperties.PROP_VERSION_CHECK_ENABLED, "false");
 37        Hazelcast.shutdownAll();
 38    }
 39
 40    @Before
 41    public void setUp() throws Exception {
 42        Hazelcast.shutdownAll();
 43    }
 44
 45    @After
 46    public void tearDown() throws Exception {
 47        Hazelcast.shutdownAll();
 48    }
 49
 50    @Test
 51    public void testSemaphoreWithTimeout() {
 52        SemaphoreConfig semaphoreConfig = new SemaphoreConfig("default", 10);
 53        Config config = new Config();
 54        config.addSemaphoreConfig(semaphoreConfig);
 55        HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
 56        ISemaphore semaphore = instance.getSemaphore("test");
 57        //Test acquire and timeout.
 58        try {
 59            assertEquals(10, semaphore.availablePermits());
 60            semaphore.tryAcquire();
 61            assertEquals(9, semaphore.availablePermits());
 62            assertEquals(false, semaphore.tryAcquire(10, 10, TimeUnit.MILLISECONDS));
 63            assertEquals(9, semaphore.availablePermits());
 64            semaphore.release();
 65            //Test acquire and timeout and check for partial acquisitions.
 66            assertEquals(10, semaphore.availablePermits());
 67            assertEquals(false, semaphore.tryAcquire(20, 10, TimeUnit.MILLISECONDS));
 68            assertEquals(10, semaphore.availablePermits());
 69        } catch (Throwable e) {
 70            e.printStackTrace();
 71            fail(e.getMessage());
 72        }
 73    }
 74
 75    @Test
 76    public void testSimpleSemaphore() {
 77        SemaphoreConfig semaphoreConfig = new SemaphoreConfig("default", 1);
 78        Config config = new Config();
 79        config.addSemaphoreConfig(semaphoreConfig);
 80        HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
 81        ISemaphore semaphore = instance.getSemaphore("test");
 82        assertEquals(1, semaphore.availablePermits());
 83        semaphore.tryAcquire();
 84        assertEquals(0, semaphore.availablePermits());
 85        semaphore.release();
 86        assertEquals(1, semaphore.availablePermits());
 87        semaphore.tryAcquire();
 88        assertEquals(0, semaphore.availablePermits());
 89        semaphore.release();
 90        assertEquals(1, semaphore.availablePermits());
 91        semaphore.tryAcquire();
 92        assertEquals(0, semaphore.availablePermits());
 93        semaphore.release();
 94        assertEquals(1, semaphore.availablePermits());
 95        semaphore.tryAcquire();
 96        assertEquals(0, semaphore.availablePermits());
 97        semaphore.release();
 98        assertEquals(1, semaphore.availablePermits());
 99    }
100
101    @Test
102    public void testSemaphoreReducePermits() {
103        SemaphoreConfig semaphoreConfig = new SemaphoreConfig("default", 10);
104        Config config = new Config();
105        config.addSemaphoreConfig(semaphoreConfig);
106        HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
107        ISemaphore semaphore = instance.getSemaphore("test");
108        assertEquals(10, semaphore.availablePermits());
109        semaphore.reducePermits(1);
110        assertEquals(9, semaphore.availablePermits());
111        semaphore.tryAcquire(9);
112        assertEquals(0, semaphore.availablePermits());
113        semaphore.reducePermits(8);
114        assertEquals(-8, semaphore.availablePermits());
115        semaphore.release();
116        assertEquals(-7, semaphore.availablePermits());
117        semaphore.release(8);
118        assertEquals(1, semaphore.availablePermits());
119    }
120
121    @Test
122    public void testSemaphoreDisconnect() throws InterruptedException {
123        SemaphoreConfig semaphoreConfig = new SemaphoreConfig("default", 10);
124        Config config = new Config();
125        config.setProperty(GroupProperties.PROP_CONNECTION_MONITOR_INTERVAL, "1");
126        config.setProperty(GroupProperties.PROP_CONNECTION_MONITOR_MAX_FAULTS, "1");
127        config.addSemaphoreConfig(semaphoreConfig);
128        HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(config);
129        HazelcastInstance instance2 = Hazelcast.newHazelcastInstance(config);
130        ISemaphore semaphore1 = instance1.getSemaphore("test");
131        ISemaphore semaphore2 = instance2.getSemaphore("test");
132        assertEquals(10, semaphore1.availablePermits());
133        semaphore1.tryAcquireAttach(5);
134        semaphore1.reducePermits(1);
135        instance1.getLifecycleService().kill();
136        Thread.sleep(500);
137        assertEquals(9, semaphore2.availablePermits());
138    }
139
140    @Test
141    public void testSemaphorePeerDisconnect() throws InterruptedException {
142        SemaphoreConfig semaphoreConfig = new SemaphoreConfig("default", 10);
143        Config config = new Config();
144        config.addSemaphoreConfig(semaphoreConfig);
145        HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(config);
146        HazelcastInstance instance2 = Hazelcast.newHazelcastInstance(config);
147        ISemaphore semaphore1 = instance1.getSemaphore("test");
148        ISemaphore semaphore2 = instance2.getSemaphore("test");
149        semaphore2.tryAcquireAttach(5);
150        int result = semaphore1.availablePermits();
151        int expectedResult = 5;
152        assertEquals(expectedResult, result);
153        final CountDownLatch latch = new CountDownLatch(1);
154        instance1.getCluster().addMembershipListener(new MembershipListener() {
155            public void memberAdded(MembershipEvent membershipEvent) {
156            }
157
158            public void memberRemoved(MembershipEvent membershipEvent) {
159                latch.countDown();
160            }
161        });
162        instance2.getLifecycleService().shutdown();
163        assertTrue(latch.await(5, TimeUnit.SECONDS));
164        expectedResult = 10;
165        result = semaphore1.availablePermits();
166        assertEquals(expectedResult, result);
167    }
168
169    @Test
170    public void testAsyncAcquire() throws Exception {
171        final ISemaphore semaphore = Hazelcast.getSemaphore("test");
172        assertEquals(0, semaphore.availablePermits());
173        final Future f1 = semaphore.acquireAsync();
174        Thread thread = new Thread() {
175            @Override
176            public void run() {
177                for (; ; ) {
178                    try {
179                        f1.get(1, TimeUnit.SECONDS);
180                        break;
181                    } catch (InterruptedException e) {
182                        //expected
183                        semaphore.release();
184                        assertFalse(f1.cancel(false));
185                        break;
186                    } catch (ExecutionException e) {
187                        // not gonna happen
188                    } catch (TimeoutException e) {
189                        // keep trying
190                    }
191                }
192            }
193        };
194        assertEquals(0, semaphore.availablePermits());
195        thread.start();
196        Thread.sleep(3500);
197        thread.interrupt();
198        assertEquals(0, semaphore.availablePermits());
199    }
200
201    @Test
202    public void testSemaphoreIncreasePermits() {
203        SemaphoreConfig semaphoreConfig = new SemaphoreConfig("default", 1);
204        Config config = new Config();
205        config.addSemaphoreConfig(semaphoreConfig);
206        HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
207        ISemaphore semaphore = instance.getSemaphore("test");
208        assertEquals(1, semaphore.availablePermits());
209        semaphore.release();
210        assertEquals(2, semaphore.availablePermits());
211    }
212
213    @Test
214    public void testSemaphoreTryAcquireTimeout() throws InterruptedException {
215        ISemaphore semaphore = Hazelcast.getSemaphore("test");
216        assertEquals(0, semaphore.availablePermits());
217        try {
218            semaphore.tryAcquire(5000, TimeUnit.MILLISECONDS);
219        } catch (InstanceDestroyedException e) {
220            e.printStackTrace();
221        }
222        assertEquals(0, semaphore.availablePermits());
223    }
224
225    @Test
226    public void testMultiInstanceSemaphore() {
227        final Random random = new Random();
228        final int rndTimeMax = 20;
229        int initialPermits = 2;
230        HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(null);
231        HazelcastInstance instance2 = Hazelcast.newHazelcastInstance(null);
232        HazelcastInstance instance3 = Hazelcast.newHazelcastInstance(null);
233        final ISemaphore semaphore1 = instance1.getSemaphore("test");
234        final ISemaphore semaphore2 = instance2.getSemaphore("test");
235        final ISemaphore semaphore3 = instance3.getSemaphore("test");
236        semaphore1.release(initialPermits);
237        assertEquals(initialPermits, semaphore1.availablePermits());
238        assertEquals(initialPermits, semaphore2.availablePermits());
239        assertEquals(initialPermits, semaphore3.availablePermits());
240        Thread thread1 = new Thread() {
241            public void run() {
242                for (int i = 0; i < 100; i++) {
243                    try {
244                        semaphore1.acquire(2);
245                        Thread.sleep(random.nextInt(rndTimeMax));
246                        semaphore1.release(2);
247                        Thread.sleep(random.nextInt(rndTimeMax));
248                    } catch (InterruptedException e) {
249                        fail(e.getMessage());
250                    } catch (InstanceDestroyedException e) {
251                        fail(e.getMessage());
252                    }
253                }
254            }
255        };
256        Thread thread2 = new Thread() {
257            public void run() {
258                for (int i = 0; i < 200; i++) {
259                    try {
260                        semaphore2.acquire();
261                        Thread.sleep(random.nextInt(rndTimeMax));
262                        semaphore2.release();
263                        Thread.sleep(random.nextInt(rndTimeMax));
264                    } catch (InterruptedException e) {
265                        fail(e.getMessage());
266                    } catch (InstanceDestroyedException e) {
267                        fail(e.getMessage());
268                    }
269                }
270            }
271        };
272        Thread thread3 = new Thread() {
273            public void run() {
274                for (int i = 0; i < 300; i++) {
275                    try {
276                        semaphore3.acquire();
277                        Thread.sleep(random.nextInt(rndTimeMax));
278                        semaphore3.release();
279                        Thread.sleep(random.nextInt(rndTimeMax));
280                    } catch (InterruptedException e) {
281                        fail(e.getMessage());
282                    } catch (InstanceDestroyedException e) {
283                        fail(e.getMessage());
284                    }
285                }
286            }
287        };
288        thread1.start();
289        thread2.start();
290        thread3.start();
291        try {
292            thread1.join();
293            thread2.join();
294            thread3.join();
295        } catch (InterruptedException e) {
296            e.printStackTrace();
297            fail();
298        }
299        assertEquals(initialPermits, semaphore1.availablePermits());
300        assertEquals(initialPermits, semaphore2.availablePermits());
301        assertEquals(initialPermits, semaphore3.availablePermits());
302    }
303}