Search This Blog

31 August 2016

Java WeakReference counterpart

We have all heard of different reference types - weak, strong, soft. We think that the WeakReference class is very useful. But we noticed the lack of StrongReference class and we think it can be useful as well. So here is our implementation of StrongReference:


1:  public class StrongReference<T> {  
2:    
3:      private T mType;  
4:        
5:      public StrongReference()  
6:      {  
7:          super();  
8:      }  
9:        
10:      public StrongReference(T aType)  
11:      {  
12:          super();  
13:          mType = aType;  
14:      }  
15:        
16:      public synchronized T get() {return mType;}  
17:      public synchronized void set(T aType) {mType = aType;}  
18:  }  

We are using synchronzed on the get and set methods, because we use the StrongReference concurently, and this was the use case we had in mind when creating it in the first place. But if your use case is different you can remove them.