Semaphores implemented in Java

Source: Internet
Author: User

Http://www.cnblogs.com/bronte/articles/2321188.html

The semaphore Implementation described in this article is based on synchronized, wait () and policy/policyall (). This is a typical implementation method before Java is released. many such cases can be found in the source code of eclipse. Several implementation classes in eclipse will also be analyzed in the following example.

Note: The semaphore Implementation described here is based on the Java language mechanism for synchronous operations between multiple threads. Therefore, for S, P (S), V (s) the introduction of other concepts will be combined with the content of this article, make appropriate adjustments, readers can read the semaphore chapter in the relevant books of the operating system to obtain the standard definition.

 

* Content

--- Semaphore Introduction

--- Typical cases

 

* Semaphore Overview

--- Generally, a non-negative integer is called semaphore and expressed as S.

S can be understood as the number of available resources. process issues are not involved here, so we assume S> = 0.

--- The synchronization mechanism implemented by S is represented as PV primitive operation

P (S): If S = 0, the thread enters the waiting queue; otherwise,-S;

V (s): ++ S, wake up the thread in the waiting state.

(Note: P is the passeren of Dutch, equivalent to the English pass, V is the verhoog of Dutch, equivalent to the incremnet in English ).

 

* Case

1) typical implementation

This program is derived from a concurrent book from IBM and implements the Count semaphores {S | S ε {0, N }}and binary semaphores (S = {0, 1 })

public abstract class Semaphore {private int value = 0;public Semaphore() {}public Semaphore(int initial) {if (initial >= 0)value = initial;elsethrow new IllegalArgumentException("initial < 0");}public final synchronized void P() throws InterruptedException {while (value == 0)wait();value--;}protected final synchronized void Vc() {value++;notifyAll();}protected final synchronized void Vb() {value++;notifyAll();if (value > 1)value = 1;}public abstract void V();public String toString() {return ".value=" + value;}}public final class BinarySemaphore extends Semaphore {public BinarySemaphore() {super();}public BinarySemaphore(int initial) {super(initial);if (initial > 1)throw new IllegalArgumentException("initial > 1");}public final synchronized void V() {super.Vb();}}public final class CountingSemaphore extends Semaphore {public CountingSemaphore() {super();}public CountingSemaphore(int initial) {super(initial);}public final synchronized void V() {super.Vc();}}

2) Implement read/write locks

Eclipse uses it to solve the synchronization problem of log operation related classes in map and array.

/******************************************************************************* * Copyright (c) 2008, 2011 IBM Corporation and others * All rights reserved. This program and the accompanying materials are made * available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/package org.eclipse.equinox.log.internal;public class BasicReadWriteLock {private int currentReaders = 0;private int writersWaiting = 0;private boolean writing = false;public synchronized void readLock() {while (writing || writersWaiting != 0) {try {wait();} catch (InterruptedException e) {// reset interrupted state but keep waitingThread.currentThread().interrupt();}}currentReaders++;}public synchronized void readUnlock() {currentReaders--;notifyAll();}public synchronized void writeLock() {writersWaiting++;while (writing || currentReaders != 0) {try {wait();} catch (InterruptedException e) {// reset interrupted state but keep waitingThread.currentThread().interrupt();}}writersWaiting--;writing = true;}public synchronized void writeUnlock() {writing = false;notifyAll();}}

3) latency semaphores

The highlight of this semaphore is in acquire (long delay ).

/*************************************** **************************************** * Copyright (c) 2003,200 6 IBM Corporation and Others. * All Rights Reserved. this program and the accompanying materials * are made available under the terms of the eclipse Public License V1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ** contributors: * IBM Corporation-initial API and implementation ******************************** **************************************** * *****/package Org. eclipse. core. runtime. internal. adaptor;/*** internal class. */public class semaphore {protected long configurations; Public semaphore (INT count) {configurations = count ;}/ *** attempts to acquire this semaphore. returns only when the semaphore has been acquired. */Public synchronized void acquire () {While (true) {If (notifications> 0) {notifications --; return;} Try {Wait ();} catch (interruptedexception E) {// ignore }}/ *** attempts to acquire this semaphore. returns true if it was successfully acquired, * and false otherwise. */Public synchronized Boolean acquire (long delay) {// if a negative number is input, it is used to determine whether the resource has been occupied long start = system. currenttimemillis (); long timeleft = delay; while (true) {If (notifications> 0) {notifications --; return true;} If (timeleft <= 0) // try {Wait (timeleft);} catch (interruptedexception e) {// ignore} timeleft = start + delay-system. currenttimemillis () ;}} public synchronized void release () {notifications ++; policyall () ;}// for debug onlypublic string tostring () {return "semaphore (" + notifications + ")"; // $ NON-NLS-1 $ // $ NON-NLS-2 $}

 

 

* Conclusion

--- Using the Java object lock and the semaphore simulated by Wait/notify mechanism, multiple forms can be presented to meet various mutex requirements.

--- The example given in this article has universal applicability. In practice, We Can Customize various semaphore implementations as needed.

--- Jdk1.5 provides another implementation mechanism of semaphore.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.