Monthly Archives: July 2016

Tomcat gets stuck during start up?

It takes more than 5 minutes for your tomcat to startup.  You think it’s your application’s program. But when you download a clean Tomcat (of the same version) can run it without dropping in any of your applications, it still gets stuck. 

It may be caused by this:

According to my just wasted 2 hours, it can be true and solution presented on it will work. 

Call Java compiler programatically

You don’t need to add any dependency

	private static void doCompile(File sourceDir) throws SomeException {
		System.out.println("Compiling started");
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		DiagnosticCollector diagnostics = new DiagnosticCollector();
		StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
		Collection files = FileUtils.listFiles(sourceDir, new String[] { "java" }, true);		 
		Iterable compilationUnits = fileManager.getJavaFileObjectsFromFiles(files);
		List compilerOptions = Arrays.asList("-source", "1.6", "-target", "1.6");
		JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, compilerOptions, null, compilationUnits);
		boolean success =;
		try {
		} catch (IOException e) {
			// ignore it
		if (!success) {
			StringBuffer errors = new StringBuffer();
			for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
				errors.append(String.format("Compilation Error on line %d in %s", diagnostic.getLineNumber(), diagnostic)).append("\n");
			throw new SomeException(errors.toString());

Tips for traversing a tree with stacks


Here are the tips of my solution:

  • You always push the root to the stack first
  • The most difficult part is: when you see a node on the top of element, should you go on to push its children, or pop it to print it? 
    • For pre-order traversal, you can pop it then push their children.  
    • For in-order traversal, you need to check whether its left child has been popped yet.  If yes, pop it; else, push its left child. 
      • You can add a flag to the node when it is pushed to stack with initial value equals to False.  
      • Enquiry this flag before deciding whether to pop current node.  If True, do a pop; If False, set this flag as True before pushing its left child. 
      • You should set the flag to True even if its left child is Null
    • For post-order traversal, you need to check whether both its children have been popped yet. This time you need two flags. 

Propagate data change from RDBMS to Solr

Basically, you will use solr’s DataImportHandler to do the importing.

  • Hit http://solr-server:port/solr/db/dataimport?command=full-import to do a full import.
  • Hit http://solr-server:port/solr/dataimport?command=delta-import to do a delta import

So, what’s the delta? This is configured in some data-config.xml:

deltaQuery="select id from item where last_modified > '${dih.last_index_time}'" 

So it requires the table on your database must have a column called "last_modified" .

No PermGen any more in Java 8

All the class definitions now go to an area called "Metaspace".  GC based on references is faster than it was in PermGen.

Metaspace is in native-memory zone.  Its size is unlimited by default.  So as long as your machine has enough memory, OOM will not happen. 

You can still set a limit to it with parameter "MaxMetaspaceSize".  On reaching this size, a GC will be done by the JVM. 

G1 v.s. CMS

G1 also aims at "low pause", and it can work well on large heaps(over 4G) .  

CMS, on the other hand, are not designed for large heaps.

And CMS requires more configuration. 

Enable https for your nginx-hosted website with a CA-signed certificate

1. Exchange a Certificate Signing Request for certificate files

openssl req -new -newkey rsa:2048 -nodes -keyout private.key -out my.csr

Then submit my.csr file to your CA. You will then get certificate files from it.  

* The private.key will be used for decryption during SSL/TLS session establishment between a server and a client.

2. Combine all the certificate files into a single certificate chain file

Nginx requires a single certificate file, while other servers may not.

     cat my_server.crt > cert_chain.crt
     vi cert_chain.crt   # to make sure there is a new line between “end certificate” and next “begin certificate"

3. Configure Nginx with the files

    server {
    	listen 80;
    	listen 443 ssl;
    	# force https-redirects
    	if ($scheme = http) {
        	return 301 https://$server_name$request_uri;
    	ssl_certificate    /path/to/your/cert_chain.crt ;
    	ssl_certificate_key /path/to/your/private.key;


Why I am not a fan of Hibernate

  1. Rich Domain Model + Lazy-loading cause problems
    1. Hiberntate encourages rich domain model over table model, that is,  A.b instead of A.bId
    2. You must enable lazy-loading, otherwise there will be performance issues
    3. If you are not in a hibernate session, A.b will be invalid ("Partial Materialization" problem)
    4. To make user you are in a hibernate session, you will use OpenSessionInView pattern
    5. But OpenSessionInView is an ANTI-PATTERN.  Your code will not work in non-web applications or in Unit tests . Yes, there are workarounds, but why bother with Hibernate? 
    6. With table model, all these problems go away, albeit the price of writing SQL manually.
  2. Hibernate has a high learning curve, but your teammate just finished the first 3 chapters
    1. They may not have solid understanding of object states (transient, persistent, detached), which requires great care. The result is you see hibernate exceptions from time to time. 
    2. They don’t know about Partial Materialization problem mentioned above 
    3. Believe me, it happens. You may have junior members in your team, or some mates who are just too confident to take Hibernate as a heavy tool.
    4. With table model, all these problems go away. You will have a more robust system and will allow the team to recruit fresh graduates.  
  3. You lose control over low-level DB manipulation.  This is not a problem if your system is a low-scale one.