I have a situation where I want to access threads in Waiting or Blocked state and destroy their connections to an external Server. Is this possible without making a global variable that stores those connections? Can I access those connection objects from another Thread in Java?
我有一種情況,我想訪問處於等待或阻塞狀態的線程並破壞它們與外部服務器的連接。如果沒有創建存儲這些連接的全局變量,這可能嗎?我可以從Java中的另一個線程訪問這些連接對象嗎?
To be more specific:
更具體:
I had connections with a RabbitMQ Server which throttles connections when it reaches a particular memory threshold which in my case it has reached. So, the client hangs waiting for RabbitMQ server to unblock it which would never happen in my use case. So, I want to close those particular connections. I have tried sending interrupts to those threads but it seems like those threads are not recognizing interrupts and remain hanged indefinitely.
我與RabbitMQ服務器建立了連接,當它到達特定的內存閾值時會限制連接,在我的情況下它達到了這個閾值。因此,客戶端掛起等待RabbitMQ服務器解除阻塞,這在我的用例中永遠不會發生。所以,我想關閉那些特定的聯系。我曾嘗試向這些線程發送中斷,但似乎這些線程沒有識別中斷並且無限期地被掛起。
1 个解决方案
#1
1
Resources do not belong to threads, Java doesn't care which thread has a reference to a Socket object for example.
資源不屬於線程,Java並不關心哪個線程具有對Socket對象的引用。
You'll need a central ConcurrentHashMap or something like that to make your connection objects visible to the outside. Or you can interrupt threads and let them kill the connection, since almost all things wait / blocking do throw InterruptedExceptions when you do so.
您需要一個中央ConcurrentHashMap
或類似的東西,以使您的連接對象對外部可見。或者您可以中斷線程並讓它們終止連接,因為幾乎所有等待/阻塞的事情都會在您執行此操作時拋出InterruptedExceptions。
So in case you know which thread it is, it's typically something like
所以,如果你知道它是哪個線程,它通常是這樣的
Socket socket = connectionMap.get(thread);
socket.close();
or
thread.interrupt();
which would go together with thread code like
這將與線程代碼一起使用
Thread myThread = Thread.currentThread();
connect();
while(!myThread.isInterrupted()) {
try {
doStuff();
} catch (InterruptedException e) {
myThread.interrupt(); // exception does not set interrupted state
}
}
disconnect();