简体   繁体   English

计数器线程请求方法

[英]Counter for requests to methods by threads

I have many threads, that I implement from the main. 我有很多线程,这些线程是我主要实现的。 My purpose is to limit requests to the server (some methods in the sever class), So I put counter before critical sections and before synchronized. 我的目的是将请求限制到服务器(sever类中的某些方法),因此我将计数器放在关键部分之前和同步之前。 I noticed, that the counter only grows up and never decreases... Thats sample of my code: 我注意到,计数器只会增长而不会减少...那就是我的代码示例:

private static int currentRequests;
/**
 * @param newStock StockState we are adding to the exist stock states.
 */
public  void addStock(StockState newStock) throws OutOfBoundConcurrentException
{
    if(currentRequests>MaxConcurrentRequests)
        throw new OutOfBoundConcurrentException();          
    System.out.println(currentRequests++);
    synchronized (this) {
    int indx=checkExistStock(newStock.getStockName());          
    if(indx<0)
    {
        stockStates.add(newStock);
        currentRequests--;
        return;
    }
    else
    {
        stockStates.get(indx).updateStockValueFromStockStateClass(newStock.getStockCurrentValue());
    }
    }
    currentRequests--;
}   

In case you have many instances of the class that has the method 如果您有该方法的类的许多实例

void addStock(StockState newStock)

Your counter is broken in regard to thread safety and the behavior of the counter is not guaranteed. 您的计数器在线程安全方面已损坏,并且不能保证其行为。 Threads that use different instances of the class will not block each other. 使用该类的不同实例的线程不会互相阻塞。 To fix it you can synchronize the java class instance itself instead. 要解决此问题,您可以改为同步Java类实例本身。

synchronized(OuterClass.class)

If you are using the lock only for the counter it is much preferred to use an instance of 如果仅将锁用于计数器,则最好使用的实例

AtomicLong

It is non-blocking and perform better in an order of magnitudes. 它是非阻塞的,并且在一个数量级上表现更好。

You can do it in 2 ways. 您可以通过2种方式来实现。

(1) Java AtomicInteger or AtomicLong : (1)Java AtomicIntegerAtomicLong

Here you can use decrementAndGet() method in both classes to achieve your goal. 在这里,您可以在两个类中使用decrementAndGet()方法来实现您的目标。 Both are synchronization free (non-blocking) operations, achieved by using Compare And Swap algorithms. 两者都是无同步(非阻塞)操作,通过使用Compare And Swap算法即可实现。

(2) Java Semaphore : (2)Java 信号量

You can easily use this one, which is specifically tailored for your kind of requirements requirement ( controlling #no of threads ). 您可以轻松地使用此代码,它是专门针对您的各种需求量身定制的( 控制#no线程 )。 In this way, you don't need to reinvent things and also can enjoy the non-blocking nature (same as #1). 这样,您无需重新发明事物,还可以享受非阻塞性(与#1相同)。 You can use acquire() and release() methods to control the count. 您可以使用acquire()release()方法来控制计数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM