Java 1.5 - whats new and modern patterns (2007)

  • 1,516 views
Uploaded on

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

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

More in: Technology , Education
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
  • good one
    Are you sure you want to
    Your message goes here
No Downloads

Views

Total Views
1,516
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
0
Comments
1
Likes
3

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

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