Apache Tomcat7 Memory leaks (Suspecting a singleton object) - java

I am currently developing a Java Web application on a machine with the
following
attributes:
Ubuntu-Server Edition Linux 12.04 64-bit
Sun java JDK version 7
Apache Tomcat 7.0.30
Netbeans IDE, version 7.1.2
My project consists of a SOAP Web service interface, that maintains a
shared in-
memory object. In order to make the object visible to all threads, I
developed a
Singleton. I post the code of my application below:
#WebService()
public class ETL_WS {
private Singleton CAP_offer_coupon_map;
public ETL_WS() { }
/**
* This method adds a single coupon record to the memory map.
*/
#WebMethod
synchronized public int singleCouponLoad(#WebParam(name =
"CouponID") long coupon_id,
#WebParam(name = "ProductCategoryID") long product_category_id,
#WebParam(name = "DateTo") Date dateTo,
#WebParam(name = "LocationID") Location location_id) {
Coupon _c = new Coupon(coupon_id, product_category_id, dateTo);
if(location_id != null)
_c.setLocation(location_id);
CAP_CouponOfferCollection _data = CAP_offer_coupon_map.getModel();
Coupon _tmp = _data.getCoupon(coupon_id);
if(_tmp == null)
return -1;
_data.insertCoupon(_c);
return 0;
}
/**
* This method adds a single offer record to the memory map.
*/
#WebMethod
synchronized public int singleOfferLoad(#WebParam(name =
"OfferID") long offer_id,
#WebParam(name = "ProductCategoryID") long product_category_id,
#WebParam(name = "DateTo") Date dateTo,
#WebParam(name = "LocationID") Location location_id) {
Offer _o = new Offer(offer_id, product_category_id, dateTo);
if(location_id != null)
_o.setLocation(location_id);
CAP_CouponOfferCollection _data = CAP_offer_coupon_map.getModel();
Offer _tmp = _data.getOffer(offer_id);
if(_tmp == null)
return -1;
_data.insertOffer(_o);
return 0;
}
#WebMethod
synchronized public String getAllCoupons() {
CAP_CouponOfferCollection _data = CAP_offer_coupon_map.getModel();
HashMap<Long, Coupon> _c = _data.getCoupons_map();
return _c.toString();
}
#WebMethod
synchronized public String getAllOffers() {
CAP_CouponOfferCollection _data = CAP_offer_coupon_map.getModel();
HashMap<Long, Offer> _o = _data.getOffers_map();
return _o.toString();
}
#WebMethod
synchronized public long getProductIdFromCouponId(#**WebParam(name
= "CouponID") long coupon_id) {
long _product_id = -1;
CAP_CouponOfferCollection _data = CAP_offer_coupon_map.getModel();
Coupon _c = _data.getCoupon(coupon_id);
if(_c != null)
_product_id = _c.getCoupon_id();
return _product_id;
}
#WebMethod
synchronized public long getProductIdFromOfferId(#WebParam(name = "OfferID") long
offer_id) {
long _product_id = -1;
CAP_CouponOfferCollection _data = CAP_offer_coupon_map.getModel();
Offer _o = _data.getOffer(offer_id);
if(_o != null)
_product_id = _o.getOffer_id();
return _product_id;
}
}
The Singleton wrapper-class is shown below:
public class Singleton {
private static boolean _instanceFlag = false;
private static final Singleton _instance = new Singleton();
private static CAP_CouponOfferCollection _data;
private Singleton() {
_data = new CAP_CouponOfferCollection();
_instanceFlag = true;
}
public static synchronized CAP_CouponOfferCollection getModel() {
if(_instanceFlag == false) {
_data = new CAP_CouponOfferCollection();
_instanceFlag = true;
}
return _data;
}
}
and the CAP_CouponOfferCollection class is shown below:
public class CAP_CouponOfferCollection {
private HashMap<Long, Coupon> _coupons_map;
private HashMap<Long, ArrayList<Long>> _product_to_coupons_map;
private HashMap<Long, Offer> _offers_map;
private HashMap<Long, ArrayList<Long>> _product_cat_to_offers_map;
private static long _creation_time;
public CAP_CouponOfferCollection() {
_creation_time = System.currentTimeMillis();
System.out.println("Creation of CAP_CouponOffer object: " +
_creation_time);
}
synchronized public void insertCoupon(Coupon newCoupon) {
if(_coupons_map == null) {
_coupons_map = new HashMap<Long, Coupon>();
_product_to_coupons_map =
new HashMap<Long, ArrayList<Long>>();
}
Long key = newCoupon.getCoupon_id();
if(!_coupons_map.containsKey(key)) {
_coupons_map.put(key, newCoupon);
key = newCoupon.getProductCategory_id();
if(_product_to_coupons_map.containsKey(key)) {
ArrayList<Long> _c_list = _product_to_coupons_map.get(key);
_c_list.add(newCoupon.getCoupon_id());
_product_to_coupons_map.remove(key);
_product_to_coupons_map.put(key, _c_list);
}else {
ArrayList<Long> _c_list = new ArrayList<Long>();
_c_list.add(newCoupon.getCoupon_id());
_product_to_coupons_map.put(key, _c_list);
}
}
}
synchronized public void insertOffer(Offer newOffer) {
if(_offers_map == null) {
_offers_map = new HashMap<Long, Offer>();
_product_cat_to_offers_map =
new HashMap<Long, ArrayList<Long>>();
}
Long key = newOffer.getOffer_id();
if(!_offers_map.containsKey(key)) {
_offers_map.put(key, newOffer);
key = newOffer.getProductCategory_id();
if(_product_cat_to_offers_map.containsKey(key)) {
ArrayList<Long> _o_list = _product_cat_to_offers_map.get(key);
_o_list.add(newOffer.getOffer_id());
_product_cat_to_offers_map.remove(key);
_product_cat_to_offers_map.put(key, _o_list);
}else {
ArrayList<Long> _o_list = new ArrayList<Long>();
_o_list.add(newOffer.getOffer_id());
_product_cat_to_offers_map.put(key, _o_list);
}
}
}
synchronized public void removeCoupon(long couponId) {
Coupon _c;
Long key = new Long(couponId);
if(_coupons_map != null && _coupons_map.containsKey(key)) {
_c = (Coupon) _coupons_map.get(key);
_coupons_map.remove(key);
Long product = new Long(_c.getCoupon_id());
ArrayList<Long> _c_list =
(ArrayList<Long>) _product_to_coupons_map.get(product);
_c_list.remove(key);
_product_to_coupons_map.remove(product);
_product_to_coupons_map.put(product, _c_list);
}
}
synchronized public void removeOffer(long offerId) {
Offer _o;
Long key = new Long(offerId);
if(_offers_map != null && _offers_map.containsKey(key)) {
_o = (Offer) _offers_map.get(key);
_offers_map.remove(key);
Long product = new Long(_o.getOffer_id());
ArrayList<Long> _o_list =
(ArrayList<Long>) _product_cat_to_offers_map.get(product);
_o_list.remove(key);
_product_cat_to_offers_map.remove(product);
_product_cat_to_offers_map.put(product, _o_list);
}
}
synchronized public Coupon getCoupon(long CouponID) {
Long key = new Long(CouponID);
if(_coupons_map != null && _coupons_map.containsKey(key)) {
Coupon _c = (Coupon) _coupons_map.get(key);
Date _now = new Date();
if(_now.compareTo(_c.getDateTo()) > 0) {
this.removeCoupon(CouponID);
return null;
}
return (Coupon) _coupons_map.get(key);
}else
return null;
}
synchronized public Offer getOffer(long OfferID) {
Long key = new Long(OfferID);
if(_offers_map != null && _offers_map.containsKey(key)) {
Offer _o = (Offer) _offers_map.get(key);
Date _now = new Date();
if(_now.compareTo(_o.getDateTo()) > 0) {
this.removeOffer(OfferID);
return null;
}
return (Offer) _offers_map.get(key);
}else
return null;
}
synchronized public ArrayList<Long> getCoupons(long ProductID) {
Long key = new Long(ProductID);
if(_product_to_coupons_map != null && _product_to_coupons_map.containsKey(key))
{
ArrayList<Long> _c_list =
(ArrayList<Long>) _product_to_coupons_map.get(key);
Iterator itr = _c_list.iterator();
while(itr.hasNext()) {
Long l = (Long) itr.next();
if(this.getCoupon(l.longValue()) == null)
_c_list.remove(l.intValue());
}
_product_to_coupons_map.remove(key);
_product_to_coupons_map.put(key, _c_list);
return _c_list;
}else
return null;
}
synchronized public ArrayList<Long> getOffers(long ProductID) {
Long key = new Long(ProductID);
if(_product_cat_to_offers_map != null &&
_product_cat_to_offers_map.containsKey(key)) {
ArrayList<Long> _o_list = _product_cat_to_offers_map.get(key);
Iterator itr = _o_list.iterator();
while(itr.hasNext()) {
Long l = (Long) itr.next();
if(this.getOffer(l.longValue()) == null)
_o_list.remove(l.intValue());
}
_product_cat_to_offers_map.remove(key);
_product_cat_to_offers_map.put(key, _o_list);
return _o_list;
}else
return null;
}
synchronized public HashMap<Long, Coupon> getCoupons_map() {
return _coupons_map;
}
synchronized public void setCoupons_map(HashMap<Long, Coupon> _coupons_map) {
this._coupons_map = _coupons_map;
}
synchronized public static long getCreation_time() {
return _creation_time;
}
synchronized public void cleanup_offers() {
if(_product_cat_to_offers_map != null) {
Set _offers_key_set = _product_cat_to_offers_map.keySet();
Iterator itr = _offers_key_set.iterator();
while(itr.hasNext()) {
Long l = (Long) itr.next();
this.getOffers(l.longValue());
}
}
}
synchronized public void cleanup_coupons() {
if(_product_to_coupons_map != null) {
Set _coupons_key_set = _product_to_coupons_map.keySet();
Iterator itr = _coupons_key_set.iterator();
while(itr.hasNext()) {
Long l = (Long) itr.next();
this.getCoupons(l.longValue());
}
}
}
}
The problem is that when I deploy the above application (its name is ETL_Procedures)
to the Apache Tomcat I get the following SEVERE log entries:
SEVERE: The web application [/ETL_Procedures] appears to have started a thread named [maintenance-task-executor-thread-1] but has failed to stop it. This is very likely to create a memory leak.
Oct 03, 2012 5:35:03 PM org.apache.catalina.loader.WebappClassLoadercheckThreadLocalMapForLeaks
SEVERE: The web application [/ETL_Procedures] created a ThreadLocal with key of type [org.glassfish.gmbal.generic.OperationTracer$1] (value [org.glassfish.gmbal.generic.OperationTracer$1#4c24821]) and a value of type [java.util.ArrayList] (value [[]]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
Oct 03, 2012 5:35:03 PM org.apache.catalina.loader.WebappClassLoadercheckThreadLocalMapForLeaks
SEVERE: The web application [/ETL_Procedures] created a ThreadLocal with key of type [com.sun.xml.bind.v2.ClassFactory$1] (value [com.sun.xml.bind.v2.ClassFactory$1#6f0d70f7]) and a value of type [java.util.WeakHashMap] (value [{class com.sun.xml.ws.runtime.config.TubeFactoryList=java.lang.ref.WeakReference#5b73a116, class javax.xml.bind.annotation.adapters.CollapsedStringAdapter=java.lang.ref.WeakReference#454da42, class com.sun.xml.ws.runtime.config.MetroConfig=java.lang.ref.WeakReference#5ec52546, class com.sun.xml.ws.runtime.config.TubeFactoryConfig=java.lang.ref.WeakReference#61124745, class java.util.ArrayList=java.lang.ref.WeakReference#770534cc, class com.sun.xml.ws.runtime.config.Tubelines=java.lang.ref.WeakReference#76cd7a1f, class javax.xml.bind.annotation.W3CDomHandler=java.lang.ref.WeakReference#2c0cc628, class com.sun.xml.ws.runtime.config.TubelineDefinition=java.lang.ref.WeakReference#7aa582af}]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
Oct 03, 2012 5:35:03 PM org.apache.catalina.loader.WebappClassLoadercheckThreadLocalMapForLeaks
SEVERE: The web application [/ETL_Procedures] created a ThreadLocal with key of type [com.sun.xml.bind.v2.runtime.Coordinator$1] (value [com.sun.xml.bind.v2.runtime.Coordinator$1#826ee11]) and a value of type [java.lang.Object[]] (value [[Ljava.lang.Object;#33d7a245]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
Oct 03, 2012 5:35:03 PM org.apache.catalina.loader.WebappClassLoader checkThreadLocalMapForLeaks
SEVERE: The web application [/ETL_Procedures] created a ThreadLocal with key of type [org.glassfish.gmbal.generic.OperationTracer$1] (value [org.glassfish.gmbal.generic.OperationTracer$1#4c24821]) and a value of type [java.util.ArrayList] (value [[]]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
I really do not know what causes those memory leaks. My questions are the
following:
Can anyone suspect what may be the issue with my web service? If the
cause of the memory leaks is the Singleton object,
what else can I do to meet my applications requirements and avoid memory
leaks.
Is there any tool that I can use in order to monitor my threads, and
what exactly causes these SEVERE messages?
If I let my application deployed for a long time, I get an
IllegalStateException with the following message:
INFO: Illegal access: this web application instance has been stopped already. Could not load com.sun.xml.ws.rx.rm.localization.LocalizationMessages. The eventual following stack trace is caused by an error thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access, and has no functional impact.
java.lang.IllegalStateException at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1600)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
at com.sun.xml.ws.rx.rm.runtime.sequence.SequenceMaintenanceTask.run(SequenceMaintenanceTask.java:81)
at com.sun.xml.ws.commons.DelayedTaskManager$Worker.run(DelayedTaskManager.java:91)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:178)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:292)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
How can I see the whole call path that causes this Exception?
Thank you for your time and I am really sorry for the long message.

Looks like you got java.lang.IllegalStateException when your application was redeployed, but failed to undeploy, and some old process still run. Maybe when you redeploy application some threads was waiting while other thread leave synchronization block. Maybe it is some scheduled process, do you have any? Difficult to say what it was.
I can suggest you to register listener in web.xml and in contextDestroyed() method clean up all resources. And run some memory analyzing tool, for example, MAT

Related

Why updating broadcast variable sample code didn't work?

I want to update broadcast variable every minute. So I use the sample code you give by Aastha in this question.
how can I update a broadcast variable in Spark streaming?
But it didn't work. The function updateAndGet() only works when the streaming application start. When I debug my code , it didn't went into the fuction updateAndGet() twice. So the broadcast variable didn't update every minute.
Why?
Here is my sample code.
public class BroadcastWrapper {
private Broadcast<List<String>> broadcastVar;
private Date lastUpdatedAt = Calendar.getInstance().getTime();
private static BroadcastWrapper obj = new BroadcastWrapper();
private BroadcastWrapper(){}
public static BroadcastWrapper getInstance() {
return obj;
}
public JavaSparkContext getSparkContext(SparkContext sc) {
JavaSparkContext jsc = JavaSparkContext.fromSparkContext(sc);
return jsc;
}
public Broadcast<List<String>> updateAndGet(JavaStreamingContext jsc) {
Date currentDate = Calendar.getInstance().getTime();
long diff = currentDate.getTime()-lastUpdatedAt.getTime();
if (broadcastVar == null || diff > 60000) { // Lets say we want to refresh every 1 min =
// 60000 ms
if (broadcastVar != null)
broadcastVar.unpersist();
lastUpdatedAt = new Date(System.currentTimeMillis());
// Your logic to refreshs
// List<String> data = getRefData();
List<String> data = new ArrayList<String>();
data.add("tang");
data.add("xiao");
data.add(String.valueOf(System.currentTimeMillis()));
broadcastVar = jsc.sparkContext().broadcast(data);
}
return broadcastVar;}}
//Here is the computing code submit to spark streaming.
lines.transform(new Function<JavaRDD<String>, JavaRDD<String>>() {
Broadcast<List<String>> blacklist =
BroadcastWrapper.getInstance().updateAndGet(jsc);
#Override
public JavaRDD<String> call(JavaRDD<String> rdd) {
JavaRDD<String> dd=rdd.filter(new Function<String, Boolean>() {
#Override
public Boolean call(String word) {
if (blacklist.getValue().contains(word)) {
return false;
} else {
return true;
}
}
});
return dd;
}});

How to reuse redis(JRedis) pool connection in Java

I am using Redis(3.2.100) for Windows to cache my database data in Java.This is my redis init code:
private static Dictionary<Integer, JedisPool> pools = new Hashtable();
static {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(2);
config.setMaxTotal(10);
config.setTestOnBorrow(true);
config.setMaxWaitMillis(2000);
for (int i = 0; i < 16; i++) {
JedisPool item = new JedisPool(config, "127.0.0.1", 6379,10*1000);
pools.put(i, item);
}
}
This is the cache code:
public static String get(String key, Integer db) {
JedisPool poolItem = pools.get(db);
Jedis jredis = poolItem.getResource();
String result = jredis.get(key);
return result;
}
The problem is when the program run for a while,the getResource method throws:
redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool
So how to reuse the connection or close the connection.I am using this command to find out that the client has reached the max value.
D:\Program Files\Redis>redis-cli.exe info clients
# Clients
connected_clients:11
client_longest_output_list:0
client_biggest_input_buf:0
blocked_clients:0
How to fix it?
Remember to close the redis connection,modify this function like this:
public static String get(String key, Integer db) {
JedisPool poolItem = pools.get(db);
Jedis jredis = null;
String result = null;
try {
jredis = poolItem.getResource();
result = jredis.get(key);
} catch (Exception e) {
log.error("get value error", e);
} finally {
if (jredis != null) {
jredis.close();
}
}
return result;
}

detect concurrent access to syncronized function java

I Have a multithreaded environment in android app. I use a singleton class to store data. This singleton class contains a arraylist that is accessed using a synchronized method.
The app uses this arraylist to render images in app.
Initial problem : Concurrent modification error use to come so I made the get arraylist function syncronized.
Current Problem:Concurrent modification error not coming but in between empty arraylist returned (maybe when there is concurrent access).
Objective : I want to detect when Concurrent modification so that Instead of empty arraylist being return I can return last state of the arraylist.
public synchronized List<FrameData> getCurrentDataToShow() {
List<FrameData> lisCurrDataToShow = new ArrayList<FrameData>();
//for (FrameData fd : listFrameData) {//concurrent modification exception
//todo iterator test
Iterator<FrameData> iterator = listFrameData.iterator();
while (iterator.hasNext()) {
FrameData fd = iterator.next();
long currentTimeInMillis = java.lang.System.currentTimeMillis();
if ((currentTimeInMillis > fd.getStartDate().getTime() && currentTimeInMillis < fd.getEndDate().getTime()) || (fd.isAllDay() && DateUtils.isToday(fd.getStartDate().getTime()))) {
if (new File(ImageFrameActivity.ROOT_FOLDER_FILES + fd.getFileName()).exists()) {
lisCurrDataToShow.add(fd);
}
}
}
if (lisCurrDataToShow.size() == 0) {
lisCurrDataToShow.add(new FrameData(defaultFileName, null, null, null, String.valueOf(120), false));
}
return lisCurrDataToShow;
}
Referred to Detecting concurrent modifications?
Please help!
EDIT1:
This problem occurs rarely not everytime.
If a threads is accessing getCurrentDataToShow() and another thread tries to access this function what will the function return?? I'm new to multithreading , please guide
Edit 2
in oncreate following methods of singleton are called periodically
DataModelManager.getInstance().getCurrentDataToShow();
DataModelManager.getInstance().parseData(responseString);
Complete singleton class
public class DataModelManager {
private static DataModelManager dataModelManager;
private ImageFrameActivity imageFrameAct;
private String defaultFileName;
public List<FrameData> listFrameData = new ArrayList<FrameData>();
// public CopyOnWriteArrayList<FrameData> listFrameData= new CopyOnWriteArrayList<FrameData>();
private String screensaverName;
private boolean isToDownloadDeafultFiles;
private String tickerMsg = null;
private boolean showTicker = false;
private boolean showHotspot = false;
private String hotspotFileName=null;
public String getDefaultFileName() {
return defaultFileName;
}
public boolean isToDownloadDeafultFiles() {
return isToDownloadDeafultFiles;
}
public void setToDownloadDeafultFiles(boolean isToDownloadDeafultFiles) {
this.isToDownloadDeafultFiles = isToDownloadDeafultFiles;
}
private String fileNames;
private DataModelManager() {
}
public static DataModelManager getInstance() {
if (dataModelManager == null) {
synchronized (DataModelManager.class) {
if (dataModelManager == null) {
dataModelManager = new DataModelManager();
}
}
}
return dataModelManager;
}
private synchronized void addImageData(FrameData frameData) {
//Log.d("Frame Data","Start date "+frameData.getStartDate()+ " " +"end date "+frameData.getEndDate());
listFrameData.add(frameData);
}
public synchronized void parseData(String jsonStr) throws JSONException {
listFrameData.clear();
if (jsonStr == null) {
return;
}
List<String> listFileNames = new ArrayList<String>();
JSONArray jsonArr = new JSONArray(jsonStr);
int length = jsonArr.length();
for (int i = 0; i < length; i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
dataModelManager.addImageData(new FrameData(jsonObj.optString("filename", ""), jsonObj.optString("start", ""), jsonObj.optString("end", ""), jsonObj.optString("filetype", ""), jsonObj.optString("playTime", ""), jsonObj.optBoolean("allDay", false)));
listFileNames.add(jsonObj.optString("filename", ""));
}
fileNames = listFileNames.toString();
}
public void setDefaultFileData(String jsonStr) throws JSONException {
JSONObject jsonObj = new JSONObject(jsonStr);
defaultFileName = jsonObj.optString("default_image", "");
screensaverName = jsonObj.optString("default_screensaver ", "");
}
#Override
public String toString() {
return fileNames.replace("[", "").replace("]", "") + "," + defaultFileName + "," + screensaverName;
}
public FrameData getFrameData(int index) {
return listFrameData.get(index);
}
public synchronized List<FrameData> getCurrentDataToShow() {
List<FrameData> lisCurrDataToShow = new ArrayList<FrameData>();
// for (FrameData fd : listFrameData) {//concurrent modification exception
//todo iterator test
Iterator<FrameData> iterator = listFrameData.iterator();
while (iterator.hasNext()) {
FrameData fd = iterator.next();
long currentTimeInMillis = java.lang.System.currentTimeMillis();
if ((currentTimeInMillis > fd.getStartDate().getTime() && currentTimeInMillis < fd.getEndDate().getTime()) || (fd.isAllDay() && DateUtils.isToday(fd.getStartDate().getTime()))) {
if (new File(ImageFrameActivity.ROOT_FOLDER_FILES + fd.getFileName()).exists()) {
lisCurrDataToShow.add(fd);
}
}
}
if (lisCurrDataToShow.size() == 0) {
lisCurrDataToShow.add(new FrameData(defaultFileName, null, null, null, String.valueOf(120), false));
}
return lisCurrDataToShow;
}
public String getCurrentFileNames() {
String currFileNames = "";
List<FrameData> currFrameData = getCurrentDataToShow();
for (FrameData data : currFrameData) {
currFileNames += "," + data.getFileName();
}
return currFileNames;
}
public ImageFrameActivity getImageFrameAct() {
return imageFrameAct;
}
public void setImageFrameAct(ImageFrameActivity imageFrameAct) {
this.imageFrameAct = imageFrameAct;
}
}
This is the only part of your question that is currently answerable:
If a threads is accessing getCurrentDataToShow() and another thread tries to access this function what will the function return?
It depends on whether you are calling getCurrentDataToShow() on the same target object; i.e. what this is.
If this is the same for both calls, then the first call will complete before the second call starts.
If this is different, you will be locking on different objects, and the two calls could overlap. Two threads need to lock the same object to achieve mutual exclusion.
In either case, this method is not changing the listFrameData collection. Hence it doesn't matter whether the calls overlap! However, apparently something else is changing the contents of the collection. If that code is not synchronizing at all, or if it is synchronizing on a different lock, then that could be a source of problems.
Now you say that you are not seeing ConcurrentModificationException's at the moment. That suggests (but does not prove) that there isn't a synchronization problem at all. And that suggests (but does not prove) that your current problem is a logic error.
But (as I commented above) there are reasons to doubt that the code you have shown us is an true reflection of your real code. You need to supply an MVCE if you want a more definite diagnosis.

WeakReference to garbage collect Remote Objects

I am playing around with JGroups as a distributed system. I want to create objects on a remote JVM and use them as if they were created locally. Therefore I am using a java.lang.reflect.Proxy to wrap the RPC calls. This is a much like RMI behavior. This works very well.
But now I want to garbage collect the remote object if the client interface/proxy is no longer in use. So I thought I can get this working by using a WeakReference but I never fall into the GC cycle. What am I missing?
public class RMILikeWrapper {
private static final ScheduledExecutorService garbageCollector = Executors.newSingleThreadScheduledExecutor();
private final Map remoteObjects = new ConcurrentHashMap();
private final Map<WeakReference, IdPointer> grabageTracker = new ConcurrentHashMap<>();
private final ReferenceQueue rq = new ReferenceQueue();
private final RpcDispatcher rpcDispatcher;
private final long callTimeout = 10000L;
private class IdPointer {
public final Address address;
public final String id;
public IdPointer(Address address, String id) {
this.address = address;
this.id = id;
}
#Override
public String toString() {
return "IdPointer{" + "address=" + address + ", id='" + id + '\'' + '}';
}
}
public RMILikeWrapper(Channel channel) {
this.rpcDispatcher = new RpcDispatcher(channel, null, null, this);
// enable garbage collecting
garbageCollector.scheduleWithFixedDelay(new Runnable() {
#Override
public void run() {
System.out.println("my GC ");
Reference<?> ref; //this should be our weak reference
while((ref = rq.poll()) != null) {
// remove weak reference from the map
IdPointer garbage = grabageTracker.remove(ref);
System.out.println("found expired weak references: " + garbage);
// now we need to destroy the remote object too
try {
rpcDispatcher.callRemoteMethod(garbage.address, "purge", new Object[]{garbage.id},
new Class[]{String.class}, new RequestOptions(ResponseMode.GET_FIRST, callTimeout));
} catch (Exception e) {
e.printStackTrace();
}
}
}
},0,10, TimeUnit.SECONDS);
}
public <T>T createRemoteObject(Class<T> proxyInterface, Address targetNode, Class c, Object[] args, Class[] argTypes) {
try {
Object[] remoteArgs = new Object[4];
remoteArgs[0] = UUID.randomUUID().toString();
remoteArgs[1] = c;
remoteArgs[2] = args;
remoteArgs[3] = argTypes;
rpcDispatcher.callRemoteMethod(targetNode, "addObject", remoteArgs,
new Class[]{String.class, Class.class, Object[].class, Class[].class},
new RequestOptions(ResponseMode.GET_FIRST, callTimeout));
// now get in interface stub for this object
return getRemoteObject(targetNode, remoteArgs[0].toString(), proxyInterface);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// Operation triggerd by RPC
public void addObject(String id, Class c, Object[] args, Class[] parameterTypes) throws Exception {
remoteObjects.put(id, c.getConstructor(parameterTypes).newInstance(args));
}
// Operation triggerd by RPC
public Object invoke(String id, String methodName, Object[] args, Class[] argTypes) throws Exception {
Object ro = remoteObjects.get(id);
return ro.getClass().getMethod(methodName, argTypes).invoke(ro, args);
}
// Operation triggerd by RPC
public void purge(String id) {
System.out.println("garbage collecting: " + id);
//return remoteObjects.remove(id) != null;
remoteObjects.remove(id);
}
public <T>T getRemoteObject(final Address nodeAdress, final String id, final Class<T> clazz) {
if (!clazz.isInterface()) throw new RuntimeException("Class has to be an interface!");
InvocationHandler handler = new InvocationHandler() {
#Override
public Object invoke (Object proxy, Method method, Object[] args) throws Throwable {
Object[] remoteArgs = new Object[4];
remoteArgs[0] = id;
remoteArgs[1] = method.getName();
remoteArgs[2] = args;
remoteArgs[3] = method.getParameterTypes();
// remote call
return rpcDispatcher.callRemoteMethod(nodeAdress, "invoke",
remoteArgs, new Class[]{String.class, String.class, Object[].class, Class[].class},
new RequestOptions(ResponseMode.GET_FIRST, callTimeout));
}
};
T result = (T) Proxy.newProxyInstance(
clazz.getClassLoader(),
new Class[]{clazz},
handler);
// use weak pointers to the proxy object here and if one is garbage collected, purge the remote object as well
WeakReference<T> weakReference = new WeakReference<>(result, rq);
grabageTracker.put(weakReference, new IdPointer(nodeAdress, id));
return result;
}
public static void main(String[] args) throws Exception {
Channel channel = new JChannel();
channel.connect("test-cluster");
List<Address> members = channel.getView().getMembers();
RMILikeWrapper w = new RMILikeWrapper(channel);
if (members.size() > 1) {
System.out.println("send to " + members.get(0));
FooInterface remoteObject = w.createRemoteObject(FooInterface.class, members.get(0), FooImpl.class, null, null);
System.out.println(remoteObject.doSomething("Harr harr harr"));
remoteObject = null;
}
System.out.println(channel.getView().getMembers());
}
}
Using following methods you could identify how GC behaves on weak references.
Option 1:
-verbose:gc
This argument record GC behaviour whenever GC kicks into picture. You could take the log file when you want to check did GC gets into action, It could be checked from the GC logs. For Interactive GC analysis try the log with http://www.ibm.com/developerworks/java/jdk/tools/gcmv/
Option 2 :
Collect Heap dump and user event and load it in https://www.ibm.com/developerworks/java/jdk/tools/memoryanalyzer/
Write OQL(Object Query language) on OQL section
select * from package(s).classname
and click on ! on the tool bar
It will give list of objects of that type
Right click on the objects -> Path to GC roots -> Exclude soft/weak/Phantom references
If suspect object does not have any strong reference then it will show NULL else
you will get information on who is holding the strong references on the suspected object.

Spring + MongoDB: potential memory leak messages

Today I tried to fix some potential memory leaks in my web application.
I use the following libraries.
spring-webmvc-3.2.9.RELEASE
spring-data-mongodb-1.5.0.RELEASE
mongo-java-driver-2.12.1
First I missed to close the MongoClient but changed my configuration this way.
#Configuration
public class MongoDBConfiguration implements DisposableBean {
private MongoClient mongoClient;
#Bean
public MongoTemplate mongoTemplate() {
try {
final Properties props = loadProperties();
log.debug("Initializing Mongo DB client");
mongoClient =
new MongoClient(getProperty(props, "host", "localhost"), cint(getProperty(props, "port",
"27017")));
UserCredentials credentials = null;
final String auth = getProperty(props, "auth", null);
if (auth != null && auth.equalsIgnoreCase("true")) {
final String user = getProperty(props, "user", null);
final String pass = getProperty(props, "pass", null);
if (user != null && pass != null) {
credentials = new UserCredentials(user, pass);
}
}
final MongoDbFactory mongoDbFactory =
new SimpleMongoDbFactory(mongoClient, getProperty(props, "dbname", "Feeder"), credentials);
final MappingMongoConverter mongoConverter =
new MappingMongoConverter(new DefaultDbRefResolver(mongoDbFactory),
new MongoMappingContext());
mongoConverter.setCustomConversions(customConversions(mongoConverter));
mongoConverter.afterPropertiesSet();
final MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory, mongoConverter);
return mongoTemplate;
} catch (final IOException e) {
log.error("", e);
}
return null;
}
/**
* close Mongo client to avoid memory leaks
*/
#Override
public void destroy() {
log.debug("Shutdown Mongo DB connection");
mongoClient.close();
log.debug("Mongo DB connection shutdown completed");
}
}
When stopping or reloading the web application, there are still messages complaining about probable memory leaks.
2014-06-24 07:58:02,114 DEBUG d.p.f.s.m.MongoDBConfiguration - Shutdown Mongo DB connection
2014-06-24 07:58:02,118 DEBUG d.p.f.s.m.MongoDBConfiguration - Mongo DB connection shutdown completed
Jun 24, 2014 7:58:02 AM org.apache.catalina.loader.WebappClassLoader checkThreadLocalMapForLeaks
SEVERE: The web application [/feeder##1.5.1] created a ThreadLocal with key of type [com.mongodb.BaseCluster$1] (value [com.mongodb.BaseCluster$1#766465]) and a value of type [java.util.Random] (value [java.util.Random#5cb9231f]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
Lines 3 and 4 are repeated up to 9 times, as fare as I have seen.
How can I fix this? Can it be ignored?
You need to clean thread locals. See my answer here stop/interrupt a thread after jdbc Driver has been deregister
/**
* Cleanup function which cleans all thread local variables. Using thread
* local variables is not a good practice but unfortunately some libraries
* are still using them. We need to clean them up to prevent memory leaks.
*
* #return number of Thread local variables
*/
private int immolate() {
int count = 0;
try {
final Field threadLocalsField = Thread.class
.getDeclaredField("threadLocals");
threadLocalsField.setAccessible(true);
final Field inheritableThreadLocalsField = Thread.class
.getDeclaredField("inheritableThreadLocals");
inheritableThreadLocalsField.setAccessible(true);
for (final Thread thread : Thread.getAllStackTraces().keySet()) {
count += clear(threadLocalsField.get(thread));
count += clear(inheritableThreadLocalsField.get(thread));
}
log.info("Immolated " + count + " values in ThreadLocals");
} catch (Exception e) {
log.error("ThreadLocalImmolater.immolate()", e);
}
return count;
}
/**
* Cleaner for thread local map.
*
* #param threadLocalMap
* thread local map to clean or null
* #return number of cleaned objects
* #throws Exception
* in case of error
*/
private int clear(#NotNull final Object threadLocalMap) throws Exception {
if (threadLocalMap == null) {
return 0;
}
int count = 0;
final Field tableField = threadLocalMap.getClass().getDeclaredField(
"table");
tableField.setAccessible(true);
final Object table = tableField.get(threadLocalMap);
for (int i = 0, length = Array.getLength(table); i < length; ++i) {
final Object entry = Array.get(table, i);
if (entry != null) {
final Object threadLocal = ((WeakReference<?>) entry).get();
if (threadLocal != null) {
log(i, threadLocal);
Array.set(table, i, null);
++count;
}
}
}
return count;
}

Categories