Tuesday, December 20, 2011

Are static fields initialized before constructor is called?

I've encountered this while debugging one very strange issue in third party library. Decompiled code made this case even more interesting and not so obvious.

How do you think, what is the output for following program?

public class AreStaticFieldsInitializedBeforeConstructorIsCalled {
public static void main(String[] args) {
new A();
}
}
class A {
static A a = new A();
static String staticField = "1";
static final String CONSTANT = "2";
public A() {
System.out.println(staticField);
System.out.println(CONSTANT);
}
}


Output is:

null
2
1
2

Constructor is called before "staticField" is initialized.

Wednesday, November 23, 2011

sudo without password

  Our team has encountered a problem with restarting tomcat server on remote Ubuntu machine.

  We have a trusted SSH connection between our machines and the remote one, so we don't have to use passwords when accessing remote machine. However, we had to use a password for restarting tomcat server with this command:

sudo service tomcat6 restart
view raw 3 hosted with ❤ by GitHub


  As we are using secure passwords, it was quite annoying to copy/paste this password all the time. Here is the solution that we figured out.

  Go to remote machine and run following command:

sudo visudo
view raw 1 hosted with ❤ by GitHub


  And add something similar to the end on file:

%tomcat6 ALL=(ALL) NOPASSWD: /usr/sbin/service tomcat6 restart
view raw 2 hosted with ❤ by GitHub


  Save changes (Ctrl+X) and logout/login

  Now all members of tomcat6 group should be able to restart the server without entering password.

  It's also nice, that you can provide not only the command that does not require password, but also arguments. In our case, it allowed to simplify tomcat restart while still requiring password for shutting down the server.