Should I declare the field mutable?

Consider the following code:

class Foo { java.util.Timer timer = new java.util.Timer(); void doAction() { ... timer.schedule(new SomeTimerTask(), 0L); ... } void cancelAction() { timer.cancel(); } } 

Methods are called from different threads. The doAction () method is called first.

Should I declare the timer volatile field visible to another thread?

+4
source share
5 answers

You better use the synchronized keywords for methods like doAction() and cacelAction() , which control the critical state of the timer instance variable .

volatile keyword acts to a large extent, as described to reflect a variable field for each thread, but applies only to each individual operation, and not to all operations collectively.

+6
source

You do not need to make the field volatile, because no thread makes changes to this field: its value is set once in the initializer, and after that it does not change.

You may need to add synchronization to your methods, but declaring a volatile variable in this case is completely optional: using final would be much more appropriate.

+3
source

The Timer class is thread safe according to its javadoc ,

Therefore, it is enough to declare timer as volatile .

However, if a timer not assigned anywhere (as is the case), the best solution is to declare the field as final . This is enough to ensure that the timer variable can be safely used from multiple threads without further synchronization. (This is guaranteed by JLS Section 17.5 .)

If the Timer was not thread safe, you will need to perform all the actions in the Timer instance in the synchronized method or block (or the equivalent implemented using Locks, etc.). A timer declaration for volatile or final will NOT suffice.

+2
source

Even without declaring the field as volatile, it will be visible to all threads. The volatile keyword associated with a variable will indicate to java runtime that this variable will potentially be modified by multiple threads and therefore should not be cached locally.

0
source

The field is not required to be volatile , but it is better to use synchronized methods.

 public void synchronized doAction(){} public void synchronized cancelAction(){} 
0
source

Source: https://habr.com/ru/post/1432454/


All Articles