Sunday, September 12, 2010

Friday, September 10, 2010

Print Java class/method name, line number in your log file

Sometime it's very helpful to print verbose information in the log file, of course it will have impact on your performance.

Get class name is very easy, but dynamically get the method name and line number at the point you put your log message need you get help from Throwable class,

When we call new Throwable(), in the constructor, it first call fillInStackTrace() method, after the object is created, we could call throwable.getStackTrace() which returns an array of StackTraceElement, StackTraceElement[0] will be the method which creates the Throwable() object, StackTraceElement[1] will be the one outside the preivous mehtod, and so on. For exampe:

Wednesday, September 8, 2010

Use of ThreadLocal class

ThreadLocal helps to maintain a separate copy of the value for each thread that use it, it is often used to prevent sharing in designs based on mutable Singletons or global variables.
Conceptually, you can think of a ThreadLocal as holding a Map that stores the thread specific values, but the real implementation is not this way, the read data actually stored in the Thread object itself.

In Thread class, there are two private variables:
ThreadLocal.Values localValues;
ThreadLocal.Values inheritableValues;

Here is how the real per-thread values are stored. (ThreadLocal.set()):

public void set(T value) {
Thread currentThread = Thread.currentThread();
Values values = values(currentThread);
if (values == null) {
values = initializeValues(currentThread);
}
values.put(this, value);
}

Values values(Thread current) {
return current.localValues;
}

Values initializeValues(Thread current) {
return current.localValues = new Values();
}

From the above code, we may see that ThreadLocal set values into Thread object's
localValues variable.When the thread terminates, the thread-specific values can be GCed.

For details please see:
crazybob.org: Hard Core Java: ThreadLocal


Improve your Java code performance

1. JDK 1.5 and above provide some new features to replace some old implementations:

  • StringBuilder is a replacement of StringBuffer

StringBuffer instances are almost always used by a single thread,yet they perform

internal synchronization. It is for this reason that was essentially replaced by StringBuilder,

which is an unsynchronized

  • Vector and ArrayList, if you create and modify the Vector within a method, ArrayList

will have better performance

2. If you only need read data from a collection, Collections.unmodifiable() will return the read-only view of

the passed in colleciton, you don't need to create a copy of the data, and you will consume less memory,

make less impact on garbage collector, and make the program faster.

Posted via email from Progress

Monday, August 9, 2010

Using and Understanding PageContext in JSP

PageContext is an abstract class which extends javax.servlet.jsp.JspContext, it provides context information when JSP is used in servlet environment, it is obtained by calling JspFactory.getPageContext(), and released by calling JspFactory.releasePageContext().

PageContext provides a single API to access various scope namespaces. Obtains an instance of an implementation dependent javax.servlet.jsp.PageContext abstract class for the calling Servlet and currently pending request and response.

JspFactory.getPageContext() is typically called early in the processing of the _jspService() method of a JSP implementation class in order to obtain a PageContext object for the request being processed.

Invoking this method shall result in the PageContext.initialize() method being invoked. The PageContext returned is properly initialized.

All PageContext objects obtained via this method shall be released by invoking releasePageContext().

Signature:

public abstract PageContext getPageContext(Servlet servlet,
ServletRequest request,
ServletResponse response,
String errorPageURL,
boolean needsSession,
int buffer,
boolean autoflush)

Example:

public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {

PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;


try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();

For every request, there will be one PageContext instance created and populated properly( various scope values)

Before the _jspService() method return, it will invoke JspFactory.releasePageContext() method, results in the PageContext.release()

method is invoked.

...

} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}

Posted via email from Progress

Monday, July 19, 2010

When does SSL Handshake happen?

SSL protocol sits on top of the transport layer but below application layer in the OSI protocol.

So the SSL handshake happens after the accept() method returned, that is, after the TCP connection is

established.

When SSLSockets are first created, no handshaking is done so that applications may first set their communication preferences: what cipher suites to use, whether the socket should be in client or server mode, etc.

The initial handshake on this connection can be initiated in one of three ways:

  1. Calling startHandshake which explicitly begins handshakes, or
  2. Any attempt to read or write application data on this socket causes an implicit handshake, or
  3. A call to getSession tries to set up a session if there is no currently valid session, and an implicit handshake is done.

Posted via email from Progress

Sunday, July 18, 2010

SSL, KeyStore and Key password

SSL server socket can be created by:
  • Calling SSLServerSocketFactory: SSLServerSocketFactory.getDefault()
    The default implementation can be specified in $JREHOME/lib/security/java.security by
    ssl.ServerSocketFactory.provider, but by default, it is not specified, instead, a internal
    implementation is used( JSSE: com.sun.net.ssl.internal.ssl.SSLServerSocketFactoryImpl)

    When this (default) implementation is used, you must specify:
    • keystore using javax.net.ssl.keyStore, if not, an empty keystore object will be managed by the KeyManager
    • keystore passwrod using javax.net.ssl.keyStorePassword
      Notice here,for the getDefault() will lead to the default SSLContext, default
      KeyManager, default TrustManager. And the most important thing is, you can only
      specify the keystore password, there is no way to specify the keys' password
      the system properties.


      For the SSL Socket created by the calling of getDefault(),the specified Keystore and the keys in the keystore must have the same password.

      Only the default implementation and is used, requires the keystore password and the keys' password must be the same.
  • Using customized SSLContext to create SSLSocket
For example:


try {
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(secureKeyStore.asInputStream(keystorePath), secureKeyStore
.getKeyStorePassword());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
kmf.init(ks, secureKeyStore.getCertificatePassword());
serverContext = SSLContext.getInstance(PROTOCOL);
serverContext.init(kmf.getKeyManagers(), SecureTrustManagerFactory
.getTrustManagers(), null);
} catch (Exception e) {
e.printStackTrace();
throw new Error("Failed to initialize the server-side SSLContext",
e);
}

In the code above, we may notice, the kmf.init(KeyStore keystore, char[] pass) method accepts two arguments, the second one specifies the password for the key(s) or certificate(s).

Note that only one password is used in this method, so the keystore must use the same
password for all the private keys it stores, and there is no requirements this password must
be the same as the keystore password( but the default implementation requires this).

If the keys in the keystore have different password, the JSSE KeyManagerFactory.init() mehtod will throw UnrecoverableKeyException. Some other implementation may just return the matched key(s), but JSSE does not.