Most of what I'm finding online makes use of ExecutorService
or ScheduledExecutorService
to handle time limited threads. It seems like the 'ScheduledExecutorService` would be the way to go as it can be non blocking?
Does this look about right?
from java.lang import Throwable, Thread
from java.net import Socket, ServerSocket
from java.io import BufferedReader, InputStreamReader, IOException
from java.util.concurrent import ConcurrentLinkedQueue, Executors, TimeUnit
bvm = system.util.globalVarMap("PersistentTCPScannerListener")
SOCKET_RETRY_PERIOD = 30000
SCANNER_CONCURRENT_QUEUE = bvm.setdefault("tcpScannerQueue", ConcurrentLinkedQueue())
TCP_LISTEN_SERVER_PORT = magicPortNumber
TCP_LISTEN_SERVER_HOSTNAME = "serverHostName"
TCPSERVER_POOL_SIZE = 4
class TCPSocketServer(Thread):
MAX_MESSAGE_TIME = 300000
def __int__(self, hostName, port, concurrentQueue, poolSize):
self.setDaemon(1)
self.tcpReadExecutor = Executors.newScheduledThreadPool(poolSize)
self.cq = concurrentQueue
try:
self.serverSocket = ServerSocket(port)
logger.infof("Server listening on port %i", port)
except IOException as ioe:
logger.warn("TCP listener server failed to start", ioe)
self.interrupt()
return
def run(self):
while not self.interrupted():
try:
readerFuture = self.tcpReadExecutor.submit(TCPSocketServerReader(self.serverSocket.accept(), self.cq))
self.tcpReadExecutor.schedule(readerFuture.cancel(True), self.MAX_MESSAGE_TIME, TimeUnit.MILLISECONDS)
except Exception as e:
logger.warn("Jython exception while attempting to monitor TCP socket", shared.later.PythonAsJavaException(e))
except Throwable as t:
logger.warn("Java exception while attempting to monitor TCP socket", t)
self.tcpReadExecutor.shutdown()
self.serverSocket.close()
return
def stop(self):
self.interrupt()
return
class TCPSocketServerReader(Thread):
def __int__(self, socket, concurrentQueue):
self.setDaemon(1)
self.socket = socket
self.cq = concurrentQueue
def run(self):
while not self.interrupted():
try:
reader = BufferedReader(InputStreamReader(self.socket.getInputStream))
while reader:
currentLine = reader.readLine()
if currentLine:
self.cq.offer(currentLine)
except Exception as e:
logger.warn("Jython error while attempting to read TCP Server socket data", shared.later.PythonAsJavaException(e))
except Throwable as t:
logger.warn("Java error while attempting to read TCP Server socket data", t)
finally:
self.socket.close()
return