Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Monday, March 21, 2011

Java 的instance initializer

http://www.c2.com/cgi/wiki?DoubleBraceInitialization
http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.6

原來Java除了 static initializer 之外
還有 instance initializer

不過這方法很少用到
因為其實constructor 就可以了

不過在Anonymous inner class時
因為他們沒有 constructor
這時就可以用 這instance initializer 來達到同樣的功能了

Tuesday, August 10, 2010

illegal forware reference in java

case 1:  比較常見的
class Test {
  String s = "hello";

  class inner {
    inner () {
        String s = s;  // <- illegal forward reference
    }
  }
}


case 2:  比較特別的 即使sStr是static也會


class Test2 {
  static {
    System.out.println(sStr);  // <- illegal forward reference
  }

  private static String sStr = "hello World";
}

Wednesday, April 28, 2010

using JNI in pthread

有人問到為什麼不能在native pthread create出來的 thread "直接" 使用 JNI

在這explain 一下 background

大家知道Thread之間是會shared memory的 (不過stack當然還是自己的)
所以大家寫code 有時會用個global 變數  然後兩三個thread來對這global變數作read/write

不過大概在2000年吧?   ABI (Binary Interface)那時有作一些update 
http://www.sco.com/developers/gabi/2000-07-17/contents.html
主要就是多個TLS - Thread Local Storage
就是讓thread 有自己的global 變數 其他的thread並不會踩到別thread的memory

例如  原本的 int g_is_vm_started;
GCC的話 :  在前面加個 __thread  就變成 thread variable了
__thread int g_is_vm_started;
在這看你自己喜歡的compile怎麼改
http://en.wikipedia.org/wiki/Thread-local_storage

而JNI 也是有用到這東西
所以在call JNI時  VM會去拿TLS裡的pointer  裡面存著vm在這個thread裡的context
如果想看Dalvik的code的話
就是在vm/Jni.c裡的 JNI_ENTER() 這macro裡
( 不過Android上其實並沒有Runtime support TLS
用readelf dump library裡其實並沒有.tdata .tbss的section
上面講的TLS 其實是bionic 裡的pthread 自己作出來的
)


想在pthread create出來的thread裡使用JNI
可以先看這
http://java.sun.com/j2se/1.5.0/docs/guide/jni/spec/invocation.html

還有個在pthread裡的ClassLoader的問題
http://groups.google.com/group/android-ndk/browse_thread/thread/7982fdb5892f79fb

Monday, August 17, 2009

java的byte to int

今天下午在作一些byte operation時
有field是開頭用2byte來指定這個data的size

例如說 c000這是little endian的
所以實際是 00co

然後要拿這length來作事情時
b[0] | b[1] <<> char是unsigned了吧
不過很麻煩 用時還要把他轉int
最後發現可以用 b[0] & 0xff 這樣
主要是 0xff 他是一個int , 0x000000ff
所以b[0]也會被promoted為int 雖然int也是signed
但跟0x000000ff AND後sign bit 就不見了

不過也有看到比較雜的code
((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
這也能把byte轉成unsigned的
原理是一樣的
但似乎多作了很多事..........


真的要買hack's delight來看了