Exception created : java.lang.OutOfMemoryError - java

I have made some modification in a code of an existing application. While testing i am getting Exception created : java.lang.OutOfMemoryError. But the error occurs only once in a while. Below the is the code snippet where the error occurs
}else if(subject.equals("Mobile")){
to=(String)hashMap.get("M_MOBILETOMAIL");
m_mobileoptionvalue=(String)parameters.get("m_mobileoptionvalue");
m_mobileq1value=(String)parameters.get("m_mobileq1value");
StringTokenizer m_tokenizer1 = new StringTokenizer(m_mobileq1value,"|");
while (m_tokenizer1.hasMoreTokens()){
m_mobileq1List.add(m_tokenizer1.nextToken());
}
m_mobileq2value=(String)parameters.get("m_mobileq2value");
StringTokenizer m_tokenizer2 = new StringTokenizer(m_mobileq2value,"|");
while (m_tokenizer2.hasMoreTokens()){
m_mobileq2List.add(m_mobileq2value);
}
m_mobileq3value=(String)parameters.get("m_mobileq3value");
StringTokenizer m_tokenizer3 = new StringTokenizer(m_mobileq3value,"|");
while (m_tokenizer3.hasMoreTokens()){
m_mobileq3List.add(m_mobileq3value);
}
m_mobileq4value=(String)parameters.get("m_mobileq4value");
m_mobileq4=(String)parameters.get("m_mobileq4");
}
The error i am gettting is in the line
m_mobileq2List.add(m_mobileq2value);
Also attaching the JVM logs ----
exception created in one of the service methods of the servlet MailSend in application interact_assorted_intapp7. Exception created : java.lang.OutOfMemoryError
at java.util.ArrayList.newElementArray(ArrayList.java:94)
at java.util.ArrayList.growAtEnd(ArrayList.java:375)
at java.util.ArrayList.add(ArrayList.java:158)
at com.international.servlets.MailSend.doPost(MailSend.java:473)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:738)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:831)
I went through a few related post but did not get any proper results.Also Increase of HeapSize is out of scope.

while (m_tokenizer2.hasMoreTokens()){
m_mobileq2List.add(m_mobileq2value);
}
You are never moving your tokenizer pointer forward, so when this condition is met, it is infinitely adding the first token to your list. Try
while (m_tokenizer2.hasMoreTokens()){
m_mobileq2List.add(m_tokenizer2.nextToken());
}

If you are running out of memory and you can't increase the heap size then all you can do is try and use less memory.
Attach a profiler of some kind to your application (most IDEs have one built in) and look at where the memory is going and what you can do to reduce it, or remove any potential resource leaks you may have.
It's also worth running findbugs against your project and seeing if that finds anything. Again it's available as a plugin for most IDEs.

Issue in your code is infinite while loop.change your code to
m_mobileq2List.add(m_tokenizer2.nextToken());
Also make null all your Strings after use.Go for StringBuffer,StringBuilder instead of Strings whenever possible.If you are using any Input/Output Stream close them after use and make them null.Making large objects null saves lot of memory.

Related

How can I tell why I'm getting an IOException at line 113 in com.sun.jdmk.comm.HttpSendSocket

My JDMK based application is getting intermittent IOExceptions at line 313 in com.sun.jdmk.comm.HttpSendSocket and I can't figure out why. All I know from the Javadoc about this is if an I/O error occurs while creating the input stream you'll get an IOException, but I don't know what kind of I/O error occurred or why one did. The code actually worked both before and after this error transpired.
Any tips on how to debug this intermittent problem would be appreciated.
I don't want to paste the source code here for HttpSendSocket since it belongs not to me, but I know it's doing an HttpURLConnection conn.getInputStream() when the IOException exception is thrown.
I thought about trying to create my own version of HttpSendSocket, and adding diagnostics in it, but couldn't figure out how since it's a package protected class.
Stack trace below:
com.sun.jdmk.comm.CommunicationException: java.io.IOException: HTTP request failed
at com.sun.jdmk.comm.HttpSendSocket.readNotify(HttpSendSocket.java:313)
at com.sun.jdmk.comm.HttpSendInputStream.read(HttpSendInputStream.java:95)
at java.io.FilterInputStream.read(FilterInputStream.java:94)
at java.io.PushbackInputStream.read(PushbackInputStream.java:150)
at com.sun.jdmk.comm.GenericHttpConnectorClient.sendHttp(GenericHttpConnectorClient.java:486)
at com.sun.jdmk.comm.GenericHttpConnectorClient.invokeRemoteOperation(GenericHttpConnectorClient.java:2234)
at com.sun.jdmk.comm.GenericHttpConnectorClient.invoke(GenericHttpConnectorClient.java:1366)
As I said, any helpful suggestions would be appreciated.
The communication Exception was caused by using ArrayList method subList. ArrayList is serializable but subList data IS NOT serializable, and therefore you cannot retrieve the data over an HttpConnector. The solution was to change:
List<UserProcessInfo> values = new ArrayList<UserProcessInfo>();
...
values.size() <= 1000 ? values : values.subList(0,1000);
to:
List<UserProcessInfo> values = new ArrayList<UserProcessInfo>();
...
return values.size() <= 1000 ? values : new ArrayList<UserProcessInfo>(values.subList(0,1000));
Attach the JDMK source to your IDE, then set a breakpoint in the HttpSendSocket and run it with debugging enabled. At least in IntelliJ you can attach the library source by trying to open the class from the stacktrace, then choosing to link source. Don't know how the process is for other IDE's but I would expect it to be possible.

Java Play Mustache NPE Error

We are getting a mustache play error in production (amazon linux EC2 AMI) but not in development (MACs) and we have tried upgrading the jvm, using the jdk instead, and changing from a tomcat deploy model to match our development environments as much as possible but nothing is working. Please any help would be greatly appreciated. We have lots of shared code in java and javascript using mustache and it would be a big deal to rewrite everything if we had to ditch mustache on the java side.
20:48:52,403 ERROR ~
#6al2dd0po
Internal Server Error (500) for request GET /mystuff/people
Execution exception (In {module:mustache-0.2}/app/play/modules/mustache/MustacheTags.java around line 32)
NullPointerException occured : null
play.exceptions.JavaExecutionException
at play.templates.BaseTemplate.throwException(BaseTemplate.java:90)
at play.templates.GroovyTemplate.internalRender(GroovyTemplate.java:257)
at play.templates.Template.render(Template.java:26)
at play.templates.GroovyTemplate.render(GroovyTemplate.java:187)
at play.mvc.results.RenderTemplate.<init>(RenderTemplate.java:24)
at play.mvc.Controller.renderTemplate(Controller.java:660)
at play.mvc.Controller.renderTemplate(Controller.java:640)
at play.mvc.Controller.render(Controller.java:695)
at controllers.MyStuff.people(MyStuff.java:183)
at play.mvc.ActionInvoker.invokeWithContinuation(ActionInvoker.java:548)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:502)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:478)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:473)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:161)
at Invocation.HTTP Request(Play!)
Caused by: java.lang.NullPointerException
at play.modules.mustache.MustacheTags._template(MustacheTags.java:32)
at play.modules.mustache.MustacheTags$_template.call(Unknown Source)
at /app/views/User/people.html.(line:22)
at play.templates.GroovyTemplate.internalRender(GroovyTemplate.java:232)
... 13 more
Seems the issue is with the threadlocal. In Prod as per my logs, the session gets initialized with the main thread.
[2012-06-30 18:35:38,102] INFO 10097[**main**] - Mustache module initialized
However, MustacheTag tries to access with various thread like this during request.
[2012-06-30 17:48:44,669] INFO 66048[**play-thread-1**] - [{module:mustache-0.2}/app/play/modules/mustache/MustacheTags.java:46] _meta() :: MustachePlugin.session():null
So I changed the implementation of MustachePlugin like this.Changed line commented out:
//private static ThreadLocal<MustacheSession> session_ = new ThreadLocal<MustacheSession>();
private static MustacheSession _session = null;
public static MustacheSession session(){
//return session_.get();
return _session;
}
public void onConfigurationRead(){
// some code
_session = new MustacheSession(compiler, root);
// some code
}
And it is working fine now in prod mode! I see no reason why it should have been in a ThreadLocal in the first place as the session gets initialized at startup!
your issue is difficult to reproduce so i'll give few pointers here. you have tried to eliminate of issue being env issue. so other possible issues could be
data issue: many times reason for production issue is usually difference in actual data and test data. check if its data issue which is casuing NPE.
code issue: Is there something at people.html.(line:22) causing issue. first try removing / altering that to check if thats causing issue. Or can you get source code of mustache (exact version which you are using) and see what object its trying to create and where its failing.
Properties file for different environments: do you have different proprties file for each env? If yes, have u missed on any property for prod env?
You have a NullPointerException on MustacheTags.java at line 32.
This means that you are probably calling a method of the Mustache library and passing a null value.
Try logging all the parameters you transfer to this method (MyStuff.java line 183?).
You can look at the source code of MustacheTags here, it might help you understand what values you are passing and what should be passed.

Exception breakpoint occurred at EventDispatchThread.java

we are getting this error at the end of running application. I search in google buti don't know what cause this error and what this means. What to do and how to solve it?
i even don't know what raise this exception...
Exception breakpoint occurred at line 145 of EventDispatchThread.java.
java.lang.NullPointerException:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at oracle.jbo.uicli.jui.JUTableBinding$JUTableModel$2.run(JUTableBinding.java:1209)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
Don't know what kind of searches you have performed on Google. I would suggest looking up each error (or rather each class where error occurs). Starting from the beginning as subsequent errors may be a due to error propagation. Two searches for EventDispatchThread and JUTableBinding.java may provide some insight at what went wrong.
http://www.docjar.org/docs/api/java/awt/EventDispatchThread.html
It seems that this class deals with AWT components ("takes events off the EventQueue and dispatches them to the appropriate AWT components")
For the JUTableBinding.java there are quite a few pages that say about NullPointerException
https://forums.oracle.com/forums/thread.jspa?threadID=515213
https://forums.oracle.com/forums/thread.jspa?threadID=2343921
https://kr.forums.oracle.com/forums/thread.jspa?threadID=503593
Some of them say that the problem may be with jdk version (seems 1.6 and above throw errors). I would assume that may be the case. Try to recompile using earlier versions of jdk and check whether error is still there. If it is not this then we will investigate further.
"I've looked into the code and found out that JUTableBinding.JUTableModel calls
mScrollUnit = control.getScrollableUnitIncrement(null,
SwingConstants.VERTICAL, 0);
(Line 947)
This was okay in Java 5, since JTable's getScrollableUnitIncrement just returned the row height."
"I changed the line to:
mScrollUnit = control.getScrollableUnitIncrement(
control.getVisibleRect(), SwingConstants.VERTICAL, 0);
and everything works fine on Java 6..."
Hope it helps.

Why do I get "Too many open files" errors?

I find myself having to explicitly call System.gc() in my Groovy scripts to prevent errors like the one below. Why doesn't the garbage collector do this for me? Is there something I can do to cause it to garbage collect to prevent these errors (maybe JAVA_OPTS)?
Caught: java.util.concurrent.ExecutionException: org.codehaus.groovy.runtime.InvokerInvocationException: java.io.IOException: Cannot run program "ls": java.io.IOException: error=24, Too many open files
at groovyx.gpars.GParsPool.runForkJoin(GParsPool.groovy:305)
at UsageAnalyzer$_run_closure2_closure6.doCall(UsageAnalyzer.groovy:36)
at groovyx.gpars.GParsPool$_withExistingPool_closure1.doCall(GParsPool.groovy:170)
at groovyx.gpars.GParsPool$_withExistingPool_closure1.doCall(GParsPool.groovy)
at groovyx.gpars.GParsPool.withExistingPool(GParsPool.groovy:169)
at groovyx.gpars.GParsPool.withPool(GParsPool.groovy:141)
at groovyx.gpars.GParsPool.withPool(GParsPool.groovy:117)
at groovyx.gpars.GParsPool.withPool(GParsPool.groovy:96)
at UsageAnalyzer$_run_closure2.doCall(<removed>)
at UsageAnalyzer.run(<removed>)
This stack trace is from a parallel program but it happens in sequential programs as well.
As you're using groovy, you can use the convenient methods such as File.withReader(), File.withWriter(), File.withInputStream(), InputStream.withStream() to ensure resources get closed cleanly. This is less cumbersome than using Java's try .. finally idiom, as there's not need to explicitly call close(), or declare a variable outside the try block.
e.g. to read from a file.
File f = new File('/mumble/mumble/')
f.withReader{ r ->
// do stuff with reader here
}
Definitely look for any place you open files or streams and make sure you close them. It's often beneficial to wrap them like this:
final InputStream in = ...;
try
{
// Do whatever.
}
finally
{
// Will always close the stream, regardless of exceptions, return statements, etc.
in.close();
}

How to get the stacktrace in a mobile device?

I'm getting a NullPointerException in a Nokia S40.
I want to know what is causing this exception.
The device shows:
NullPointerException java/lang/NullPointerException
This error only occurs in the device, running in the emulator the application works fine.
I use microlog to debug my application. But the application works fine if the log is enabled.
Is there a way to get the stack trace when I get this NullPointerException? I don't need all details like the line number just which method cause this exception.
UPDATE: I installed the same application in another Nokia S40 and the same error didn't occur.
Nokia 2660 - error
Nokia 6131 - no error
UPDATE 2: Somehow I find what was causing the NullPointerException.
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
public class OuterClass extends Canvas {
private Config config;
public OuterClass() {
this.config = new Config();
}
public void paint(Graphics graphics) {
HelperClass helper = new HelperClass(this.config);
helper.doStuff();
}
public void dispose() {
this.config = null;
}
public class Config implements IConfig {
public int getSomething() {
// ...
}
}
}
public class HelperClass {
private IConfig config;
public HelperClass(IConfig) {
this.config = config;
}
public doStuff() {
config.getSomething(); // Here is thrown NullPointerException
}
}
In some situations a thread is started and call the OuterClass.dispose() before the helper.doStuff() causing the NPE. I think when I enabled the log it made the thread slower and helper.doStuff() was called when I expected it to be called.
You are not going to find any way to save a Throwable stack trace on a Nokia Series40 handset.
The usual brute force way of debugging JavaME application on Series40 is to modify your code to create a stack trace yourself in memory.
What I'm talking about is:
Each Thread that you can identify (including system callback threads) needs its own Stack object, containing strings. Obviously, this increases the memory footprint of your application somewhat but keeping it in memory should limit the impact on race conditions.
When your code enters a method, it adds the method signature to the current Thread Stack. When the method exits (and you better only have one exit point per method) it pops the top of the Stack.
You can add aditional debug info on the stack, like values of variables in different places of the code.
You don't necessarily need to add this to every single method in your code.
You can add try{}catch(Throwable){} to the entry point of every thread you identified and either dump the stack in a file or on the screen (in a Form).
Obviously, this is not the kind of change you want to manually add in a lot of places in a large existing codebase. You can however make it part of your organisation coding standards for the future and write a source code parsing script to automatically add it to existing code.
I had some trouble in the past trying to print the stack trace to somewhere else than the standard output. The standard exception class doesn't provide the printStackTrace method that receives the output stream, therefore it only prints to the standard output stream.
It's possible, at least in Java SE, to redirect the java output stream to somewhere else by simply saying that System.out = . The PrintStream class receives an OutputStream, which means that you could create your own ByteArrayOutputStream, initialize a PrintStream, sets System.out to that stream, and then call ex.printStackTrace(). I don't have a J2ME environment here but I believe that, as long as it won't break when you try to set System.out to something else (nothing says that it's readonly in the docs), you should be able to do it.
After you do that, I would recommend writing it to a RecordStore that you have specifically for that, and then upload the records of that RecordStore to your server so you can get it.
I know it's not very easy but it may work. I would first test the System.out thing. If it works, everything else should work too.
My answer was wrong. As pointed out, the System.out and System.err fields are declared final. If you can't get the stack trace, and if you can't get the error when running the application on your emulator, try creating trace bullets on your code (alerts, logs, whatever you can) to isolate the piece of code where the problem is happening. It has to be something that could change between the emulator and the real device - for example, something related to retrieving/ saving records in a RecordStore, opening a Connection, etc... What did you try to do when you had the problem?
You could use Microlog to send an e-mail when the exception occurs.
Microlog
You could try catching the exception in some high-level try/catch block and then emailing the trace to yourself.

Categories