开发者

How to check if ArrayBlockingQueue is locked or queue element currently processed by thread?

Greetings, I am curious if there is someway to check if ArrayBlockingQuery query is currently locked ? The reason for this : I have a server which is listens to a socket, receives parameters, process them and then returns some result to client. That server(let say开发者_JAVA技巧 it is server A) while processing parameters open session with other server( server B) and then send info to B. Only one session can be created when connecting to B, but A can accept several client connection. Because of that ArrayBlockingQueue is used to stored that parameters and some other thread run through the queue and send them one by one to B.

I need to do that functionality - when ArrayBlockingQueue is empty and nothing is processed in current moment and client data send to A then process immediately - send data to B server, process response from B and then A return response to client if ArrayBlockingQuery is not empty and something is processed then just add parameters to queue and send other response from A to client. Thats why i need to know if there is a way to check if ArrayBlockingQueue is locked or queue element currently processed by thread.

Thank you!


Is there any reason you don't just use a Lock as this is designed for protecting resources which can only be used in one thread at a time.

// in a client connection thread
lock.lock();
try {
    // use connection to server B
} finally {
    lock.unlock();
}

This ensures server B will only be use in one thread at a time and you don't need to add anything to a queue.


Not sure what a ArrayBlockingQuery is, nor does google. Do you mean ArrayBlockingQueue?

An ArrayBlockingQueue is not locked for very long, so this information isn't very useful. However you could obtain the lock via reflection.

You appear to be over thinking your solution.

You want to ensure that server B only get a connection one at a time, and you are using a queue to do this, however you want to way to by-pass this, but this means discarding your one at a time principle.


I would advice against implementing what you described. It would make the code a lot more complex, and it will open up for race conditions unless you synchronize big parts, and really think about what you are doing. It's much better to always handle all events in the same way, that is always queue, even if the "worker thread" is idle. It will then dequeue and work as usual.

Your problem can however be solved by having the "worker thread" updating/using a Semaphore. You can then check if the semaphone has been acquired or not. (By checking available permits)


If you mean ArrayBlockingQueue, it has a (nonblocking) peek() method which

Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜