четверг, 14 февраля 2013 г.

Safe publication

This is an example of unsafe publication:
public class MyClass{
public Holder holder = new Holder(42);
...
}
This publication is unsafe because there is not sufficient synchronization and reader threads may see stale value (null); But in case of static field it is safe:
public static Holder holder = new Holder(42);
Static initializers are executed by the JVM at class initialization time; because of internal synchronization in the JVM, this mechanism is guaranteed to safely publish any objects initialized in this way [JLS 12.4.2]. To fix the issue that is described in the beginning just add the volatile modifier to the instance field;
public class MyClass{
public volatile Holder holder = new Holder(42);
...
}

четверг, 7 февраля 2013 г.

How to get a full command line for process in Solaris

Using command like
 ps -aef
returns quite full information about processes running. But it cuts command line so you cannot see full command and arguments the process has been started with. To fix that in Solaris (SunOS) use this command:
 usr/ucb/ps -auxww
For example to view all java processes following command is useful:
 /usr/ucb/ps -auxww | grep java | grep -v grep

понедельник, 4 февраля 2013 г.

Joins

Join = inner join (пересечение). Left(right, full) join = outer join. Left join возьмет все записи из left и добавит к ним некоторые из правой

Static nested class access

class Test {
    private static class Test2 {
        private static String name = "Name";
    }
    
    public static void main(String[] args) {
        System.out.println(Test2.name);
    }
}
Можно. Даже без проблем можно обратиться к Test2.name, хоть он и private. А без static у класса Test2 ругня на name: The field name cannot be declared static; static fields can only be declared in static or top level types.

Constructor and child class

class A{
  A(int i){}
}
class B extends A{
  B(int i){}
}
Так нельзя. Если у предка отсутствует конструктор по умолчанию, то потомок должен вызвать явно другой конструктор.
class A{
 A(int i){}
}
class B extends A{
 B(int i){
  super(i);
 }
}
Можно

Nested and inner classes

Вложенные классы делятся на статические и нестатические (non-static). Собственно нестатические вложенные классы имеют и другое название - внутренние классы (inner). Внутренние классы в Java делятся на три вида: внутренние классы-члены (member inner classes); локальные классы (local classes); анонимные классы (anonymous classes). Локальный класс – в пределах метода или блока, не может быть public, private, protected, static.

Раннее и позднее связывание

public class LinkageTest{
    public static class Parent{
        public void test(){
            System.out.println("parent::test");
        }
    }
    public static class Child extends Parent{
        public void test(){
            System.out.println("child::test");
        }
    }
    public static class Tester{
        public void test(Parent obj){
            System.out.println("Testing parent...");
            obj.test();
        }
        public void test(Child obj){
            System.out.println("Testing child...");
            obj.test();
        }
    }
    public static void main(String[] args){
        Parent obj = new Child();
        Tester t = new Tester();
        t.test(obj);
    }
}
Результатом выполнения будет: Testing parent... child::test

воскресенье, 3 февраля 2013 г.

Exceptions and finally blocks

public class ExceptionLossTest{
    public static void main(String[] args){
        try {
            try {
                throw new Exception("a");
            } finally {
                if (true) {
                    throw new IOException("b");
                }
                System.err.println("c");
            }
        } catch (IOException ex) {
            System.err.println(ex.getMessage());
        } catch (Exception ex) {
            System.err.println("d");
            System.err.println(ex.getMessage());
        }
    }
}
Результатом его выполнения будет вывод в консоль b. И только. Return в finally тоже затирает другие ретурны