When you call connection.sendPacket(packet) your packet is not necessarily sent immediately. It is actually added to a queue and then scheduled to be sent to the server by another thread so that your code doesn’t block. So let’s unroll the loop and consider the following example of what is probably happening:
packet.setTo(“user1”);
connection.sendPacket(packet); // Now the queue has 1 packet set for user1
packet.setTo(“user2”);
connection.sendPacket(packet); // Now the queue has 2 packets, but since both of them are the same instance, both are now set to user2
packet.setTo(“user3”);
connection.sendPacket(packet); // Now the queue has 3 copies of the same packet and all are now set for user3
The packet writer thread now wakes up, sends those 3 copies of the packet to the server, and clears the queue
packet.setTo(“user4”);
connection.sendPacket(packet); // Now the queue has 1 packet set for user4
The packet writer thread now wakes up and sends the packet to user4
So as you can see, due to the background sending thread, whether or not your code works depends on when the thread is given CPU time to process the packets. Whenever I needed to send out a packet to many users, I just created a new packet for each send and never had any problems.