When developing a singleton class that can be used by multiple threads, I come across the following task:
This leaves the main thread and another thread called the client. The main method first gets an instance, and then clients also get instances. And then the client executes the singleton class method, my debug step shows that the main thread is interrupted to execute the method that the client calls.
How can I guarantee that the client thread executes this method without interrupting the main thread.
Thanks in advance for your efforts.
Cheers Bob
Edit:
public class SingletonEsperEngine { private static SingletonEsperEngine esperEngineObject;
The problem occurs when a client thread calls dataToEsperEngine()
public class Client implements Runnable { Socket mClientConnectionSocket; Connection mCon; //Seperate thread for every client, to handle the communication and event processing //ClientThread clientThread; public static Boolean stopClientThreads = false; public int mMode = CONSTANT.CLIENT_MODE_IDLE; public int mNumberOfThisClient; SingletonEsperEngine mEsperSupport; public Thread t; private String name; public void run() { String tmp = null; int idleTime = CONSTANT.SHORT_IDLE_TIME; while (!stopClientThreads) { try { tmp = null; switch (mMode) { case CONSTANT.CLIENT_MODE_STOP: //This will cause exiting of the while loop and terminates the thread stopClientThreads = true; return; case CONSTANT.CLIENT_MODE_IDLE: //Being lazy break; case CONSTANT.CLIENT_MODE_RECEIVE_STREAM: tmp = receiveMessage(); if (tmp != null) { System.out.println(tmp); mEsperSupport.dataToEsperEngine(tmp, mNumberOfThisClient); } break; } //I am aware of the performance issues //TODO rebuild with execution pool this.t.sleep(idleTime); } catch (InterruptedException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } } return; } Client(Socket cC, String name) { //Save socket (=connection) into the client class mClientConnectionSocket = cC; gui.Debug.logThis("The server made a connection with: " + mClientConnectionSocket.getInetAddress()); mEsperSupport = mEsperSupport.getInstance(); this.name = name; mMode = CONSTANT.CLIENT_MODE_IDLE; t = new Thread(this); t.start(); this.mNumberOfThisClient = Integer.parseInt(name); //Connect the input and output stream try { mCon = new Connection(new BufferedReader(new InputStreamReader(mClientConnectionSocket.getInputStream())), new PrintWriter(mClientConnectionSocket.getOutputStream())); } catch (IOException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } } public String receiveMessage() { String tmp = null; try { tmp = mCon.cFrom.readLine(); } catch (IOException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } return tmp; } }
source share