- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can we make Array volatile using volatile keyword in Java?
The volatile modifier indicates the JVM that the thread accessing a volatile variable should get data always from the memory. i.e. a thread should not cache the volatile variable.
Accessing a volatile variable synchronizes all the cached copied of the variables in the main memory. Volatile can only be applied to instance variables, which are of type object or private. A volatile object reference can be null.
Example
public class MyRunnable implements Runnable { private volatile boolean active; public void run() { active = true; while (active) { // line 1 // some code here } } public void stop() { active = false; // line 2 } }
Making an array volatile
The elements of an array don’t have the volatile behavior though we declare it volatile.
To resolve this, Java provides two classes namely AtomicIntegerArray and, AtomicLongArray, these represents arrays with atomic wrappers on (respective) variables, elements of these arrays are updated automatically.
i.e. can access individual elements of these arrays represented by these classes as volatile variables. These classes provides get() and set() variables to retrieve or, assign values to each elements individually.
Since atomic wrappers are available for integer and long types for remaining datatypes you need to reassign the reference value of the array each time you assign an element to it.
volatile int[] myArray = new int[3]; myArray [0] = 100; myArray = myArray; myArray [1] = 50; myArray = myArray; myArray [2] = 150; myArray = myArray;
- Related Articles
- volatile Keyword in Java
- volatile keyword in C#
- What is volatile keyword in C++?
- What does the volatile keyword mean in C++?
- Volatile Storage vs Non-Volatile Storage
- Difference between Volatile Memory and Non-Volatile Memory
- Difference between volatile and transient in java
- What is the difference between Volatile and Non-Volatile substances?
- “volatile” qualifier in C
- Why do we use a volatile qualifier in C++?
- What are 'Volatile' and 'Non-volatile' substances?
- What does the modifier volatile in Java do?
- Can a C++ variable be both const and volatile?
- What is the difference between transient and volatile in Java?
- How to Use Volatile Variables in Arduino?
