简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM