J.Olufsen
J.Olufsen

Reputation: 13915

How to communicate to other threads using shared resource?

There is auction server which accepts clients and make for each socket connection a new thread to serve client. Each thread has it's protocol. Server have only one instance of Auction object. Auction object holds list of Lot objects. Auction object is passed as argument to client thread. Protocol has to have a way to put a bid and notify all client threads somehow. The makeBid method exists in Lot and it puts bid to list of bids. The next step is to notify all client thread form makeBid method. What is the best practice to do this? enter image description here

I tried to use a field (MSG) in Thread to hold a message. Thread checks if !MSG.isEmpty() while in run(). If !MSG.isEmpty() then ClientThread prints to socket this MSG. I think there is a better solution.


public class ClientServiceThread extends Thread  {
public String PRINT_NEW_MSG = "";
while (m_bRunThread) {

                if(!PRINT_NEW_MSG.isEmpty()){
                    out.println("PRINT_NEW_MSG: "+PRINT_NEW_MSG);
                    PRINT_NEW_MSG = "";
                String clientCommand = in.readLine();
                                 ...
            }
}

Upvotes: 0

Views: 268

Answers (2)

Michael
Michael

Reputation: 35341

You could create a subscription design that calls a lotUpdated() method whenever a client places a bid on a Lot. Each ClientThread would subscribe to the Lots that it wants to be notified of.

public class Lot {
  private List<ClientThread> clients = new ArrayList<ClientThread>();
  private List<Integer> bids = new ArrayList<Integer>();

  public synchronized void subscribe(ClientThread t){
    clients.add(t);
  }

  public synchronized void unsubscribe(ClientThread t){
    clients.remove(t);
  }

  public synchronized void makeBid(int i){
    bids.add(i);
    for (ClientThread client : clients){
      client.lotUpdated(this);
    }
  }
}

public ClientThread {
  public void lotUpdated(Lot lot){
    //called when someone places a bid on a Lot that this client subscribed to
    out.println("Lot updated");
  }
}

Upvotes: 1

David Mathias
David Mathias

Reputation: 335

Better you can synchronize the "makeBid" method using this object. Then call notifyAll method

at the end of makeBid.

Upvotes: 1

Related Questions