Reputation: 4028
In Java, I have a global variable x, what should I use to allows many threads get the value of x at a time but only one thread can change the value of x variable at a time?
Any example? Thanks.
Upvotes: 0
Views: 857
Reputation: 1845
You can use a ReadWriteLock to acheive this. Java java.util.concurrent.locks package provides different types of locks. You can use ReentrantReadWriteLock from this package. Code samples can be found in javadoc.
If the global variable is a basic data type, AtomicLong, AtomicInt etc in java.util.concurrent.atomic package should also be able to solve the usecase.
Upvotes: 1
Reputation: 36011
In this case you should be able to use the classes in java.util.concurrent.atomic
. These classes are containers for a single value that allow lock-free access. If you don't need a compare-and-swap operation you can use a volatile field as long as you're using at least java 1.5.
Upvotes: 1
Reputation: 95489
If you want to allow multiple concurrent reads, then you will want to use a ReadWriteLock (the ReentrantReadWriteLock class implements that particular interface) to protect access.
Upvotes: 1