rthur
rthur

Reputation: 1534

Java sharing an object between threads

I have a database object which stores objects in various data structures. Several threads access this database, but the database is not always up to date. If I change the name of the object in one thread, the change is only reflected in the other threads if they have not accessed that object already. If I add a new item in one thread, all threads are able to view this item.

I've tried declaring the database object as volatile, but the problem remains and I'm all out of ideas...

Thanks!

EDIT: Issue was traced down to not calling .reset() on my objectOutputStream

Upvotes: 0

Views: 1218

Answers (2)

duplicatedcode
duplicatedcode

Reputation: 1

well,you can copy the data is a new instance ,and OP on this instance like memcached cache design. step: 1.get instance 2. copy instance 3. modify instance 4.use

Upvotes: 0

Adam Siemion
Adam Siemion

Reputation: 16039

You need to synchronize access to the database object instance.

In Java there are two two basic synchronization idioms:

  • synchronized methods (apply the synchronized keyword to the methods accessing the database object instance)
  • synchronized statements (wrap the code accessing the database object instance inside the synchronized block).

More details

Upvotes: 1

Related Questions