Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Multithreading 计算未阻塞的活动we请求数_Multithreading_Concurrency - Fatal编程技术网

Multithreading 计算未阻塞的活动we请求数

Multithreading 计算未阻塞的活动we请求数,multithreading,concurrency,Multithreading,Concurrency,在java web服务器上,我想知道是否有任何活动的web请求 我的第一个想法是: public static AtomicInteger count = new AtomicInteger(); public void processRequest() { count.incrementAndGet(); // process my request count.decrementAndGet(); } publ

在java web服务器上,我想知道是否有任何活动的web请求

我的第一个想法是:

    public static AtomicInteger count = new AtomicInteger();

    public void processRequest() {
        count.incrementAndGet();
        // process my request
        count.decrementAndGet();
    }

    public boolean areThereActiveRequests() {
        return 0 == count.get();
    }
这显然会使web请求在递增或递减时相互阻塞(尽管速度很快),等待count()上的锁定,这对于高度可伸缩的服务器是不希望的

请注意,无论是什么代码调用,都可能存在同步问题—它返回的值在返回时可能已过时—但出于我的目的,这没有问题


有什么想法吗?

由于AutomicInteger不需要任何锁,并且利用硬件同步原语,因此您的web请求不会在等待锁时互相阻塞


因此,对于您试图解决的问题,您当前的代码看起来不错。

这最好作为中间件实现。进站时计数器递增,出站时计数器递减。这样,您就不必将应用程序请求处理代码与此监控代码绑定在一起。准确地说,没有对计数的锁定。它在循环中使用CAS。硬件同步原语并不神奇:)它们仍然需要处理争用。根据架构的不同,原子内存操作可能会锁定内存总线,从而限制可伸缩性。同意,但它们比其他锁定机制要好得多。