本文介绍了原子参考的保证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! c> c>将会返回 CustomObject 新版本 ? 这是关于Is there a guarantee that on line obj = ref.get(); //???? the get will return the most fresh version of CustomObject?This is related to the answer of assylias for post:推荐答案实际上,您的代码具有可能导致新数据丢失的竞争条件:Actually, your code has a race condition which could cause new data to be lost: 第一个调用者进入loadNewData并开始加载新数据有信号量) 第二个调用者不能获取信号量并等待获取 第一个调用者完成加载和释放信号量) 第二个呼叫者获取信号量,调用 ref.get()并获取旧数据 第一个调用者返回传递给 ref.set()的新数据 ref.set()first caller goes into loadNewData and starts loading new data (has semaphore)second caller cannot get semaphore and waits at acquirefirst caller finishes loading and releases semaphore (but doesn't return new data yet)second caller acquires semaphore, calls ref.get() and gets old datafirst caller returns new data which is passed to ref.set()second caller return old data which overwrites new data when passed to ref.set() $ 覆盖新数据b $ b 由于 someMethod()总是正在载入新资料,您总是希望来电者等待新数据正在加载,所有这些额外的东西是无用的。只是使用一个简单的同步块(或锁)围绕整个块和沟道原子参考。根据链接的帖子,似乎你只想做一次,所以使用一个初始化的标志。Since someMethod() is always loading new data and you always want callers to wait while new data is loading, all this extra stuff is useless. just use a simple synchronized block (or Lock) around the whole block and ditch the atomic reference. according to the linked post, it seems like you only ever want to do this once, so use an initialized flag.private boolean _initialized;public synchronized void loadLatestData() { if(!_initialized) { // load latest data ... _initilized = true; }} 这篇关于原子参考的保证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-03 21:18