0

Is that possible or is it a good idea to call volatile variable from isnside a locked method from anywhere?

volatile myvolatile;
    public synchronized void scan() {
        myvolatile=1;
        scback = new ScanCallback() {
javatex511
  • 13
  • 6
  • 1
    Are you asking if it will work? Yes, it will work. However, there is no point for that variable to be `volatile` if you always use it inside of synchronized blocks/methods. – Amongalen Jun 30 '20 at 10:06
  • Could you explain why it might be a bad idea in your opinion? Then we could help you better to get a better understanding by eliminating your misunderstanding. – akuzminykh Jun 30 '20 at 10:09
  • Synchronization provides Mutual exclusion and visibility control but volatile provides only the visibility control. Now you decide should we have a volatile var inside a sync method. – Sabareesh Muralidharan Jun 30 '20 at 10:10
  • no, i am calling it from another thread which is not locked. – javatex511 Jun 30 '20 at 10:10
  • `volatile` variables don't get a local thread copy & are stored in main memory, and do have atomic writes... so, there's that. But if your purpose is to "optimize" performance(?) by avoiding synchronized access to `myvolatile`, this may be counter-productive. Using a separate synchronized getter/setter for the variable might be better: reads are probably fine for your volatile, but writes will probably be slower, plus, obviously, you do not have any predictable execution order between your threads, so I'm not sure what the purpose would really be. – michael Jun 30 '20 at 10:30
  • ps: I was reading this, which might be informative. Also note option of using `AtomicReference` https://stackoverflow.com/questions/4633866/is-volatile-expensive – michael Jun 30 '20 at 10:35

0 Answers0