The JDK document said:
Always create only one instance of a CouchbaseCluster and share it across threads (same with buckets).
The SDK is thread-safe, so no additional synchronization is needed when interacting with the SDK.
I use the jdk client in a multithread environment, and I only open one Bucket handler for the same bucket. I find that the data got from one thread maybe mixed with other thread. So I have to synchronized the get operation.
Does the Bucket handler is thread safe?
Should I open one handler per thread?
No both the cluster and the bucket instances are thread safe, and as the documentation stated they should be shared across threads.
Can you explain in more detail what you mean by “mixed”?
For example, thread 1 get doc1, and thread 2 get doc2. Sometimes the content of doc2 is returned to thread1, and doc1 is returned to thread2.
This result of this is that the user data is not what they want.
After I add synchronize code, everything is OK.
@jiuchang2004 that makes sense, because since thread ordering is not guaranteed the get makes it into the queue before the set. The client is still thread safe, but it can’t guarantee the ordering of your execution threads.
If you add some orchestration on your side (like you did with synchronize) in order to guarantee the set comes before the get, all is good. Order of execution is a different concern than thread safety of the client, if you know what I mean.
Thread ordering is guaranteed , But in thread safe environment, threads runs in isolation. jiuchang2004 should confirm that he is not getting result of thread 1 with thread 2 and vice-versa.