Relate 2 objects to a single reference / key

4

I have a while(true) that accepts multiple connections ( Socket and ServerSocket ). Each connection is passed to a Handling object that handles its read / write data. This Handling is passed to a Thread so you can accept connections and read / write simultaneously .

I wanted to know if there is any way to save these 2 objects ( Treatment and Thread ) so that they have a identification only key , so when I need to close them , call this key, receive the 2 objects and close them individually.

    
asked by anonymous 13.08.2015 / 18:11

1 answer

3

You can make a tuple class (for 2 elements). As described here: link

With this class you even have the calculation of the hash taking into account the two objects. Modify it for your reality, if necessary.

For this case it would look like this:

Map<Integer, Tuple<Tratamento,Thread>> objs = new HashMap<Integer, Tuple<Tratamento,Thread>>();

You will probably have to have some kind of object that stores keys that have not yet been closed.

If more than one thread goes to access HashMap, then you will need to use a thread-safe version, called ConcurrentHashMap.

Update - Usage example

Below is an example of how to use it. Note that I used Integer, String instead of Treatment and Thread.

    HashMap<Integer, Tuple<Integer,String>> objs = new HashMap<Integer, Tuple<Integer, String>>();
    objs.put(10,new Tuple<Integer, String>(150,"ABC"));
    objs.put(11,new Tuple<Integer, String>(300,"DEF"));

    Tuple<Integer,String> tuple = objs.get(10);

    System.out.println(tuple.x);
    System.out.println(tuple.y);


    tuple = objs.get(11);

    System.out.println(tuple.x);
    System.out.println(tuple.y);

If you want, simply change the attributes of the class Tuple from x and y to Treatment and Thread. However, your class will no longer be generic. If you need it only for this part of your code, swap for clarity.

    
13.08.2015 / 18:40