0

I'm creating a Server-Client networking library for java. I'm just wondering if it's recomended to use the same DatagramSocket object from multiple classes, or if it may cause problems.
The reason to why I'm wondering is because I think that it might be problems if you for example send two things at the same time from the same socket. Is that true?
Here is an example of what I mean:
ExampleClass1:

public class ExampleClass1 {

    // The socket
    DatagramSocket socket;

    public ExampleClass1() {
        // Create the socket
        socket = new DatagramSocket(1111);

        // Create an instance of the ExampleClass2
        ExampleClass2 class2 = new ExampleClass2(socket);
    }

    public static void main(String[] args) {
        // Send something through the socket
        socket.send(new DatagramPacket(new byte[] {}, 0, 0.0.0.0, 0001));
    }
}

ExampleClass2:

public class ExampleClass2 {

    // Another socket object
    DatagramSocket socket;

    public ExampleClass2(DatagramSocket exampleClass1Socket) {
        // Set this class's socket object to the socket in the ExampleClass1
        this.socket = exampleClass1Socket;
    }

    public static void main(String[] args) {
        // Send something from the socket
        socket.send(new DatagramSocket(new byte[] {}, 0, 0.0.0.0, 0000));
    }
}
user229044
  • 232,980
  • 40
  • 330
  • 338
Daniel Kvist
  • 3,032
  • 5
  • 26
  • 51
  • see http://stackoverflow.com/questions/16498223/is-datagramsocket-send-thread-safe the send system call is atomic. – rafalopez79 Nov 06 '14 at 18:45

1 Answers1

0

No it isn't true. You can send from multiple threads simultaneously with no problems.

user207421
  • 305,947
  • 44
  • 307
  • 483