1

I have a client use a bufferedwriter for write in a socket. But client create a thread that can use the same bufferedwriter. I don't use lock for it and my program doesn't have problem, but have I a problem if the main thread of client and the thread of the client write in the bufferedwriter in the same time?

Ecila
  • 57
  • 1
  • 4

4 Answers4

1

BufferedWriter's documentation does not describe its thread safety; the package-level documentation says nothing either.

Even if the individual methods were implemented atomically, calling multiple methods on the writer would definitely not be atomic.

You should err on the side of caution and assume it is not thread-safe, and externally synchronize the instance. The fact that no bug has manifested yet does not imply the bug is absent.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
1

Writting to socket is not an atomic operation.

Is better to use a syncrhonized method to writting


Update

https://stackoverflow.com/a/1457347/5065312

All versions of Unix and Windows attempt to keep the write atomic, but apparently very few provide a guarantee.

And if you are using a Realtime Kernel the writes are not atomic.


Update 2:

IEEE Std 1003.1-2017 If the number bytes written to socket is not specified or if the number of bytes written to socket is more than {PIPE_BUF}, then, it does not guarantee that this writting is atomic.

For more information see: man 7 pipe

PostData: It is bad practice to write concurrently without controlling the flow. 99% can work because 99% of the time the socket output will be free

VasileM
  • 606
  • 7
  • 13
  • Writing to a socket *is* an atomic operation. Writing to a `BufferedWriter` is not, and that's what the question is about. – user207421 Jun 18 '18 at 17:11
  • No, you are wrong. The Operating System attemp to keep writes as atomic operation but very few provide this function. And what happens if you are using a Real Time Kernel? https://stackoverflow.com/questions/1457256/is-it-safe-to-issue-blocking-write-calls-on-the-same-tcp-socket-from-multiple – VasileM Jun 18 '18 at 17:40
0

You will have to synchronize in the BufferedWriter when writing from any thread. Even then you are going to have massive problems at the receiving end understanding the stream, unless your protocol consists merely of lines.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

Here is the answer of your question: How to get string between two characters using regular expression?

Use this:

$input = "hi my name [is] Mary [Poppins]";
$arr = explode(' ', $input);
$from = "[";
$to = "]";
function getStringBetween($input, $from, $to) {

    $sub = substr($input, strpos($input, $from) + strlen($from), strlen($input));

    return substr($sub, 0, strpos($sub, $to));
}


foreach ($arr as $data) {

    echo getStringBetween($data, $from, $to) . " ";  // is Poppins
}
Kayani
  • 369
  • 1
  • 4
  • 16