Showing posts with label exception. Show all posts
Showing posts with label exception. Show all posts

Tuesday, January 19, 2010

Exception Utility

In JAVA, Throwable/Exception thrown for many reasons. Based on its impact to the application, Throwable category is splitted into two - Exception, Error.

  • java.lang.Exception indicates that malfunction happened, and possible to correct it using try-catch block.
    • Checked Exception must to be captured in try-catch block to succeed compilation
    • UnChecked Exception need not to be captured in try-catch block to get successful compilation. These exceptions are having java.lang.RuntimeException as super class. Examples, java.lang.IllegalArgumentException, java.lang.ArrayIndexOutOfBoundsException. If we feel JVM may throw this RuntimeException then we may need to use try-catch block to capture it. Java compiler will not enforce us to use try-catch block for unchecked exception. It is developer responsibility to catch this exception, and run resolving code.
  • java.lang.Error indicates that serious problem happened which adviced not to capture using try-catch block.

Cause in Exception

In a method, Exception captured using try-catch block and thrown back to the caller method with reconstructing using some other Exception class. For instance, we got some unknown/unexpected exception in a API, which will be used to create instance of caller understandable Exception and send back to them. While reconstructing, Exception catched will be treated as cause in constructed/new Exception.

Here, very first occuring exception is called Actual Cause. Rest are just used to convey the issue to the root of the caller, where we decide alternate for this issue.

We have to know, how the issue throwing API reached from root?. This will be done by traversing stack trace of Thread from the issue araised line of code. Throwable.printStackTrace() used to get the stack trace of complete Exception and Cause. Actual cause will be displayed in end of the trace. If reconstrcution happened in various layer on the Exception then we will get equal number of Cause trace, which may annoy our customer, even developer.

We have to take a call on this and provide only the issue and trace of the same to Customer/log file. Pushing all the Cause trace, impacts peformance in multi-threaded environment, where we do log variety of details to console/Log file parallely, where as console/Log stream is synchronized which blocks/waits for other thread to relase the lock. Pushing minimal and adequate data increase the performance of application.


Exception Util

In the following sample program, APIs are exposed - getCause(), exceptionToString(),printActualCause().

  • getCause() - helps to retrieve actual cause from Exception
  • exceptionToString() - helps to retrieve stacktrace information as a String object
  • printActualCause() - prints the stacktrace, message of actual cause


import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

public class ExceptionUtil {
/**
 * get Actual cause from the exception thrown
 * 
 * @param throwable
 * @return
 */
public static Throwable getCause(Throwable throwable) {
 if (null == throwable)
  return null;
 Throwable cause = getCause(throwable.getCause());
 if (null == cause)
  cause = throwable;
return cause;
}

/** Converts stacktrace to string
 * @param t
 * @return
 */
private static String exceptionToString(Throwable t) {
String stackTrace = null;
OutputStream os = null;
try {
 os = new ByteArrayOutputStream();
 PrintWriter printWriter = new PrintWriter(os);
 t.printStackTrace(printWriter);
 printWriter.close();
 stackTrace = os.toString();
} catch (Exception exc) {
} finally {
 try {
 os.close();
 } catch (Exception e) {
 //do nothing
 }
}
return stackTrace;
}

public static void printActualCause(Throwable throwable)
{
 Throwable cause=getCause(throwable);
 String stack= exceptionToString(cause);
 String msg=cause.getLocalizedMessage();

 System.out.println(msg+"\n"+stack);
}

public static void main(String[] args) {
try
{
 throw new IllegalArgumentException("Actual exception");
}catch(Exception e)
{
 try
 {
  throw new Exception(e);
 }catch(Exception e1)
 {
  printActualCause(e1);
 }
}
} }

Wednesday, January 6, 2010

Part 2: NoRouteToHostException

Part1 : Part2

If following code run without proxy details, then java.net.NoRouteToHostException will be thrown in windows/linux platform


import java.net.Socket;
public class SocketPrg {
public static void main(String[] args) throws Exception{
Socket sock=new Socket("abc.javafundu.com",8001);
}
}


UnknownHostException

Assume, I have given proper proxy details if internet connection established through proxy server. If we refer wrong host name which does not exsit then we do get java.net.UnknownHostException.

Additionally, we may refer right host name then also we do get this exception. In this case we have to check hosts file and correct the entry.

windows: /windows/system32/drivers/hosts
Linux : /etc/hosts

Make following entry in hosts file
127.87.6.207 abc.javafunud.com javafundu.com
Exception will be thrown as below


Exception in thread "main" java.net.UnknownHostException: abc.javafundu.com
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at SocketPrg.main(SocketPrg.java:7)


ConnectException

If host name is correct and hosts points right IP address with wrong port number then ConnectException will be thrown with Connection timed out for remote host most of the time( with default timeout configuration). For localhost or same network host, we do get Connection refused.

Socket sock=new Socket("localhost",8001);


Exception in thread "main" java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at SocketPrg.main(SocketPrg.java:7)

Socket sock=new Socket("javafundu.com",8001);


Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at SocketPrg.main(SocketPrg.java:9)

Tuesday, January 5, 2010

NoRouteToHostException

java.net.NoRouteToHostException thrown when tried to access remote host and port, where firewall blocks the access. In general, -Dhttp.proxyHost and -Dhttp.proxyPort is incorrect then we do get this exception in Linux environment.


import java.io.InputStream;
import java.net.URL;
public class SocketPrg {
 public static void main(String[] args) throws Exception{
  URL url =new URL("http://schemas.xmlsoap.org/soap/envelope/");
  InputStream is=url.openStream();
 }
}

javac SocketPrg.java

java SocketPrg

In Linux, the following exception will be thrown

Exception in thread "main" java.net.NoRouteToHostException: No route to host
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:519)
at java.net.Socket.connect(Socket.java:469)
at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:233)
at sun.net.www.http.HttpClient.New(HttpClient.java:306)
at sun.net.www.http.HttpClient.New(HttpClient.java:323)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:852)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:793)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:718)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1041)
at java.net.URL.openStream(URL.java:1009)
at SocketPrg.main(SocketPrg.java:16)

In Windows, the following exception will be thrown for the above program

Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at SocketPrg.main(SocketPrg.java:16)

Run the above, program with commandline arguments with proper proxy settings

Solution:
java -Dhttp.proxyHost=www-proxy.us.abc.com -Dhttp.proxyPort=80 SocketPrg

Tuesday, December 29, 2009

StuckThread Exception

In Application server, mangaged/unmanaged threads can run continuously without interrupting/sleep/wait for a given/sliced time. If the thread exceeds the maximum time configured for StuckThreadMaxTime.

Server keeps the track of when the thread started and how long continuously running, once the thread exceeds time immediatly the respective thread state will changed to STUCK and incident error will be thrown. However, thread will be kept running. Hence, we can consider this as benign error message.

Administrator can take call on based on how many times, this issue comes in a day, and what is the sevearity of this issue giving thread.

Each application server has the provision to configure the max time. We may have a question, why this limitation is required for Server? , this limitation needed for security reasons. Assume that, we have deployed a web application where HTTP call made by crackers/hackers to stop responding application for intented customer by keeping server always busy. Server helps us by notifying server panic state by throwing this error message.

In weblogic, default value for stuckThread Max Time would be 600s.

Environment > servers > soa_server > Configuration > Tuning > change Stuck Thread Max Time

This value has to be changed only when we get stuck thread exception and increasing this number may degrade performance. Maximum 1200s would be the recommended value for weblogic server.


<Apr 3, 2009 4:30:26 PM PDT> <Error> <WebLogicServer> <BEA-000337> <[STUCK] 
ExecuteThread: '1' for queue: 'weblogic.ker 
nel.Default (self-tuning)' has been busy for "1,301" seconds working on the 
request "org.bank.BankUtilityBean_fq50_EOImpl", which is more than the 
configured time (StuckThreadMaxTime) of "1,200" seconds. Stack trace: 
java.net.SocketInputStream.socketRead0(Native Method) 
java.net.SocketInputStream.read(SocketInputStream.java:129) 
oracle.net.ns.Packet.receive(Packet.java:240) 
oracle.net.ns.DataPacket.receive(DataPacket.java:92) 
oracle.net.ns.NetInputStream.getNextPacket(NetInputStream.java:172) 
oracle.net.ns.NetInputStream.read(NetInputStream.java:117) 
oracle.net.ns.NetInputStream.read(NetInputStream.java:92) 
oracle.net.ns.NetInputStream.read(NetInputStream.java:77) 
oracle.jdbc.driver.T4CMAREngine.unmarshalUB1(T4CMAREngine.java:1034) 
oracle.jdbc.driver.T4CMAREngine.unmarshalSB1(T4CMAREngine.java:1010) 
oracle.jdbc.driver.T4C8TTILob.receiveReply(T4C8TTILob.java:847) 
oracle.jdbc.driver.T4C8TTILob.write(T4C8TTILob.java:243) 
oracle.jdbc.driver.T4CConnection.putBytes(T4CConnection.java:2078) 
oracle.sql.BLOB.setBytes(BLOB.java:698) 

Saturday, December 26, 2009

IOException: Broken pipe

java.io.IOException: Broken pipe

In Client server application, Message send from/to. If message size is less than 10MB, then we would have not faced any issues. Since most of the application/web server comes with default configuration for message size to 10MB or more.

Usecase : upload a zip file from client to server

In server side, any of the endpoints like Servlet(http), EJB, JMS, or TCP, has to be established to receive message as byte array or byte array holding java objects. Stream objects can not be serialized, it has to be stored as byte and trasmitted. While marshalling and unmarshalling byte array object, Heap usage go to the peak. In this time, we may get OutOfMemoryException

In Client Side, InputStream created to read data from file and convert into byte array.

If server receives message more than the size configured then server will throw weblogic.socket.MaxMessageSizeExceededException

<ExecuteThread: '1' for queue: 'weblogic.socket.Muxer'> <<WLS Kernel>> <> <> <1229479358244> 
<BEA-000403> <IOException occurred on socket: Socket[addr=/127.1.1.34,port=281 30,localport=8001] 
weblogic.socket.MaxMessageSizeExceededException: Incoming message of size: '10000080' bytes 
exceeds the configured maximumof: '10000000' bytes for protocol: 't3'.>
at weblogic.socket.BaseAbstractMuxableSocket.incrementBufferOffset(BaseAbstractMuxableSocket.java:174)
at weblogic.rjvm.t3.MuxableSocketT3.incrementBufferOffset(MuxableSocketT3.java:343)
at weblogic.socket.SocketMuxer.readReadySocketOnce(SocketMuxer.java:906)
at weblogic.socket.SocketMuxer.readReadySocket(SocketMuxer.java:842)
at weblogic.socket.JavaSocketMuxer.processSockets(JavaSocketMuxer.java:335)
at weblogic.socket.SocketReaderRequest.run(SocketReaderRequest.java:29)
at weblogic.work.ExecuteRequestAdapter.execute(ExecuteRequestAdapter.java:21)
at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:145)
at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:117)

If server receives message even with in the limit, but while unmarshalling data, application exceeds heap size, then server will drop the connection established with client abrubtly with OutOfMemoryException. Since connection got closed then we do get IOException as below.

java.io.IOException: Broken pipe
at java.net.SocketOutputStream.socketWrite(Native Method)
at java.net.SocketOutputStream.write(SocketOutputStream.java:83)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:72)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:130)
at java.io.FilterOutputStream.flush(FilterOutputStream.java:123)
at weblogic.net.http.ContentLengthOutputStream.close(ContentLengthOutputStream.java:56)


Note:Broken pipe message comes for anytime stream could not able to write/read data from file(socket). In general, heart beat will be delivered by server/client in stipulated format. If this max number of attempts cross then application assumes that socket is closed by other party and throws this exception.


Weblogic

In weblogic server console or config xml, we can set maximum message size only to the http protocol or t3 or all the protocols.

Environment > servers > soa_server > protocols > General > change Maximum Message Size as below

<max-message-size>100000000</max-message-size>
<max-t3-message-size>100000000</max-t3-message-size>
<max-http-message-size>100000000</max-http-message-size>
The above code set 100mb for these properties. These configuration helps to intimate the server that maximum message of receiving capacity. There is no configuration required to be configured to send message from server.

What about client side, to receive 100 mb message?

Yes, we have to set weblogic.MaxMessageSize config property in commandline.

-Dweblogic.MaxMessageSize=100000000


Refer this link supported maximum message size in weblogic

Java Management Extensions (JMX)

Java Management Extensions (JMX)

Application is running for a long time suddenly started performing not good. We do not have any clue at this time. Idea started early 1998, there should be a way to interact the application from a local/remote vM to monitor and maintain the resource. For example, HeapSize almost reached maxSize and full collector not yet triggered, in this time we could make a request for GC from our application. This may not be the right solution, however, we can avoid OOM Exception.

In clustered environment, application may share the same configuration. User may update property in one node, which has to be replicated in other environment in flexible way. We cannot use tightly coupled model, since in failover scenario this will cause more pain to us. JMX Remote API, solves this problem by Change notification mechanism.

JSR details:

  • JSR 3 - Java Management Extensions
  • JSR 160 - JMX Remote API
  • JSR 255 - JMX 2.0


Typical uses of the JMX technology include:

  • Consulting and changing application configuration
  • Accumulating statistics about application behavior and making them available
  • Notifying of state changes and erroneous conditions.

The resources are instrumented as JAVA Object, known as Managed Beans(MBean). MBeans and its services sare registered in a Object Server, known as MBean Server or JMX agents. JMX Connectors helps agent to connect remote VM.

  • enables Java applications to be managed without heavy investment
  • provides a standard way to manage Java technology-based applications, systems, and networks
  • can be used for out-of-the-box management of the Java VM
  • provides a scalable, dynamic management architecture
  • leverages existing standard Java technologies
  • integrates easily with existing management solutions and emerging technologies. JMX solutions can use lookup and discovery services and protocols such as JiniTM network technology and the Service Location Protocol (SLP).

Examples TechNote

Thursday, December 24, 2009

Oracle JRockit : OutOfMemoryError

Oracle JRockit : OutOfMemoryError

Thread Local Area and LargeObjectOrArray


In JRockit, Each thread allocates TLA (Thread Local Area) to store short living objects, and benefits GC to reclaim space. The repective thread can then allocate
objects in its TLA without synchronizing with other threads. If particular TLA size become full, then new TLA will be alotted. In general, we think that by specifying bigger number for TLA we get best performance. But reality is not that case, whenever new thread starts, TLA size has to be reserved with minimum space mentioned in tlasize.



We can specify what could be the largeObject or Array size needs to be stored in TLA, others goes to Heap. Recommendation would be, -XXtlasize:min and -XXlargeObjectLimit has to be equivalent and -XXtlasize:preferred size must to set minimum double the -XXlargeObjectLimit value.



-XXtlasize:min=3k -XXtlasize:preferred=10k -XXlargeObjectLimit=3k

Above configuration tells JVM that 3k objects are larger and it should not go to TLA. Each TLA can grow maximum 10k. If application starts/maintains maximum of 100 threads and all operates on its own data (mean, no synchronization required), then specifying bigger number for TLA, would help to increase the application.



Exception in thread "PoolThread" java.lang.OutOfMemoryError: allocLargeObjectOrArray - Object size: 586154000, Num elements: 586153984
Cause: allocLargeObjectOrArray - Object size: 65552, Num elements: 32768



In the above exception Object Size specifies the size of the Object trying to store in old space with Num elements. This is due to poor garbage collection triggered.



Nursery Size


-Xns option used to specify the size of Nursery. Garbage collection happens quickly in Smaller nursery and larger size takes longer. This size has to be defined based on the application memory usage, and eventually it is Performance Engineer responsibility to set memory settings to make sure that as many object as possible are garbage collected by young collection rather than old collection.Recommended value for this size would be half of the free heap size.



-Xns=100m

-XXkeepAreaRatio:<percentage> used to keep the young and old collection frequency. If ratio high young generation will be triggered often.



Garbage Colletor


JRockit R27.3.0 and later releases offers various types of collector. It is our responsibility to find best suiting option to our application.




Static garbage collector


-Xgc:<strategy>
-Xgc:genpar - generational parallel garbage collector
-Xgc:gencon - To use a generational concurrent garbage collector

-Xgc:singlecon - To use a single-spaced concurrent garbage collector
-Xgc:singlepar - single-spaced parallel garbage collector


Dynamic garbage collector


-XgcPrio:<mode>
-Xgcprio:throughput - gives priority for throughput
-XgcPrio:pausetime -XpauseTarget=40ms - gives priority for pause time
-XgcPrio:deterministic -XpauseTarget:40ms - gives priority for throughput and not crossing pause time


Parallel Mark and Sweep

While garbage collection other Java threads will be paused- genpar and singlepar.



Mostly Concurrent Mark and Sweep

While garbage collection all other JAVA threads will not be paused, if no necessary of synchronization - singlecon and gencon.



For more details, visitOracle JRockit

Sunday, December 20, 2009

Externalizable

java.io.Externalizable



Externalizable interface extends java.io.Serializable, whereas this interface comes with two methods to store and retrieve data from Object Stream and this is not marker interface. This approach gives luxury of deciding to application developer, what to be serilized and what not to be. However, this technique enforces that the order in it stored in stream, the same order, has to be used to read back.




import java.io.Externalizable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class ExternalizableTest {

public static class EmployeeBean implements Externalizable {

private static final long serialVersionUID = 4258520358186173223L;

String name;

String designation;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getDesignation() {
return designation;
}

public void setDesignation(String designation) {
this.designation = designation;
}

public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
// TODO Auto-generated method stub

name= (String)in.readObject();
designation=(String)in.readObject();

}

public void writeExternal(ObjectOutput out) throws IOException {
// TODO Auto-generated method stub
out.writeObject(name);
out.writeObject(designation);
}
}
public static void main(String[] args) throws Exception {

ExternalizableTest.EmployeeBean emp = new EmployeeBean();

emp.setName("Krishna");

FileOutputStream bos = new FileOutputStream(new File("/tmp/a.txt"));
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(emp);
out.close();

FileInputStream bis = new FileInputStream(new File("/tmp/a.txt"));
ObjectInputStream in = new ObjectInputStream(bis);
EmployeeBean empFromPersist = (EmployeeBean) in.readObject();
System.out.println("Employee name from persisted Bean ::" + empFromPersist.getName());
in.close();
}

}



The above code will stores and retrieves two fields.



If number of read operations is not equivalent in readExternal to write operations in writeExternal then following Exception



Exception in thread "main" java.io.OptionalDataException
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1349)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
at ExternalizableTest$EmployeeBean.readExternal(ExternalizableTest.java:42)
at java.io.ObjectInputStream.readExternalData(ObjectInputStream.java:1792)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1751)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
at ExternalizableTest.main(ExternalizableTest.java:65)

Wednesday, December 16, 2009

NoClassDefFoundError

java.lang.ClassNotFoundException and java.lang.NoClassDefFoundError



java.lang.ClassNotFoundException vs java.lang.NoClassDefFoundError



JAVA throws for fatal issues Error and recoverable issues as Exception. While it comes to class loading exception/error, it is really a myth for developer, who are novice to classloader and its behaviour. Aforementioned classes get used to intimate the issue based on the nature of the class loading.



In general, these issues raises for the same reason of non-existing class in run time. The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found in the time of Application getting executed.




ClassLoader



ClassLoader used to load the bytecodes and convert the same to runnable format based on the platform. In classLoader, findClass() and loadClass() are the methods which helps us to create the instance of objects. loadClass() method get called by JVM, to load class, where new class reference found in the application. If already the definition of class found then Class object will be returned. If given class reference not loaded already then findClass() get called and implementation of this method responsible to find the binary for the class. Once binary found then findClass() method which calls defineClass() to return Class object.



ClassNotFoundException



This class extends Exception. After throwing this exception also ClassLoader can able to proceed and will not break the application.

Thrown when an application tries to load in a class through its string name using:


  • The forName method in class Class.
  • The findSystemClass method in class ClassLoader. This is final method and get called by JVM..
  • The loadClass method in class ClassLoader.

but no definition for the class with the specified name could be found. Default implementation of findClass() also throws ClassNotFoundException.



The above mentioned APIs are pretty safe and mostly used to make lazy loading of classes. Even specified class not found also, no issues application implementor can decide to take alternate approach of business.



For instance, We have Web container application, and ClassLoader is written by us to load classes(eg: Servlet) which are comes part of web application. While doing web application deployment, our ClassLoader has to load the classes referred in web.xml as Servlet. If any one of the class not found then it has to throw just an exception, and rollback deployment. No need of webcontainer stop, it can continue to doing its business.



ClassNotFoundException.java
public class ClassNotFoundExceptionTest {
public static void main(String[] args) {
Class.forName(""); // empty space also throws ClassNotFoundException
ClassLoader.getSystemClassLoader().loadClass("NonExistingClass$subclass"); // non-existing class in classpath
}}


$javac *.java

$java ClassNotFoundExceptionTest
Exception in thread "main" java.lang.ClassNotFoundException:
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at ClassNotFoundExceptionTest.main(ClassNotFoundExceptionTest.java:4)


Comment Class.forName(""); line and compile and run

Exception in thread "main" java.lang.ClassNotFoundException: NonExistingClass$subclass
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:303)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at ClassNotFoundExceptionTest.main(ClassNotFoundExceptionTest.java:5)





NoClassDefFoundError



This error occurs whenever JVM could not able to progress application due to non-existing class reference found in object creation.



Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.




Create following classes in a same folder and compile both java files.

MainClass.java
public class MainClass {
public static void main(String[] args) {
Object a= new NonExistingClass();
}
}
NonExistingClass.java
public class NonExistingClass {}



$javac *.java

$java MainClass
No error will be thrown

$ rm NonExistingClass.class

$ java MainClass
Exception in thread "main" java.lang.NoClassDefFoundError: MainClass
Caused by: java.lang.ClassNotFoundException: MainClass
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
Could not find the main class: MainClass. Program will exit.



Evenmore, we can see NoClassDefFoundError in JVM startup, by refering non-existing class
$ java NonExistingClass
Exception in thread "main" java.lang.NoClassDefFoundError: NonExistingClass
Caused by: java.lang.ClassNotFoundException: NonExistingClass
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
Could not find the main class: NonExistingClass. Program will exit.

Tuesday, December 15, 2009

java.util.concurrent.CyclicBarrier JSR166

java.util.concurrent.CyclicBarrier

Assume the scenario, I have to transfer money from my bank account to my friend account. In the first phase, my account details and balance is verified and validate. Now, amount has to be debited in my account and creadited in my friend account. While commiting the changes in these two transaction, if any exception comes then these two activity has to be get informed. credit/debit operations are happening in multithreaded environment, How to achive this scenario. In older ages, we have to reiniate two more threads to rollback these operation.



CyclicBarrier helps us to achive this and intimate back to the threads who are all waiting for the commit operation, to take necessary action using the exception BrokenBarrierException. The CyclicBarrier uses an all-or-none breakage model for failed synchronization attempts. Common operation which needs to run at the end of multiple threads operation, will go in Runnable implementation.



We do not wants to do any special operation as common for all the threads, however we wants to end all the thread in same time. For example, first thread may take 5minutes to complete the operation, whereas second thread may take 1Hour to complete. Assume T2 has to complete prior to T1 thread completion, then CyclicBarrier has to instantiate without Runnable object.



import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierTest {
public static void main(String[] args) {
final CyclicBarrier cb = new CyclicBarrier(2, new Runnable() 
{
public void run() {
System.out.println("Commit Operation - Completed");
}
});

new Thread() {
@Override
public void run() {
try{sleep(1000);}catch(Exception e){}
System.out.println("T1 pre-commit");
try
{
cb.await();
}catch (Exception e)
{
//do something commit operation failed
}
System.out.println("T1 post-commit");
}
}.start();

new Thread() {
@Override
public void run() {
try{sleep(1000);}catch(Exception e){}
System.out.println("T2 pre-commit");
try
{
cb.await();
}catch (Exception e)
{
//do something commit operation failed
}
System.out.println("T2 post-commit");
}
}.start();
}
}

Monday, December 14, 2009

Thread : Wait and Notify

Thread : Wait and Notify



We use sleep() method in Thread to pass the thread for some milliseconds/nanoseconds and resume the thread on its own. However, while waiting for the shared resource, this will not help.

In JAVA, Object class comes with wait() and notify/notifyAll methods, which helps us to mark saying, I am waiting for this object, who ever owns object monitor lock, release and let me know. While calling this methods, we have to own the object monitor lock of this





public class WaitNotifytest {
static Object obj=new Object();

public static void main(String[] args) throws Exception{
new Thread()
{
@Override
public void run() {
try
{
obj.wait();
}catch(Exception e)
{
e.printStackTrace();
}
}
}.start();

new Thread()
{
@Override
public void run() {
obj.notify();
}
}.start();

Thread.sleep(1000);
}
}




If the above program will throw java.lang.IllegalMonitorStateException

java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:485)
at WaitNotifytest$1.run(WaitNotifytest.java:21)
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.notifyAll(Native Method)
at WaitNotifytest$2.run(WaitNotifytest.java:59)




notify and wait with Object monitor lock



notify() method awakes only one thread in the queue(no gaurantee in order), rest has to wait for awakened thread to notify().





public class WaitNotifytest {
static Object obj = new Object();

public static void main(String[] args) throws Exception {

new Thread() {
@Override
public void run() {
try {
synchronized (obj) {
obj.wait();
System.out.println("T1");
obj.notify();
}

} catch (Exception e) {
e.printStackTrace();
}
}
}.start();

new Thread() {
@Override
public void run() {
try {
synchronized (obj) {
obj.wait();
System.out.println("T2");
obj.notify();
}

} catch (Exception e) {
e.printStackTrace();
}
}
}.start();

new Thread() {
@Override
public void run() {
synchronized (obj) {
obj.notify();
}

}
}.start();
}
}



notifyAll


Each thread notifies after usage of object. If T1 and T2, wants to make read access of object then T3 alone notfiy to all the threads. To do this notifyAll() method get used. This method should only be called by a thread that is the owner of this object's monitor, otherwise we will get the IllegalMonitorStateException. Awakened Threads will compete each other runs/access this object.




public class WaitNotifytest {
static Object obj = new Object();

public static void main(String[] args) throws Exception {

new Thread() {
@Override
public void run() {
try {
synchronized (obj) {
obj.wait();
System.out.println("T1");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();

new Thread() {
@Override
public void run() {
try {
synchronized (obj) {
obj.wait();
System.out.println("T2");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();

new Thread() {
@Override
public void run() {
synchronized (obj) {
obj.notifyAll();
}
}
}.start();
}
}


In this program only one notifyAll method called on object to release all the lock.

Note:

  • If wait() called on the object and no notify signal received then this wait called thread will wait for ever. However, there could be a chance of thread awaking without any of notificatin like notify, timeout or interrupt. This is called spurious wakeup. This will happen in rare condition.


  • We can even specify the time, how long maximum this thread to wait to acquire the lock, even if other thread is not signalled notify/notifyAll, however object lock is released and no other thread acquires lock of this object.



wait with max timeout




public class WaitNotifytest {
static Object obj = new Object();

public static void main(String[] args) throws Exception {

new Thread() {
@Override
public void run() {
try {
synchronized (obj) {
obj.wait(400);
System.out.println("T1");
// obj.notify();

}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();

new Thread() {
@Override
public void run() {
synchronized (obj) {
try{Thread.sleep(10000);}catch(Exception e){}
// obj.notifyAll();

}
}
}.start();
}
}

java.util.ConcurrentModificationException and ConcurrentHashMap

ConcurrentModificationException comes whenever modification happened in the time of iteration operation happening in the Collections objects like HashMap, AbstractList and etc.,

Eventually within the iterator loop, if we try to add item to Map also we get this exception.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;


public class concurrentMaptest {

public static void main(String[] args) throws Exception{
final Map<Integer,Integer> m= new HashMap<Integer, Integer>();
for(int i=0;i<1000;i++)
{
m.put(i, i);
}

new Thread()
{
@Override
public void run() {
Iterator<Entry<nteger,Integer>> it=m.entrySet().iterator();
while(it.hasNext())
{
Entry<nteger,Integer> ent=it.next();

m.put(ent.getKey()+1, ent.getValue());
}
}
}.start();

new Thread()
{
@Override
public void run() {
Iterator<Entry<nteger,Integer>> it=m.entrySet().iterator();
while(it.hasNext())
{
it.next();
it.remove();
}
}
}.start();

Thread.sleep(1000);

System.out.println(m);
}
}



Following exception trace will be the outcome of this program

Exception in thread "Thread-0" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
at java.util.HashMap$EntryIterator.next(Unknown Source)
at java.util.HashMap$EntryIterator.next(Unknown Source)
at concurrentMaptest$1.run(concurrentMaptest.java:24)


java.util.concurrent.ConcurrentHashMap



java.util.concurrent.ConcurrentHashMap is an utility class which follows complete spec of HashMap( except null key is not allowed) and makes lock-free threadsafe collection operations.


For instance, change the HashMap declaration line as below and run the program, we won't face any Exception

final Map<Integer,Integer> m= new ConcurrentHashMap<Integer, Integer>(); 



Tuesday, October 6, 2009

JAXB version attribute must be present

Add/set jaxb:version attribute in schema tag to avoid this exception

<xsd:schema
targetNamespace="http://xmlns.abc.com/"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:lite="http://xmlns.abc.com/"
xmlns:common="http://xmlns.oracle.com/integration/b2b/common"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
jaxb:version="1.0" elementFormDefault="qualified">

Saturday, April 25, 2009

weblogic.jdbc.extensions.ConnectionDeadSQLException: weblogic.common.resourcepool.ResourceDeadException

weblogic.jdbc.extensions.ConnectionDeadSQLException: weblogic.common.resourcepool.ResourceDeadException


MisfireHandler: Error handling misfires: Failed to obtain DB connection
from data source 'soaNonManagedDS': java.sql.SQLException: 
Could notretrieve datasource via JNDI url 'jdbc/SOALocalTxDataSource' 
weblogic.jdbc.extensions.ConnectionDeadSQLException: 
weblogic.common.resourcepool.ResourceDeadException: 
0:weblogic.common.ResourceException: Could not create pool connection. 
The DBMS driver exception was: Socket read timed out[[org.quartz.JobPersistenceException: 
Failed to obtain DB connection from data source 'soaNonManagedDS': 
java.sql.SQLException: Could not retrieve datasource via JNDI url 
'jdbc/SOALocalTxDataSource' weblogic.jdbc.extensions.ConnectionDeadSQLException: 
weblogic.common.resourcepool.ResourceDeadException: 0:weblogic.common.ResourceException: 
Could not create pool connection. The DBMS driver exception was: Socket read timed out 
[See nested exception: java.sql.SQLException: Could not retrieve datasource via JNDI 
url 'jdbc/SOALocalTxDataSource' weblogic.jdbc.extensions.ConnectionDeadSQLException: 
weblogic.common.resourcepool.ResourceDeadException: 0:weblogic.common.ResourceException: 
Could not create pool connection. The DBMS driver exception was: Socket read timed out] 
at org.quartz.impl.jdbcjobstore.JobStoreCMT.getNonManagedTXConnection(JobStoreCMT.java:167) 
at org.quartz.impl.jdbcjobstore.JobStoreSupport.doRecoverMisfires(JobStoreSupport.java:3011) 
at org.quartz.impl.jdbcjobstore.JobStoreSupport$MisfireHandler.manage(JobStoreSupport.java:3789) 
at org.quartz.impl.jdbcjobstore.JobStoreSupport$MisfireHandler.run(JobStoreSupport.java:3809)


The above exception comes while reserved connection test started by application server while all connections are used by application. In general, we can stop the Application server test on connection, if we are running heavy load application. In Application console, we have to set Connection Pool param "test-connections-on-reserve" as false


Sample:

<jdbc-connection-pool-params> 
 <initial-capacity>0</initial-capacity>
 <max-capacity>50</max-capacity>    
 <capacity-increment>1</capacity-increment>    
 <connection-creation-retry-frequency-seconds>10</connection-creation-retry-frequency-seconds>    
 <test-frequency-seconds>300</test-frequency-seconds>    
 <strong><test-connections-on-reserve>false</test-connections-on-reserve> </strong>   
 <test-table-name>SQL SELECT 1 FROM DUAL</test-table-name>    
 <seconds-to-trust-an-idle-pool-connection>0</seconds-to-trust-an-idle-pool-connection>
</jdbc-connection-pool-params>
Read more about unexpected exception while enlisting

Tuesday, March 31, 2009

Reading Bytes From Any InputStream

Reading Bytes From Any InputStream

Most of the time, we do get available bytes in one stroke by calling read() API in InputStream.

long length = is.available();
byte[] bytes = new byte[(int) length];
is.read(bytes);
System.out.println(new String(bytes));

The above given code may not work for InputStream which reads data from socket. Means, this will not read full data from the stream, reason could be
  • network delay in transmitting content
  • mounted filesystem unlinked
  • message size is exceeds TCP window size
  • etc.,
.

Hence, the following code will make sure and helps us to check whether all the bytes are received or not.


public static byte[] getBytesFromInputStream(InputStream is)
throws IOException {

// Get the size of the file
long length = is.available();

if (length > Integer.MAX_VALUE) {
// File is too large
}

// Create the byte array to hold the data
byte[] bytes = new byte[(int) length];

// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}

// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file ");
}

// Close the input stream and return bytes
is.close();
return bytes;
}

Read more : Reverse Reading

Sunday, November 18, 2007

OutOfMemoryExceptions

The throughput collector will throw an out-of-memory exception if too much time is being spent doing garbage collection.

For example, if the JVM is spending more than 98% of the total time doing garbage collection and is recovering less than 2% of the heap, it will throw an out-of-memory expection. The implementation of this feature has changed in 1.5. The policy is the same but there may be slight differences in behavior due to the new implementation.

About Generational GC
JVM heap size
Heap Size
Heap Size Options
Heap Size
OutOfMemoryExeception

Recent Posts

Unix Commands | List all My Posts

Texts

This blog intended to share the knowledge and contribute to JAVA Community such a way that by providing samples and pointing right documents/webpages. We try to give our knowledege level best and no guarantee can be claimed on truth. Copyright and Terms of Policy refer blogspot.com