JDK 1.5 and modern patterns Peter Antman, CTO, 2007 Mogul
Whats on in the Java space? <ul><li>A refresher on JDK 1.5 </li><ul><li>Although old – not yet fully utilized
The base to using J2EE effectively
New Language Feature, new libraries, new methods, new runtime </li></ul></ul><ul><li>Some important new patterns </li><ul>...
Interceptors
Dependency Injection/IoC
AOP </li></ul></ul>
New features in JDK 1.5 <ul><li>Generics
New for loop
Autoboxing
Varargs
Enums
Static import
Annotations
New concurrency libraries
New stuff in java.lang.System, java.util.*
New management API and tools (JMX)
Better runtime (gc)
And more... </li></ul>
Generics – stronger typing <ul><li>Generics: a new language feature that makes Java more strongly typed
Makes it possible to write classes that handles any type logically, but bind it to a specific type when programming </li><...
A type parameter
Generics is parameterized classes (and methods)
Much like you may create new class instances with different values at runtime  </li><ul><li>ToBe notToBe = new ToBe(false)...
Generics and Collections <ul><li>Most widely used with Collections
No more typecasts
Only use arrays for performance critical work
Cleaner code for simple cases </li></ul>
Generics –  compile time check <ul><li>Old runtime checked code </li></ul>List strings = new ArrayList(); strings.add(new ...
Generics - map <ul><li>Iterating a Map of Maps – non generic </li></ul>Iterator it = topMap.entrySet().iterator(); while(i...
Generics – erasure <ul><li>Generics works by erasure
The generic type informations is lost in byte code
Source code/Byte code roundtripping not possible </li></ul>List<String> strings = new ArrayList<String>(); strings.add(&qu...
Generics – defining a class <ul><li>Creating a generic interface </li></ul>interface Factory<P> { P create(); } <ul><li>Cr...
Generic methods <ul><li>Possible to make methods generic
Done by prepending a type parameter
Lets redo javax.rmi.PortableRemoteObject </li></ul>public class PortableRemoteObject { static  <T>  T narrow(Object o, Cla...
Generics – inheritance <ul><li>Inheritance is a little bit surprising
Parameterizing a class with “compatible” types does not make the classes type compatible </li></ul>List<Integer> does  NOT...
Generics – inheritance example <ul><li>List<Number> ln = new List<Number>();
Can put both Integer and Double
ln.add(new Double(3.14));
List<Integer> li = new List<Integer>();
May only take Integer and subclasses, not Double
ln = new List<Integer>(); //  Compile error
Not OK, Integer can not risk being a Double </li></ul>
Generics – get principle <ul><li>Inheritance of generics classes is done with the extends and super wildcards
To be able to read from an inheritable generic class one must use the extends wildcard
<? extends T>  says that we can use any instance of the generic class that has been instantiated with the typ T or any sub...
Generics – put principle <ul><li>To be able to put stuff into a “inherited” generic type one has to use the super  wildcard
<? super T>  say that any type that is a parent to T used to parameterized a generic class will make that class a subtype ...
Look at  List<? super Number> . What is List<Object>?
Since Object is a supertype of Number List<Object> is a subtype of List<? super Number>!
When writing the limiting factor is the type to write (the thing you write into must be same type or a parent) </li></ul>s...
Generic – more complicated stuff <ul><li>Wildcard capture
Wildcard not allowed at top level during instance creation
Bounded type variables
Multiple bounds
Unbounded generics
Arrays and generics
Exceptions </li></ul>
New rule when overriding <ul><li>Old rule: a subclass can only override a method if it has the exact same signature
To override  public Object clone()  one had to do it like this </li></ul>class Person { public Object clone() {} } Person ...
Autoboxing <ul><li>Java typesystem </li><ul><li>primitives which are NOT objects: int, byte, boolean...
Objects inheriting from java.lang.Object
Primitives have no common parent </li></ul></ul>
Autoboxing - primitives Primitives does not work well with Collections or any other class that work on  Object void visit(...
Upcoming SlideShare
Loading in...5
×

Java 1.5 - whats new and modern patterns (2007)

1,626

Published on

Presentation of all the new stuff in Java 1.5 from 2007.

Published in: Technology, Education
1 Comment
3 Likes
Statistics
Notes
  • good one
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total Views
1,626
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
1
Likes
3
Embeds 0
No embeds

No notes for slide

Java 1.5 - whats new and modern patterns (2007)

  1. 1. JDK 1.5 and modern patterns Peter Antman, CTO, 2007 Mogul
  2. 2. Whats on in the Java space? <ul><li>A refresher on JDK 1.5 </li><ul><li>Although old – not yet fully utilized
  3. 3. The base to using J2EE effectively
  4. 4. New Language Feature, new libraries, new methods, new runtime </li></ul></ul><ul><li>Some important new patterns </li><ul><li>POJO
  5. 5. Interceptors
  6. 6. Dependency Injection/IoC
  7. 7. AOP </li></ul></ul>
  8. 8. New features in JDK 1.5 <ul><li>Generics
  9. 9. New for loop
  10. 10. Autoboxing
  11. 11. Varargs
  12. 12. Enums
  13. 13. Static import
  14. 14. Annotations
  15. 15. New concurrency libraries
  16. 16. New stuff in java.lang.System, java.util.*
  17. 17. New management API and tools (JMX)
  18. 18. Better runtime (gc)
  19. 19. And more... </li></ul>
  20. 20. Generics – stronger typing <ul><li>Generics: a new language feature that makes Java more strongly typed
  21. 21. Makes it possible to write classes that handles any type logically, but bind it to a specific type when programming </li></ul>public interface List<E> extends Collection <E> {} <ul><li><E> - whats that?
  22. 22. A type parameter
  23. 23. Generics is parameterized classes (and methods)
  24. 24. Much like you may create new class instances with different values at runtime </li><ul><li>ToBe notToBe = new ToBe(false); </li></ul><li>You can create a specialized typed instance programmatically </li><ul><li>List<String> myStrings = new List<String>(); </li></ul></ul>
  25. 25. Generics and Collections <ul><li>Most widely used with Collections
  26. 26. No more typecasts
  27. 27. Only use arrays for performance critical work
  28. 28. Cleaner code for simple cases </li></ul>
  29. 29. Generics – compile time check <ul><li>Old runtime checked code </li></ul>List strings = new ArrayList(); strings.add(new Integer(1));// Ok String s = (String)strings.get(0);// Runtime error <ul><li>New safe code </li></ul>List<String> strings = new ArrayList<String>(); strings.add(new Integer(1));// Compile error String s = strings.get(0);// No typecast
  30. 30. Generics - map <ul><li>Iterating a Map of Maps – non generic </li></ul>Iterator it = topMap.entrySet().iterator(); while(it.hasNext()) { Map.Entry e = (Map.Entry) it.next(); Iterator itSub = ( (Map) e.getValue()).entrySet().iterator(); while(itSub.hasNext()) { Map.Entry eSub = (Map.Entry) itSub.next(); String k = (String) eSub.getKey(); } } <ul><li>Iterating a Map of Maps – generic </li></ul>Iterator <Map.Entry<String, Map<String, String>>> it = topMap.entrySet().iterator(); while(it.hasNext()) { Map.Entry <String, Map<String, String>> e = it.next(); Iterator <<Entry.Set<String, String>> itSub = e.getValue().entrySet().iterator(); while(itSub.hasNext()) { Map.Entry <String, String> eSub = itSub.next(); String k = eSub.getKey(); } }
  31. 31. Generics – erasure <ul><li>Generics works by erasure
  32. 32. The generic type informations is lost in byte code
  33. 33. Source code/Byte code roundtripping not possible </li></ul>List<String> strings = new ArrayList<String>(); strings.add(&quot;hello&quot;); String h = strings.get(0); <ul><li>Becomes </li></ul>ArrayList arraylist = new ArrayList(); arraylist.add(&quot;hello&quot;); String s = (String)arraylist.get(0);
  34. 34. Generics – defining a class <ul><li>Creating a generic interface </li></ul>interface Factory<P> { P create(); } <ul><li>Creating a generic class </li></ul>static class FactoryImpl<T> implements Factory<T> { FactoryImpl(Class<T> c) {...}; public T create() {...} } Factory<My> f1 = new FactoryImpl<My>(My.class); My m1 = f.create();
  35. 35. Generic methods <ul><li>Possible to make methods generic
  36. 36. Done by prepending a type parameter
  37. 37. Lets redo javax.rmi.PortableRemoteObject </li></ul>public class PortableRemoteObject { static <T> T narrow(Object o, Class<T> t) {...} } <ul><li>The type is inferred during call </li></ul>My m2 = narrow(new My(), My.class); <ul><li>When inferred type is not clear one may have to help, calling </li></ul>static <T> List<T> trouble(T t1, T t2) <ul><li>like this: </li></ul>List<Object> lo1 = GenericsTest. <Object> trouble(new Integer(1), &quot;hello&quot;); //Must be a “.” before!
  38. 38. Generics – inheritance <ul><li>Inheritance is a little bit surprising
  39. 39. Parameterizing a class with “compatible” types does not make the classes type compatible </li></ul>List<Integer> does NOT inherit List<Number> <ul><li>runtime typing system not the same as compile time </li></ul>List<Number> ln = new ArrayList<Number>(); List<Integer> li = new ArrayList<Integer>(); ln.getClass().isInstance(li);// TRUE! <ul><li>instanceof does not work with generics because of erasure </li></ul>li instanceof List<Number> is not valid
  40. 40. Generics – inheritance example <ul><li>List<Number> ln = new List<Number>();
  41. 41. Can put both Integer and Double
  42. 42. ln.add(new Double(3.14));
  43. 43. List<Integer> li = new List<Integer>();
  44. 44. May only take Integer and subclasses, not Double
  45. 45. ln = new List<Integer>(); // Compile error
  46. 46. Not OK, Integer can not risk being a Double </li></ul>
  47. 47. Generics – get principle <ul><li>Inheritance of generics classes is done with the extends and super wildcards
  48. 48. To be able to read from an inheritable generic class one must use the extends wildcard
  49. 49. <? extends T> says that we can use any instance of the generic class that has been instantiated with the typ T or any subtypes of T </li></ul>class Reader<S> { S read(Reader<? extends S> r) { return r.read(); } <ul><li>Without this Reader<My> would only be able to read other Reader<My> instances. With extends it may also read for example Reader<MySub> </li></ul>
  50. 50. Generics – put principle <ul><li>To be able to put stuff into a “inherited” generic type one has to use the super wildcard
  51. 51. <? super T> say that any type that is a parent to T used to parameterized a generic class will make that class a subtype of the declaring class
  52. 52. Look at List<? super Number> . What is List<Object>?
  53. 53. Since Object is a supertype of Number List<Object> is a subtype of List<? super Number>!
  54. 54. When writing the limiting factor is the type to write (the thing you write into must be same type or a parent) </li></ul>static class Writer<D> { void write(Writer<? super D> w) { w.write(); } <ul><li>Without this Writer<My2> would not be able to write to a Writer<My> </li></ul>
  55. 55. Generic – more complicated stuff <ul><li>Wildcard capture
  56. 56. Wildcard not allowed at top level during instance creation
  57. 57. Bounded type variables
  58. 58. Multiple bounds
  59. 59. Unbounded generics
  60. 60. Arrays and generics
  61. 61. Exceptions </li></ul>
  62. 62. New rule when overriding <ul><li>Old rule: a subclass can only override a method if it has the exact same signature
  63. 63. To override public Object clone() one had to do it like this </li></ul>class Person { public Object clone() {} } Person pc = (Person) person.clone(); <ul><li>New rule: the return type may be a subtype of the type returned by the overridden method. Its now legal to do this: </li></ul>class Person { public Person clone() {} } Person pc = person.clone();
  64. 64. Autoboxing <ul><li>Java typesystem </li><ul><li>primitives which are NOT objects: int, byte, boolean...
  65. 65. Objects inheriting from java.lang.Object
  66. 66. Primitives have no common parent </li></ul></ul>
  67. 67. Autoboxing - primitives Primitives does not work well with Collections or any other class that work on Object void visit(String page) { int val = 0; if (stats.containsKey(page)) { val = ((Integer) stats.get(page)).intValue(); } Integer newVal = new Integer(++val) ; stats. put (page, newVal); }
  68. 68. Autoboxing - example <ul><li>Autoboxing means that the compiler automatically wraps and unwraps primitives to and from their Object counterparts </li></ul>Integer[] is = new Integer[]{1,2,3}; <ul><li>An example </li></ul>static protected void visitAuto(String page) { if (!map.containsKey(page)) { map.put(page, 0); } map.put(page, map.get(page) + 1); <ul><li>Be aware of null pointer </li></ul>Map<Integer> ints = new HashMap<Integer>(); int i = ints.get(“no”);// NullPointerException
  69. 69. Autoboxing – problems <ul><li>Some compile check go unnoticed. Whats wrong with this class? </li></ul>public class Conference { private Collection delegates = new ArrayList(); public void add(String... names) { Collections.addAll(delegates, names); } public void removeFirst() { delegates.remove(0); } public String toString() { return &quot;Conference &quot; + delegates; } public static void main(String[] args) { Conference sun_tech_days = new Conference(); sun_tech_days.add(&quot;Herman&quot;, &quot;Bobby&quot;, &quot;Robert&quot;); sun_tech_days.removeFirst(); System.out.println(sun_tech_days); } }
  70. 70. Varags – variable length arguments <ul><li>Variable length arguments added </li></ul>Object method(Object... o); method(“h”, “e”, “l”, “l”, “o”); <ul><li>Must be last in argument list </li></ul>Object method(String n, Object... o); <ul><li>Is actually an array </li></ul>Object method(new Object[] {“H”, “E”}); <ul><li>Empty invoke same as null </li></ul>Object method(); <ul><li>Works with generics </li></ul>static <T> T method(T... t); <ul><li>Be aware of inferrence problems </li></ul>Object o = VaragsTest.<Object>method();
  71. 71. Nice new method <ul><li>Arrays.asList: public static <T> List <T> asList(T... a)
  72. 72. Before with had to initialize lists like this: </li></ul>List l = new ArrayList(); l.add(new Integer(1)); <ul><li>Now we do it like this </li></ul>List<Integer> ints = Arrays.asList(1, 2, 3); List<Double> ds = Arrays.asList(3.2, 4.5); List<String> ss = Arrays.asList(“by”, by”);
  73. 73. Enums <ul><li>Enumerated types introduced to be used for constants
  74. 74. Constants mostly used to look like this: </li></ul>public static final int SEASON_WINTER = 0; <ul><li>Not type safe
  75. 75. Requires recompilation of all using classes when changed
  76. 76. Not nice to print
  77. 77. Lot of work to implements ones own enums </li></ul>
  78. 78. Enum - features <ul><li>Easy to declare </li></ul>enum Rgb {RED, GREEN, BLUE}; <ul><li>Nice to print </li></ul>System.out.println(Rgb.RED); -> RED <ul><li>May be used in switch statements </li></ul>Rgb r = Rgb.RED; switch(r) { case RED: System.out.println(&quot;OK&quot;); break; default: System.out.println(&quot;NO&quot;); } <ul><li>Use EnumSet and EnumMap when working with collections </li></ul>
  79. 79. foreach lop <ul><li>A new foreach loop called for
  80. 80. Iterates over Iteratable, enums and arrays
  81. 81. Avoids local variables </li></ul>List<Integer> ints = Arrays.asList(1,2,3); for (int i: ints) System.out.println(&quot;I: &quot; + i); int[] ints2 = new int[]{1,2,3}; for (int i: ints2) System.out.println(&quot;I: &quot; + i); for(Rgb c: Rgb.values()) System.out.println(&quot;C: &quot; +c);
  82. 82. Static import <ul><li>Possible to import static variables from a class
  83. 83. Avoids antipattern that inherits static variable through interface
  84. 84. Use with caution </li></ul>Math.PI * 2 import static java.lang.Math.PI; PI * 2; Possible, but seldom recommended, to do wildcard import
  85. 85. Annotations <ul><li>Annotations added
  86. 86. Metadata that can be attached to a package, class, interface, field, method, parameter, constructor or local variable
  87. 87. No inherent logic, only a placeholder for data
  88. 88. May be available in source code, byte code and at runtime
  89. 89. Is used by other tools and runtime components: these may change the behavior of a program
  90. 90. Typical usage: </li><ul><li>generate code
  91. 91. generate documentation
  92. 92. generate deployment descriptor
  93. 93. read deployment info from class/at runtime,
  94. 94. add aspects
  95. 95. inject objects </li></ul></ul>
  96. 96. Annotions - declaration <ul><li>Annotations declarations consists of its name and one or more attributes ( not Bean style)
  97. 97. Attributes may have default values
  98. 98. The value() attribute is special
  99. 99. Attributes may only be primitives, String, Class, enums, annotations and arrays of these
  100. 100. Annotations always have parent java.lang.annotation.Annotation </li></ul>@interface MyAnnotation { String value(); String myDefault() default &quot;[Default Value]&quot;; }
  101. 101. Annotating annotation <ul><li>Annotations may be annotated
  102. 102. Target tells where an annotation is valid
  103. 103. Retention tells where an annotation is available, i.e source, binary, runtime </li></ul>import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.annotation.ElementType; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface MyAnnotation {
  104. 104. Using annotations <ul><li>Annotation is a modifier, by convention placed before other modifier
  105. 105. Are compile time dependent on provider
  106. 106. Are not runtime dependent when not introspected
  107. 107. May be used together with package, class, interface, field, method, parameter, constructor and local variables </li></ul>@MyAnnotation(“value”) public class MyClass { @MyAnnotation(value = “value”) int var = ...; @MyAnnotation(“value”, myDefault=”noDefault”) public void method() @MyAnnotation(“value”) public MyClass(@MyAnnotation(“param”) String arg) {
  108. 108. Introspected annotations <ul><li>Annotations may be introspected at runtime
  109. 109. If classes are not available they silently “disappear” </li></ul>@HiddenAnnotation(&quot;Ha&quot;) public static void main(final String[] args) throws Exception{ Method m = AnnotationTest.class. getMethod(&quot;main&quot;, String[].class); Annotation[] as = m.getDeclaredAnnotations() ; for (Annotation a: as) { if (a instanceof HiddenAnnotation){ System.out.println(&quot;Value=&quot; + ((HiddenAnnotation)a).value() ); } } }
  110. 110. New concurrency library <ul><li>Doug Leas famous concurrency library has been incorporated into the sdk
  111. 111. Contains interfaces and core classes which makes it easier and safer to work with concurrency
  112. 112. Never write concurrent code without checking this library
  113. 113. Contains libraries to work with </li><ul><li>Effective concurrent collections
  114. 114. Pools of Threads and other things
  115. 115. Concurrent collaboration
  116. 116. Asynchronous invocations
  117. 117. Advanced locking
  118. 118. Atomic operations on objects (not just ints) </li></ul></ul>
  119. 119. Concurrent collection <ul><li>First cut of Java “collections” was synchronized: eg Hashtable </li><ul><li>Safe but ineffective </li></ul><li>Second generation of Java collections was unsynchronized </li><ul><li>Effective, but does not work with concurrent code </li></ul><li>Either you have to guard your access to collections by writing your own synchronization </li><ul><li>easy to get wrong </li></ul><li>Or translate them to completely synchronized: </li></ul>Map safe = Collections.synchronizedMap(new HashMap()); <ul><li>Often problems with Iterators (not part of synchronization)
  120. 120. Failfast iterators: clone state before iterating </li></ul>
  121. 121. New concurrent collections <ul><li>Not all or nothing
  122. 122. Uses new techniques and algorithms to handle different usage patterns effectively
  123. 123. Different strategies to make iterations safer </li><ul><li>snapshot iterators
  124. 124. weakly consistent iterators </li></ul></ul>
  125. 125. ConcurrentHashMap <ul><li>Lock striping
  126. 126. Optimized for reads: does not block reads even when its updated
  127. 127. Does often not block on updates either
  128. 128. Weakly consistent iterators
  129. 129. Atomic check and take action methods </li></ul>V putIfAbsent(K key, V value); boolean remove(Object key, Object value); V replace(K key, V value); boolean replace(K key, V oldValue, V newValue);
  130. 130. ConcurrentHashMap - example <ul><li>Old style </li></ul>synchronzied(map) { if(map.containsKey(key) map.put(key, value); } <ul><li>New style </li></ul>concMap.putIfAbsent(key, value);
  131. 131. CopyOnWrite collections <ul><li>CopyOnWriteArrayList and CopyOnWriteArraySet
  132. 132. Safe for concurrent operations but no synchronized reads
  133. 133. Use when mostly used with concurrent reads
  134. 134. Typical usecase: listeners
  135. 135. Costly to write to
  136. 136. Snapshot iterators, not possible to modify collection through them </li></ul>
  137. 137. Queue <ul><li>Queue – holds element for processing in a queue specific order (priority, fifo, mm)
  138. 138. interface Queue </li><ul><li>PriorityQueue
  139. 139. ConcurrentLinkedQueue </li><ul><li>Weakly consistent iterator, wait-free, thread-safe </li></ul></ul><li>interface BlockingQueue </li><ul><li>Producer/Consumer patterns
  140. 140. LinkedBlockingQueue – unbound by default
  141. 141. ArrayBlockingQueue – bounded queue
  142. 142. PriorityBlockingQueue – a blocking thread safe priority queue
  143. 143. DeleayQueue – entered items only available after a delay
  144. 144. SynchronousQueue – empty queue, rendevouz, two colaborating threads </li></ul></ul>
  145. 145. BlockingQueue - example final BlockingQueue<String> bq = new LinkedBlockingQueue<String>(); Thread c = new Thread(new Runnable(){ public void run() { while(true) { try { String s = bq.take(); System.out.println(&quot;Took &quot; + s); } catch(InterruptedException e){} } } }); Thread p = new Thread(new Runnable(){ int counter = 0; public void run() { while(true) { try { bq.put(&quot;b&quot; + counter++); } catch(InterruptedException e){} } } }); c.start(); p.start();
  146. 146. Executor <ul><li>Executes Runnable task according to implementation
  147. 147. Use instead of manually creating Threads
  148. 148. Not necessarily asynchronous
  149. 149. One method: void Excecute(Runnable); </li></ul>Executor exe = Executors.newFixedThreadPool(10); exe.execute(task);
  150. 150. ExecutorService <ul><li>Extension to Executor
  151. 151. Provides management methods
  152. 152. May track submitted task and get result back
  153. 153. Uses Future and Callable </li></ul>Callable<String> worker = new Callable<String>() { int c = 0; public String call() { try {Thread.sleep(2000L);}catch(Exception ignore){} return &quot;jobb no &quot; + c++; } }; ExecutorService exe = Executors.newSingleThreadExecutor(); Future<String> result = exe.submit(worker); while(!result.isDone()) { // Do something other } String s = result.get();
  154. 154. Atomic objects <ul><li>java.util.concurrent.atomic
  155. 155. volatile but with conditional atomicity
  156. 156. Finer granularity of locking (hardware based)
  157. 157. Non blocking
  158. 158. Built on optimistic assumptions: do it, check and redo
  159. 159. Non blocking counting </li></ul>AtomicLong at = new AtomicLong(); // one thread, no synchronzied long current = at.get(); // another thread increment, no sync at.incrementAndGet();
  160. 160. Locking <ul><li>java.util.concurrent.locks
  161. 161. More flexible locks and mutex than builtin
  162. 162. Great to handle many reads, few writes </li></ul>ReadWriteLock locks = new ReentrantReadWriteLock(); public void read() { Lock readLock = locks.readLock(); readLock.lock(); try { // Do read, multiple threads allowed } finally { readLock.unlock(); } } public void write() { Lock writeLock = locks.writeLock(); writeLock.lock(); try { // Do write, only one thread } finally { writeLock.unlock(); } }
  163. 163. Other new stuff in java.util <ul><li>UUID – universally unique identifier </li><ul><li>UUID uuid = UUID.randomUUID(); </li></ul><li>Arrays.hashCode() and Arrays.deepHashCode()
  164. 164. Arrays.toString([] ) and Arrays.deepToString(Object[] )
  165. 165. Collections.reverseOrder(Comparator<T>)
  166. 166. Collections.addAll(Collection<T>, T... ) </li></ul>
  167. 167. Other new stuff <ul><li>java.lang.ProcessBuilder - to start and manage external processes
  168. 168. java.lang.StringBuilder – use instead of StringBuffer when no synchronization is needed
  169. 169. long n = System.nanoTime();
  170. 170. System.getEnv()
  171. 171. Thread.getStackTrace()
  172. 172. Thread.State s = t.getState ()
  173. 173. ThreadLocal.remove()
  174. 174. java.lang.instrument </li></ul>
  175. 175. JMX <ul><li>javax.management (1.2) and remote (1.0) is part of the API
  176. 176. The JVM is managable with jmx both locally and remote
  177. 177. When managability is turned on one may use the builtin MbeanServer
  178. 178. Managability is turned on with system properties
  179. 179. Turn on local management: </li></ul>java -Dcom.sun.management.jmxremote MyServe r <ul><li>Turn on remote management, no security </li></ul>java -Dcom.sun.management.jmxremote.port=4711 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false <ul><li>Turn on remote management, password </li></ul>java -Dcom.sun.management.jmxremote.port=4711 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.password.file=FILE
  180. 180. jconsole
  181. 181. Getting the mbean server and managing an object   public static interface My { public String getMyName(); } public static class MyImpl implements My { String n; MyImpl(String s) { n = s; } public String getMyName(){return n;} } ArrayList servers = MBeanServerFactory.findMBeanServer(null); if (servers.size() > 0) { server = (MBeanServer)servers.get(0); StandardMBean b = new StandardMBean(new MyImpl(&quot;Peter&quot;), My.class); server.registerMBean(b, new ObjectName(&quot;test:name=Peter&quot;)); }
  182. 182. Manage the bean with jconsole
  183. 183. Better garbage collection algorithms <ul><li>Better default gc
  184. 184. More detailed configuration </li></ul>
  185. 185. Important “new” patterns <ul><li>Reaction against J2EE
  186. 186. Driven by two reactions </li><ul><li>Small open source project
  187. 187. Head to head with .Net regarding web development </li></ul><li>Lightweight
  188. 188. No dependencies on infrastructure
  189. 189. No infrastructure in code
  190. 190. Testability </li></ul>
  191. 191. POJO <ul><li>POJO – Plain Old Java Object
  192. 192. Martin Fowler 2000
  193. 193. Concentrate on logic
  194. 194. No plumbing code
  195. 195. No framework dependencies
  196. 196. No special runtime requirements
  197. 197. Makes it easier to test </li></ul>
  198. 198. IoC <ul><li>IoC = Inversion of Control
  199. 199. “Old” style – classes handles their dependencies for them self </li><ul><li>creating a data base connection
  200. 200. looking up a properties file
  201. 201. Really hard when testing
  202. 202. DataSource ds = new DataSource(); </li></ul><li>EJB and Avalon first type 1 IoC containers </li><ul><li>Dependencies are handled by container
  203. 203. Classes implements frameworks hooks and marker interfaces
  204. 204. Container make external resources available through these hooks
  205. 205. EJB: setSessionContext(SessionContext ctx)
  206. 206. Also hard to test: requires deployment in runtime environment </li></ul></ul>public void service(ServiceManager sm) { ds = (DataSource)sm.lookup(“myDataSource”); }
  207. 207. IoC type 2 <ul><li>IoC type 2: setter injection
  208. 208. Must known container: Spring
  209. 209. A class declares setter for any external dependencies
  210. 210. These dependencies are handled by container
  211. 211. After object is created the dependencies are injected by invoking the correct set-methods
  212. 212. Much easier to test
  213. 213. Hard to know when an object is really “ready”, one often needs one or more life cycle callbacks! </li></ul>public void setDataSource(DataSource ds)
  214. 214. IoC – type 3 <ul><li>IoC type 3: constructor injection
  215. 215. Same as type 2, but objects always get their full dependencies at creation
  216. 216. No life cycle methods needed
  217. 217. Many dependencies lead to cluttered constructors
  218. 218. Optional dependencies harder to handle
  219. 219. Property type configuration not as straight forward </li></ul>
  220. 220. Dependency injection <ul><li>IoC type 2 and 3 now has a common name
  221. 221. Dependency Injection
  222. 222. Martin Fowler 2004
  223. 223. From JDK 1.5 dependency injection primarily seems to be done with annotations
  224. 224. Several new types of injections introduced </li><ul><li>attribute injection
  225. 225. thread/context injections </li></ul></ul>
  226. 226. Dependency Injection - annotation @DataSource DataSource ds; MyClass(@DataSource ds) { @DataSource public void setDataSource(DataSource ds)
  227. 227. Interceptors <ul><li>Interceptors have become popular
  228. 228. Based on the decorator pattern
  229. 229. Intercept call to a POJO and add framework logic
  230. 230. JBoss revolutionized the interceptor pattern in its EJB container
  231. 231. The servlet spec popularized it through the introduction of servlet filter
  232. 232. Plumbing logic is moved out from the POJO
  233. 233. Foundation laid with introduction of Proxy in JDK 1.3
  234. 234. Only possible on method level by default </li></ul>
  235. 235. Simple logging interceptor Object target; LoggingInterceptor(Object target) { this.target = target; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { log(&quot;TRACE&quot;, &quot;Calling &quot; + method.getName()); return method.invoke(target, args); } My m = (My)Proxy.newProxyInstance(Thread.currentThread(). getContextClassLoader(), new Class[]{My.class}, new LoggingInterceptor(new MyImpl())); String s = m.hello();
  236. 236. ThreadLocalInjector <ul><li>Lets finish this up with a thread local injector
  237. 237. We want to be able to have a class looking like this: </li></ul>interface My { String hello(); } class MyImpl implements My { public String msg; @InjectThreadLocal(name=&quot;msg&quot;, type=String.class) public String hello(){ return msg;} } <ul><li>The logic is that a calling thread shall inject a thread local variable into the msg attribute </li></ul>
  238. 238. InjectThreadLocal annotation <ul><li>We need an annotation </li></ul>@Retention(RetentionPolicy.RUNTIME) @interface InjectThreadLocal { String name(); Class type(); }
  239. 239. ThreadLocalInterceptor <ul><li>And an interceptor
  240. 240. First part </li></ul>static class ThreadLocalInterceptor<T> implements InvocationHandler { Object target; Class targetClass; ThreadLocal<T> local; ThreadLocalInterceptor(Object target, ThreadLocal<T> local) { this.target = target; this.local = local; targetClass = target.getClass(); }
  241. 241. ThreadLocalInterceptor – part 2 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Need to use real target class! Method targetMethod = targetClass. getDeclaredMethod(method.getName(), method.getParameterTypes()); InjectThreadLocal a = targetMethod. getAnnotation(InjectThreadLocal.class); if (a != null) { Field f = targetClass.getField(a.name()); if (f != null) { Object tl = local.get(); if (f.getType().isAssignableFrom(tl.getClass())) { f.set(target, tl); } } } return method.invoke(target, args); }
  242. 242. Inject in a stateless instance <ul><li>We use a “stateless” instance </li></ul>Runnable r = new Runnable() { public void run() { while(true) { long id = Thread.currentThread().getId(); local.set(&quot;&quot; + id); String s = m.hello(); System.out.println(&quot;Thread &quot; + id + &quot; said hello: &quot; +s); } } }; Thread t1 = new Thread(r); t1.start(); Thread t2 = new Thread(r); t2.start();
  243. 243. Injection result <ul><li>Output when run </li></ul>Thread 9 said hello: 9 Thread 9 said hello: 9 Thread 10 said hello: 10 Thread 9 said hello: 9 Thread 9 said hello: 9 Thread 10 said hello: 10 Thread 9 said hello: 9 Thread 9 said hello: 9 Thread 10 said hello: 10
  244. 244. AOP <ul><li>AOP – Aspect Oriented Programming
  245. 245. Interceptors taken to a new layer
  246. 246. Cross Cutting Concerns
  247. 247. Not just method inteceptions
  248. 248. join point – where to join in
  249. 249. point cuts – pointer to join points
  250. 250. advice – aspect to join in
  251. 251. Much more... </li></ul>
  252. 252. mogul .slut på presentation Kontakt: [email_address]

×