Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-6977788

Write blocked while reading on a SocketChannel

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Duplicate
    • Icon: P3 P3
    • None
    • 6u20
    • core-libs
    • None
    • generic
    • generic

      Although the documentation states that "Socket channels are safe for use by multiple concurrent threads. They support concurrent reading and writing, though at most one thread may be reading and at most one thread may be writing at any given time." Actually the writer gets blocked until the reader finishes.

      $ java -version
      java version "1.6.0_20"
      Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
      Java HotSpot(TM) Server VM (build 16.3-b01, mixed mode)

      My example application creates a SocketChannel against my localhost's echo service. Initially, to test everything works fine, the same thread writes a message to it and then read from it. This works correctly.

      The main thread then creates a second thread and reads from the SocketChannel, as nothing is available it blocks. Once data is available for reading, the thread should unblock and read it.

      The newly launched thread will first wait 5 seconds to guarantee that the other thread gets blocked while trying to read. After waiting it will try to write a message to the SocketChannel for the reader thread to read. However, it will get blocked and will be unable to write until the reader finishes.

      The attached code produces the following output:

      Thread Main - Sending message
      Thread Main - Reading message
      Thread Main - Correctly read the message
      Thread Reader - Reading message
      Sender Thread is delaying
      (5 seconds delay)
      Sender Thread is sending the message

      At this point, the sender thread gets blocked while trying to write.

            Unassigned Unassigned
            alopez Alejandro Lopez (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: