Which class should take care of doing a get on an AtomicLong - java

I have a multithreaded application where I need to ensure all threads are referring to the latest version of a long. I was thinking of using AtomicLong for this purpose.
The AtomicLong will be in one class and other classes will need to get the value and also set the value.
private final AtomicLong key;
public ClassHoldingLong(){
this.key = new AtomicLong(System.currenttimemillis());
}
public long getKey() {
return key.get();
}
public void setKey(long key) {
this.key.set(key);
}
Is this fine to do or should the getter be AtomicLong itself and someone calls .get() on the AtomicLong rather than this class holding the variable calling it for another class. From what I read, these getters setters don't need to be synchronized but not sure if that is only if AtomicLong is the return type.
This class does have additional information it holds such as statistics and additional functionality. I just included this snippet of code for an example

Related

Is this code thread safe for unique id in java

I have a simple code where I want to have objects generated with unique id. Here is the code snippet
public class Test {
private static long counter = 0;
private long id;
private Test() {
// Don't worry about overflow
id = counter++;
}
// Will this method always Test Object with unique id?
public static Test getTest() {
return new Test();
}
public long getId() {
return id;
}
}
Would like to know if getTest method is called by multiple threads will all TestObjects have unique id's?
It's not thread-safe because two threads can execute counter++ at same time and you can get unexpected results.
You should use AtomicInteger:
public class Test {
private static AtomicLong counter = new AtomicLong(0);
private long id;
private Test() {
// Don't worry about overflow
id = counter.incrementAndGet();
}
// Will this method always Test Object with unique id?
public static Test getTest() {
return new Test();
}
public long getId() {
return id;
}
}
No, it is not thread-safe for generating unique IDs. It may well happen that objects will receive non-unique IDs. You could use AtomicInteger/AtomicLong to make this work (i.e., private static AtomicLong counter = (new AtomicLong())) and then counter.getAndIncrement() in the constructor of Test.
The reason it is not thread-safe is that each processor/core has its own set of registers and without synchronization the variable may have inconsistent copies in the different processors/cores. Even on a single-processor system, preemptive multi-threading introduces the same problem. Synchronization would not be needed in non-preemptive threading systems.
you can also use synchronize block in your constructor if you want to lock class-level variable (Not the instance variable because for instance variable there is no need of synchronization . only one thread will be able to create object at a time).
so you can try this also as your constructor.
private Test() {
// Don't worry about overflow
synchronized(Test.class){
id = counter++;
}
}

Refering "this" in a lazy initialization supplier?

For business decision applications, I run into a lot of cases where I must cache an expensive value with lazy initialization. So I leveraged generics and a Supplier lambda to encapsulate a lazy initialization.
import java.util.function.Supplier;
public final class LazyProperty<T> {
private final Supplier<T> supplier;
private volatile T value;
private LazyProperty(Supplier<T> supplier) {
this.supplier = supplier;
}
public T get() {
if (value == null) {
synchronized(this) {
if (value == null) {
value = supplier.get();
}
}
}
return value;
}
public static <T> LazyProperty<T> forSupplier(Supplier<T> supplier) {
return new LazyProperty<T>(supplier);
}
}
But I'd like to be able to use this also in cases where I can't initialize a property until after the object is created, because the object can only calculate this property after it is created (usually needing context of itself or other objects). However, this often requires a reference to this in the supplier function.
public class MyClass {
private final LazyProperty<BigDecimal> expensiveVal =
LazyProperty.forSupplier(() -> calculateExpensiveVal(this));
public BigDecimal getExpensiveVal() {
return expensiveVal.get();
}
}
As long as I can guarantee the LazyProperty's get() function is only called after MyClass is constructed (via the getExpensiveVal() method), there shouldn't be any partial construction issues due to the this reference in the supplier, correct?
Based on the little code you showed you should not have any problems but I would probably write your class like this to be more explicit:
public class MyClass {
private final LazyProperty<BigDecimal> expensiveVal;
public MyClass() {
this.expensiveVal = LazyProperty.forSupplier(() -> calculateExpensiveVal(MyClass.this));
}
public BigDecimal getExpensiveVal() {
return expensiveVal.get();
}
}
Your code will have one Problem which depends on the implementation of method calculateExpensiveVal.
if calculateExpensiveVal calls getExpensiveVal on the passed reference of MyClass you will get NullPointerException.
if calculateExpensiveVal creates a thread and pass the reference of MyClass, again you may run into the same problem as point 1.
But if you guarantee calculateExpensiveVal is not doing any of the things, then your code stand correct from Thread safety Perspective. MyClass will never be seen partially constructed
because of the final gaurantees provided by the JMM
After saying that even though your *calculateExpensiveVal may employ any one or both those points you are only going to have problem in getExpensiveVal method with NullPointerException.
your lazyProperty.get method is already thread safe so there woun'd be any problem.
Because you will always see fully constructed Supplier object because of final keyword (only if you didn't escaped 'this' reference to another thread) and you already have used volatile for value field which takes care of seeing fully constructed value object.

ReadWriteLock decorator, is this code thread safe?

We're building cache stores in our app backed by memory, file, and remote services. Want to avoid explicit synchronization to keep the stores simple while using decorators for behavioral concerns like blocking.
Here's a simple cache, this is just an example!
import java.util.HashMap;
public class SimpleCache {
private HashMap<String,Object> store;
private final BlockingCacheDecorator decorator;
public SimpleCache(){
store = new HashMap<String,Object>();
decorator = new BlockingCacheDecorator(this);
}
//is NOT called directly, always uses decorator
public Object get(String key){
return store.get(key);
}
//is NOT called directly, always uses decorator
public void set(String key, Object value){
store.put(key, value);
}
//is NOT called directly, always uses decorator
public boolean isKeyStale(String key){
return !(store.containsKey(key));
}
//is NOT called directly, always uses decorator
public void refreshKey(String key){
store.put(key, new Object());
}
public BlockingCacheDecorator getDecorator(){
return decorator;
}
}
getDecorator() returns a decorator providing synchronization for get() and set(), while isKeyStale() and refreshKey() allows the decorator to check if a key should be refreshed without knowing why or how. I got the idea for a synchronizing decorator from here.
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class BlockingCacheDecorator {
private SimpleCache delegate;
private final ReentrantReadWriteLock lock;
public BlockingCacheDecorator(SimpleCache cache){
delegate = cache;
lock = new ReentrantReadWriteLock();
}
public Object get(String key){
validateKey(key);
lockForReading();
try{
return delegate.get(key);
}finally{ readUnlocked(); }
}
public void setKey(String key, Object value){
lockForWriting();
try{
delegate.set(key,value);
}finally{ writeUnlocked(); }
}
protected void validateKey(String key){
if(delegate.isKeyStale(key)){
try{
lockForWriting();
if(delegate.isKeyStale(key))
delegate.refreshKey(key);
}finally{ writeUnlocked(); }
}
}
protected void lockForReading(){
lock.readLock().lock();
}
protected void readUnlocked(){
lock.readLock().unlock();
}
protected void lockForWriting(){
lock.writeLock().lock();
}
protected void writeUnlocked(){
lock.writeLock().unlock();
}
}
Questions:
Assuming SimpleCache is only ever used via its decorator, is the code thread-safe?
Is it bad practice for ReadWriteLock to be declared outside the class being synchronized? SimpleCache.getDecorator() ensures a 1-to-1 mapping between cache and decorator instances, so I'm assuming this is ok.
Is this code thread-safe?
Yes. Assuming that the instance of the decorated SimpleCache is not passed about.
Is it bad practice for ReadWriteLock to be declared outside the class being synchronized? SimpleCache.getDecorator() ensures a 1-to-1 mapping between cache and decorator instances, so I'm assuming this is ok.
No. Although it is also worth noting that as discussed in comments, BlockingCacheDecorator would usually implement a Cache interface.
In its current form the code is trivially non-threadsafe, as there's nothing preventing a caller from calling methods of SimpleCache directly, or indeed pass the same SimpleCache instance to multiple decorators, causing even more mayhem.
If you promise never to do that, it is technically thread-safe, but we all know how much those promises are worth.
If the aim is to be able to use different implementations of underlying caches, I'd create a CacheFactory interface:
interface CacheFactory {
Cache newCache();
}
A sample implementation of the factory:
class SimpleCacheFactory implements CacheFactory {
private final String cacheName; //example cache parameter
public SimpleCacheFactory( String cacheName ) {
this.cacheName = cacheName;
}
public Cache newCache() {
return new SimpleCache( cacheName );
}
}
And finally your delegate class:
public class BlockingCacheDecorator {
private final Cache delegate;
private final ReentrantReadWriteLock lock;
public BlockingCacheDecorator(CacheFactory factory){
delegate = factory.newCache();
lock = new ReentrantReadWriteLock();
}
//rest of the code stays the same
}
This way there's a much stronger guarantee that your Cache instances won't be inadvertently reused or accessed by an external agent. (That is, unless the factory is deliberately mis-implemented, but at least your intention not to reuse Cache instances is clear.)
Note: you can also use an anonymous inner class (or possibly a closure) to provide the factory implementation.

how to use singleton pattern for sequence number creation in java

I have an Orders class and i need to have a singleton pattern to be able to create a sequence number for each order processed. How do i implement this?
My order class has an Order_ID, Customer_ID, Order_desc and Ordered_qty. There needs to be a sequence number created for each order processed using the singleton pattern.
This may be one of those X/Y problems, where you think Y is a solution to X, so you ask for help with Y, but perhaps there is a better solution.
Strictly speaking, to implement a singleton, all you need is a class whose only constructors are private, a static reference to an instance of the class as a class field, and a public getInstance method. Then create an instance method which returns the next number in line.
public class MySingleton {
private static MySingleton instance = new MySingleton();
private volatile int next = 0;
private MySingleton() {
// prevent external instantiation of a singleton.
}
public static MySingleton getInstance() {
return instance;
}
public synchronized int getNextSequence() {
return next++;
}
}
There are many flaws with this solution to your problem, some are just basic OOP design and some are more systemic:
A singleton that does not implement or extend any types is worthless. You could just use all static methods instead. Singletons are useful if you are writing a class that implements an interface and that interface is used by somebody else, but you only want a single instance as an implementation detail. This type of singleton is an attempt to make a global variable look like it is not a global variable.
This will not survive application restarts. If these sequences are being used to identify data that is stored externally or shared, you will end up repeating the same numbers when the application is restarted.
If you deploy multiple instances of the application who read and write to a common persistent storage, like a database, they will re-use the same numbers because the sequence is only tracked within the JVM.
Databases are already exceptionally good at this. Trying to re-invent it in the application tier seems.... inappropriate.
Although I agree #Elliott Frisch that the question itself sounds strange. However if you indeed have to generate IDs yourself here is the prototype that implements classic version of Singleton pattern.
public class IdGenerator {
private static IdGenerator instance;
private int id = 0;
private IdGenerator(){}
private static IdGenerator getInstance() {
synchronized(IdGenerator.class) {
if (instance == null) {
instance = new IdGenerator();
}
return instance;
}
}
public int nextId() {
return id++;
}
}
Please note that word "classic". There are a lot of possible improvements of Singleton pattern and there are hundreds of articles that explain them.
The key aspect is to use a single AtomicLong as the singleton. You may model it like this:
class Orders {
private static final AtomicLong NEXT_ID = new AtomicLong();
static Order newOrder(Customer customer, String description, int quantity) {
return new Order(orderId(), customer, description, quantity);
}
private static long orderId() {
return NEXT_ID.incrementAndGet();
}
}
class Order {
private final long orderId;
private final long customerId;
private final String description;
private final int quantity;
Order(long orderId, Customer customer, String description, int quantity) {
this.orderId = orderId;
this.quantity = quantity;
this.customerId = customer.getCustomerId();
this.description = description;
}
}
class Customer {
public long getCustomerId() {
throw new UnsupportedOperationException("not yet implemented");
}
}

Exposing instance constants with non-static public final variables

I never see this kind of constants declaration in any Java code around me...
So i'd like to know if you see any drawback of using non-static final constants.
For exemple, i've declared a Guava function as a public constant of a given MaintenanceMode instance. I think it's better because if i created a getDecoratorFunction() it would create a new function instance each time...
Or the get function could return the single instance function that is kept private in the class, but it hads useless code... When we declare constants at class level, we declare directly the constants being public, we do not put them private and provide a public getter to access them...
public class MaintenanceMode {
/**
* Provides a function to decorate a push service with the appropriate decorator
*/
public final Function<PushService,PushService> MAINTENANCE_DECORATION_FUNCTION = new Function<PushService,PushService>() {
#Override
public PushService apply(PushService serviceToDecorate) {
return new PushServiceMaintenanceDecorator(serviceToDecorate,MaintenanceMode.this);
}
};
private final EnumMaintenanceMode maintenanceMode;
private final long milliesBetweenMaintenances;
private final Optional<ExecutorService> executorService;
public EnumMaintenanceMode getMaintenanceMode() {
return maintenanceMode;
}
public long getMilliesBetweenMaintenances() {
return milliesBetweenMaintenances;
}
public Optional<ExecutorService> getExecutorService() {
return executorService;
}
private MaintenanceMode(EnumMaintenanceMode maintenanceMode, long milliesBetweenMaintenances, ExecutorService executorService) {
Preconditions.checkArgument(maintenanceMode != null);
Preconditions.checkArgument(milliesBetweenMaintenances >= 0);
this.maintenanceMode = maintenanceMode;
this.milliesBetweenMaintenances = milliesBetweenMaintenances;
this.executorService = Optional.fromNullable(executorService);
}
}
And i can access this variable with:
pushServiceRegistry.decoratePushServices(maintenanceMode.MAINTENANCE_DECORATION_FUNCTION);
I guess it could lead to strange behaviours if my maintenanceMode was mutable and accessed by multiple threads, but here it's not.
Do you see any drawback of using this kind of code?
Edit: I can have multiple instances of MaintenanceMode, and all instances should be able to provide a different constant function according to the MaintenanceMode state. So i can't use a static variable that would not access the MaintenanceMode state.
The point of a getter would be dynamic dispatch. If you have no need for it, using a public final field is perfectly fine. I even routinely write bean-like objects that have no getters, just public final fields.
By making a constant non-static, you are basically saying that the constant can only be accessed when you have an instance of that class. But it is public (in the case of MAINTENANCE_DECORATION_FUNCTION) and it is part of that class so why not make it static? The constant is, after all, a constant and it does not require an instance of that class to be used elsewhere. The variable maintenanceMode is fine as it is a private constant.

Categories

Resources