java - do I need to use volatile if update to other thread'cache is not time-constraint -


i have singleton object 1 method:

class static single {   string static somefilecontent;    public static void set(string str){somefilecontent=str;}    public static string get(){return somefilecontent;} } 

and have 2 thread,

one thread query content single.get() in operations, 100 times/sec.

and thread monitor file update string set() method in period, if file modified,refresh content.

it acceptable few operation use old string value.

my question is: should need volatile ,because not time-constraint?

if worst happen, whether read thread not update forever?

i wondering happen use plain java? yes, read thread may read old value after value update. said, read old value few times acceptable. wondering whether old value stays forever in cpu cache.

and vaspar's answer.

better use reentrantreadwritelock , don't need use volatile variable. get call should readlocked shared, , set call should writelocked exclusive. changes updated in threads once respective readlocks.

all readwritelock implementations must guarantee memory synchronization effects of writelock operations (as specified in lock interface) hold respect associated readlock. is, thread acquiring read lock see updates made upon previous release of write lock.

sample code:

import java.util.concurrent.locks.reentrantreadwritelock; import java.util.concurrent.locks.reentrantreadwritelock.readlock; import java.util.concurrent.locks.reentrantreadwritelock.writelock;   public class single {     private static string                       somefilecontent = null;     private static final reentrantreadwritelock readwritelock   = new reentrantreadwritelock();     private static final readlock               readlock        = readwritelock.readlock();     private static final writelock              writelock       = readwritelock.writelock();      public static string get() {         try {             readlock.lock();             return somefilecontent;         } {             readlock.unlock();         }     }      public static void set(string str) {         try {             writelock.lock();             somefilecontent = str;         } {             writelock.unlock();         }     } } 

Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -