Allora ho il seguente problema...
Ho la seguente classe:
Il thread è interrombile nei casi "normali" con il metodo stop():codice:public class SocketConnectionsAccepter implements Runnable { private boolean stopped; private int port; private ServerSocket serverSocket; private LinkedBlockingQueue<Socket> socketsAcceptedQueue; public SocketConnectionsAccepter(int port,LinkedBlockingQueue<Socket> socketsAcceptedQueue) throws IOException { this.port = port; this.socketsAcceptedQueue = socketsAcceptedQueue; this.stopped = true; } public boolean isStopped() { return this.stopped; } public void stop() throws IOException { if (!isStopped()) { stampa("Actually is running"); this.serverSocket.close(); this.stopped = true; } else stampa("Already stopped"); } @Override public void run() { // TODO Auto-generated method stub stampa("Trying to start"); if (isStopped()) { stampa("Actually is stopped"); try { this.stopped = false; this.serverSocket = new ServerSocket(this.port); stampa("Started"); while(!isStopped()) { stampa("Accepting"); Socket temp = serverSocket.accept(); stampa("Socket accepted. Putting in the socket Queue"); //socketsAcceptedQueue.put(temp); preferibile ma problemi di interruzione socketsAcceptedQueue.offer(temp, 500, TimeUnit.MILLISECONDS); } } catch (IOException e) { stampa("ServerSocket was waiting. Abruptly stopped"); } catch (InterruptedException e) { // TODO Auto-generated catch block stampa("Abruptly interrupted"); } finally { stampa("Stopped"); } } else stampa("Already running"); } private void stampa(String string) { System.out.println("Connection Accepter: " + string); } }
- Nell'eventualità che non sia bloccato esce dal ciclo e termina l'esecuzione normalmente
- Nel caso in cui sia bloccato in un Accept() la chiusura del serverSocket avvia il lancio di un eccezione che viene catturata silenziosamente. Dopo di che termina l'esecuzione...
Il problema che osservo è il seguente (probabilmente ce ne sono altri che non ho visto anche).
Avvio il thread nel seguente modo:
Supponiamo che il thread, che viaggia in parallelo, i fermi in una accept();codice:ExecutorService starter = Executors.newCachedThreadPool(); starter.execute(accepter);
Nel momento in cui chiudo lo starter (starter.shutdownNow()), questo lancia un interruzione al thread. Quest ultimo però la ignora! (perchè il blocco nell'accept non è uno dei casi interrompibili!
Questo risulta un problema perchè se non chiudo l'esecutore del thread l'esecuzione del thread da cui faccio il forking (es Main) non si chiude normalmente! Devo necessariamente mettere sequenzialmente i seguenti?
accepter.stop();
starter.shutdownNow();
Non mi sa molto di una cosa "pulita". Come posso/devo fare? Vi ringrazio in anticipo

Rispondi quotando