I need to create an application that will receive data over the network and pass it on to other classes for processing. I decided to use the observer template for this, but I ran into a problem. Multiple connections can arrive at the same time, so for each one I create a new instance of the class, accepting the connection and processing the data. But how then is it right to attach observers to the server class. To use something in an additional thread, the variable must be static or final. The final is not suitable, because for each connection a new server instance. And static confuses me, I do not quite understand how it works.
Below is the code, tell me, please, how to organize it correctly, so that during operation no garbage got out.
This is the main class
public class Main { static Server server = new Server(); public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { try { int i = 0; // счётчик подключений ServerSocket socket = new ServerSocket(3013); while(true)// слушаем порт { server = new Server(i, socket.accept()); i++; } } catch(Exception e){ System.out.println("init: " + e); } } }).start(); ConcreteObserver observer = new ConcreteObserver(server); } }
This is a server class.
public class Server extends Thread implements Observable { Socket socket; int num; List<String> string = null; private static List<Observer> observers; public Server() { observers = new ArrayList<Observer>(); } public Server(int num, Socket s) { this.num = num; this.socket = s; start(); } public void run() { // doing something notifyObservers(); } public void addObserver(Observer o) { if (o != null) { observers.add(o); } } public void deleteObserver(Observer o) { if (o != null) { observers.remove(o); } } public void notifyObservers() { for (Observer observer : observers) { observer.update(listMettUnits); } } }
And the observer class
public class ComputeAll implements Observer { private Server server = null; public ComputeAll(Server server) { this.server = server; server.addObserver(this); } public void update(List<String> list) { // doing something } }