简体   繁体   中英

Synchronized in a Java thread

My program is a client connected to multiple servers. I save connection objects to all servers in a static map object:

server1 -> connection1
server2 -> connection2
serverN -> connectionN

public class CacheConnection {

    private final static Map cacheConnection = new HashMap();

    public static void add(String serverName, Socket sock) {
        synchronized (cacheConnection) {
            cacheConnection.put(serverName, sock);
        }
    }

    public static Socket get(String serverName) {
        return (Socket) cacheConnection.get(serverName);
    }

    ..
}

I have many threads getting connections from this map to communicate with the servers. How can I ensure a connection can only be used by one thread at a time?

For example, I want to be sure thread 1 and thread 2 cannot use connection 1 at the same time.

I am not completely sure, what you want. I assume that you want to guarantee that only one thread at a time accesses one particular server.

If your connection is something like a socket, then you can use it as a lock in a synchronization statement :

private void send(Connection c, Data d) {
  synchronized (c) {
    // for each connection object, only one thread may be inside this block.
    // all other threads wait until the thread currently in this block exits it.
    c.send(d);
  }
}

// somewhere else ...

Data data = determineDataToSend()
Connection connection = map.get(key);
send(connection, data)

You can put the logic also into a decorator for the connection. This is especially useful if your connection has more than one method that send or receive (eg, because you use a higher abstraction level like RMI):

public interface PowerfulConnection {
  public void doA();
  public int doB(ParameterForB param);
}

public class ConnectionImpl implements PowerfulConnection {
   // handles the actual connection
}

/**
 * This method is a decorator for PowerfulConnection that synchronizes all method accesses.
 */
public class SynchronizedConnection implements PowerfulConnection {
  private PowerfulConnection target;

  public SynchronizedConnection(PowerfulConnection target) {
    if (target == null) throw new NullPointerException();
    this.target = target;
  }

  public synchronized void doA() {
    target.doA();
  }

  public synchronized int doB(ParameterForB param) {
    return target.doB(param);
  }
}

If you are using the decorator approach, then the only thing you need to change is the instance creation. Instead of:

private void connect(key, connectionParams) {
  map.put(key, new ConnectionImpl(connectionParams));
}

use

private void connect(key, connectionParams) {
  map.put(key, new SynchronizedConnection(new ConnectionImpl(connectionParams)));
}

Or, in your initial example, the get method could just remove the connection from the map. Of course, that means the client would have to be sure (probably in a finally block, to call add again, when done)

Then have wait and notify loops for when a client comes in to ask for a connection, and it's not there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM