javaone 2013 san francisco asyn-concurrencyonee7

86
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 1

Upload: oracle-fusion-middleware

Post on 27-Jan-2015

114 views

Category:

Technology


3 download

DESCRIPTION

 

TRANSCRIPT

Page 1: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 1

Page 2: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

[ CON10982 ] Implementation of Async and Concurrent Applications in the Java EE Environment Yoshio Terada Java Evangelist http://yoshio3.com

Page 3: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 3 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 3

If  you  have  some  questions,could  you  give  me  a  message  on  Twitter  with  following  hash  tag  ?

[#CON10982]My  Twitter  ID  :  @yoshioterada

Page 4: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 4 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 4

The following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle.

Page 5: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 5

It is very easy to implement concurrent application on EE 7 environment. Customizable flexibly

Page 6: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 6

Structure  of  My  Sesiosn

Review  of  Async/Concurrencyon  Java  SE  &  Java  EE6

Concurrency  Utilities  onJava  EE  7  

15-‐‑‒20  MinWith  Demo

40  MinWith  Demo

Page 7: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 7

History  of  Async  Application  in  Java

Java  SEEnvironment

Page 8: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 8

1996 1997

JDK1.0ThreadRunnable

20042006

JDK1.1

J2SE1.2

J2SE  1.3

J2SE  1.4

Java  SE  5JSR-‐‑‒166Concurrency  Utilities

Java  SE  6JSR-‐‑‒166x

Hisotry  of  Java  Thread

1998 2000 2002

Page 9: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 9

2011

・・・・・・・・

・・

・・・・・・・・

Java  SE  7JSR-‐‑‒166yFork/Join

Java  SE  8Lambda  Expression  &  JSR-‐‑‒166eConcurrency  Utilities

2014

History  of  Java  SE  Thread

Page 10: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 10 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 10

class MyWebServer{! public static void main(String argv[]){! ServerSocket socket = new ServerSocket(80);! while(true){! final Socket conn = socket.accept();! Runnable r = new Runnable(){! publiv void run(){ ! addConnQueue(conn);//Server opeartion   }};! new Thread(r).start();! }!} }!

Ex  :  Impl  of  MultiThread  Web  Server

Create  new  

Thread  for  

request

No  more  Recommend  This  way

Page 11: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 11

new  Thread(r).start();

Thread-‐‑‒1

Thread-‐‑‒2

Thread-‐‑‒3

Thread-‐‑‒n

Generated  Thread  Indefinitely・・・

Page 12: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 12

Thread-‐‑‒1

Thread-‐‑‒2

Thread-‐‑‒3

Thread-‐‑‒n

Ex  :  Stack  area  is  also  allocated

スタック

Thread-‐‑‒1  Stack

Thread-‐‑‒2  Stack

Thread-‐‑‒3  Stack

Thread-‐‑‒n  Stack

… …

-‐‑‒Xss

Page 13: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 13

Load  of  Java  VM  and  OS

Memory  Consumption  for  each  thread

UpperLimit  of  the  number  of  thread  creation

Overhead  of  the  context  switch

Disadvantage  of  unlimited  thread

Page 14: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 14

Page 15: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 15

Java  Concurrency  Utilities

•  Easy  API  to  implement  concurrency  application

•  Provide  simple  and  easy  API•  Scalability,  Performance,  Maintainability,  Thread  safe,  easy  to  understand

Page 16: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 16

JSR-‐‑‒166  Overview

•  Async  task  operation•  Concurrency  Collection•  lock,  synchronizer•  Atomic  operation

Page 17: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 17

Useful  classes

•  Executors,  Thread  Pool,  Futures  •  Collection:  Queues,  Blocking  Queues,  Concurrent  

HashMap•  Lock,  synchronization:  Semaphores,  Barriers,  Atomic  

variable•  Others  …

Page 18: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 18 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 18

public interface Executor{ ! void execute(Runnable command); !} !

Executor  InterfaceAsync  invocation

Page 19: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 19 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 19

public interface ExecutorService extends Executor{ ! void shutdown(); ! List<Runnable> shutdownNow(); ! boolean isShutdown(); ! boolean isTerminated(); ! boolean awaitTermination(long timeout,!    TimeUnit unit); ! <T> Future<T> submit(Callable<T> task) ! // and more …!} !

ExecutorService  InterfaceLifecycle  management,  get  return  value

Page 20: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 20 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 20

static int CPU_NUM =! Runtime.getRuntime().availableProcessors();! ExecutorService pool = ! Executors.newFixedThreadPool(CPU_NUM);! public static void main(String argv[]){! ServerSocket socket = new ServerSocket(80);! while(true){! final Socket conn = socket.accept();! Runnable r = new Runnable(){! public void run(){;//do something      } };! pool.execute(r);! }}!

WebServer    implemented  by  Executor

Page 21: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 21

newFixedThreadPool

ExecutorService execution using fixed Thread Pool

LinkedBlockingQueue  (FIFO)

ThreadFactory…T1 T2 T3 T4 Tn

ExecutorService pool =!   Executors.newFixedThreadPool(CPU_NUM);

pool.execute(r);

•  Reuse  the  created  Thread

•  Number  of  max  Thread

•  Queing  of  incoming  request

Page 22: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 22

Execute  Thread  more  Efficiently

Possible  to  manage  the  lifecycle  of  Thread

Benefit  of  Concurrency  Utilities

Page 23: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 23

History  of  Async  on  Java  EE

JMS(MDB)Async  ServletAsync  EJB

Page 24: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 24

1998

2009

JPE

J2EE  1.4

Java  EE  6Async  ServletAsync  EJB

History  of  Async  on  Java  EE

19992001

2003

Java  EE  5

2006

J2EE  1.2JMS

J2EE  1.3MDB

Page 25: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 25

JMS  &  MDBMore  Easy  :  Java  EE  7

Page 26: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 26

Message  Provider

JNDI  Naming  Space

ConnFactory

jms/MyConFactory

App  Server  Administrator

Destination

jms/MyQueue

Queue  Name

Delegate  the  operation  to  External  Message  Provider

Page 27: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 27

JNDI  Name  Space

ConnFactory Destination

JMS  Client

Resource  Injection  jms/MyFactory  jms/MyQueue

JMS  Client  connect  to  Message  Provider  via  JNDI  lookup

Message  Provider

Queue  NameDeveloper

Developer  refer  to  the  JNDI

Page 28: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 28 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 28

@Stateless!public class MailAddressRegisterEJB {! @Resource(mappedName = "java:comp/JMSConFact")! ConnectionFactory conn;! @Resource(mappedName = "jms/mailRegistQueue")! Queue queue;!! public void registEmailAddress(String address){! try(JMSContext context = conn.createContext()){!   context.createProducer().send(queue,  !                               address);}}}

Send  :  JMS  2.0  (Java  EE  7)

Page 29: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 29 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 29

@MessageDriven(mappedName = "jms/mailRegistQueue")!public class SendMessageMDB implements MessageListener{! public SendMessageMDB(){}! @Inject MailSender mailSender;! @Override! public void onMessage(Message message) {! try {! TextMessage msg = (TextMessage) message;! mailSender.sendMessage(msg.getText());! } catch (JMSException jmse) {! jmse.printStackTrace();! }! }}

Receive:  MDB  (Java  EE  7)

Page 30: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 30

Servlet  3.0  :  since  Java  EE  6(asyncSupported  =  true)

Page 31: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 31 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 31

@WebServlet(name = "MailSenderServlet", ! urlPatterns = {"/MailSenderServlet"}, ! asyncSupported = true)!public class MailSenderServlet extends HttpServlet {!! protected void processRequest(! HttpServletRequest request, ! HttpServletResponse response)! throws ServletException, IOException {! AsyncContext ac = request.startAsync();! ac.start(new MailSenderRunnable(ac));! }}!

Servlet  3.0  :  Async  Servlet

Page 32: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 32

EJB  3.1  :  since  Java  EE  6@Asynchronous

Page 33: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 33 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 33

@Stateless!public class SyncEmailSenderEJB {! @Inject! MailSender mailsend;! public void syncSendMessage(String email){! mailsend.sendMessage(email);! }!! @Asynchronous! public void asyncSendMessage(String email){! mailsend.sendMessage(email);! }}!

EJB  3.1  (Java  EE  6)

Page 34: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 34

Concurrency  Utilities  for  EE

Page 35: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 35

Application  Servers

Java  SE

Web/EJB  Container

EJB JSP

Servlet

Runnable

CallableOther  Java  EE  functionality  (JAX-‐‑‒RS,JavaMail,  CDI,  etc)

Not  recommended  to  create  Threadon  Java  EE  environment.

Thread  run  outside  of  the  Container

Page 36: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 36

Application  Servers

Java  SE

Web/EJB  Container

EJB JSP

Servlet

Runnable

Callable

Concurrency  Architecture  on  EE  7

Other  Java  EE  function(JAX-‐‑‒RS,JavaMail,  CDI,  etc)

ManagedExecutor  ServiceManagedScheduledExecutorServiceContextServiceManagedThreadFactoryConcurrency  Utilities  for  EE

Page 37: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 37 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 37

Memo

It  is  easy  to  implement  !!

It  is  possible  to  Customize  !!

Small  Package  :  Total  12  class

Page 38: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 38 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 38

Usecase  senario?

For  long  running  process

Effective  use  of  hardware!

For  executing  regularly

Page 39: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 39 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 39

Usecase  senario

Would  like  to  run  a  Task  on  Java  EE  

environmentWhich  is  implemented

 on  Java  SE  

environment.

Page 40: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 40 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 40

Important  Interfaces

Best  4

• ManagedExecutorService

• ManagedScheduledExecutorService

• ManagedThreadFactory

• ContextService

Page 41: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 41

Easy  development  To  create  Async  Task(ManagedExecutorService)

Page 42: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 42 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 42

Memo Most easy way !!

Page 43: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 43

Implements  some  Task

A  implements  RunnableB  implements  Callable

Implement  Async  Task

Use  the  configured  managed  Thread  by  resource  Injection

Configure  Server  side

Possible  to  use  the  default  configuration

1 2

Step  to  create  Async  Task

Page 44: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 44 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 44

public class MyRunnableTask implements Runnable {! @Override! public void run() { ! try {! Thread.sleep(10000); //do Something } catch (InterruptedException ex) {! logger.log(Level.SEVERE, null, ex);! }! }!}!

Implement  Runnable  Task1

Page 45: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 45 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 45

Implement  Callable  Task        ●  Possible  to  get  the  return  value        ●  Possible  to  throw  the  Exception

public class MyCallableTask implements ! Callable<String> {! @Override! public String call() throws Exception {! return “Hello World”;! }!}!

Page 46: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 46

Configuration  on  Server  Side2

Page 47: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 47 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 47

@Stateless!public class MyManagedExecutorService {! @Resource(name = ! "concurrent/DefaultManagedExecutorService")! ManagedExecutorService managedExecsvc; ! public void execExecutorService() {! MyRunnableTask task = new MyRunnableTask();! managedExecsvc.submit(task);!      MyCallableTask singleTask = !          new MyCallableTask("Foo Bar");! Future<String> singleFuture =    ! managedExecsvc.submit(singleTask);}!

Exec  Async  Task  on  EJB3

Inject  the  resource

Page 48: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 48

Scheduling  the  Async  Task(ManagedScheduledExecutorService)

Page 49: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 49

Implement  the  Task

A  implements  RunnableB  implements  Callable

Implement  Async  Task

Use  the  configured  managed  Thread  by  resource  Injection

Configure  on  Server  Side

Possible  to  use  default  configuration

1 2

Scheduling  Async  Task  Impl

Page 50: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 50

Server  Side  Configuration2

Page 51: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 51 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 51

@Stateless!public class MyManagedScheduledExecutorService{! @Resource(name = "concurrent/! DefaultManagedScheduledExecutorService")! ManagedScheduledExecutorService managedScheduledExecsvc;!! public void execScheduledExecutorService() {! MyRunnableTask task = new MyRunnableTask();! managedScheduledExecsvc.schedule(! task, 60L, TimeUnit.SECONDS);! }!

Exec  Async  Scheduled  Task3

Exec  TaskAfter  1  min.

Page 52: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 52 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 52

@Stateless!public class MyManagedScheduledExecutorService{! @Resource(name = "concurrent/! DefaultManagedScheduledExecutorService")! ManagedScheduledExecutorService managedScheduledExecsvc;!! public void execScheduledExecutorService() {! MyRunnableTask task = new MyRunnableTask();! managedScheduledExecsvc.schedule(! task, new MyTrigger(new Date(), 10, 1000) }!

You  can  Implement  own  trigger

Exec  Async  Scheduled  Task3

Page 53: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 53 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 53

import javax.enterprise.concurrent.Trigger;!public class MyTrigger implements Trigger {!! @Override! public Date getNextRunTime(LastExecution le, ! Date date){! }!! @Override! public boolean skipRun(LastExecution le, ! Date date) {!! }!}! On  Trigger  you  can  i

mplement  

The  next  run  time  and/or  skip

Page 54: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 54

Management  and  Monitoringof  Task  Lifecycle

Page 55: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 55

Lifecycle  of  Task

taskSubmitted Submitted taskStarting

taskAborted Started

taskDone

Done

submit() submitsuccess

Cancel  or  Abort

About  to  Start

Running  Task

Cancelled  or  aborted Task  has  finished

Task  Monitoring

    :  can  write

Rejected

Page 56: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 56 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 56

public class MyManagedTaskListener implements ! ManagedTaskListener {! public void taskSubmitted(Future<?> future, ! ManagedExecutorService mes, Object o) {! }! public void taskStarting(Future<?> future, ! ManagedExecutorService mes, Object o) {! }! public void taskAborted(Future<?> future, ! ManagedExecutorService mes, Object o, Throwable thrwbl){! }! public void taskDone(Future<?> future, ! ManagedExecutorService mes, Object o, Throwable thrwbl){! }!}!

Create  own  Task  Listener

which  is  implemented  by  

ManagedTaskListener

Page 57: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 57 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 57

@Resource(name = "concurrent/! MyManagedExecutorService")!ManagedExecutorService manageExecsvc;!!public void invokeMyTaskListener() {! MyRunnableTask task = new MyRunnableTask();! MyManagedTaskListener listener = ! new MyManagedTaskListener();! Runnable taskWithListener = ! ManagedExecutors.managedTask(task, listener);! manageExecsvc.execute(taskWithListener);!}!

Page 58: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 58

Detail  of  Internal  BehaviorContextSerivce

Page 59: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 59 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 59

ManagedExecutorService

ManagedScheduledExecutorService

We  can  understand  :

it  is  very  easy  to  implement  the  concurrent  t

ask            

by  Resource  Injection.

We  can  manage  the  lifecycle  of  tasks.

Page 60: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 60 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 60

How  to  run  the  concurrent  

tasks  internally  ?

Page 61: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 61 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 61

MemoInternally  :

Use  “Dynamic  Proxy”  and

add  some  context  informations

Page 62: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 62 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 62

Memo

Do  you  remember  

Dynamic  Proxy  ?

(java.lang.reflect.Proxy)

Page 63: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 63

Method  Invocation  by  Dynamic  Proxypublic class MyRunnable implements Runnable{! @Override! public void run() {!   System.out.println(“Original Method Invoke");!  }!}

This  Task  will  be  executed  via  

Dynamic  Proxy

Page 64: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 64

Implement  of  own  InvocationHandler

public class MyInvocationHandler implements InvocationHandler {! private Object underlying;! public MyInvocationHandler(Object underlying) {! this.underlying = underlying;! }!

@Override!public Object invoke(Object proxy, Method method, !             Object[] args) throws Throwable {! System.out.println(”Pre Invoke of orign method");! Object ret = method.invoke(underlying, args);! System.out.println(“Post Invoke of orign method");! return ret;}!}

Page 65: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 65

Execute  the  Task  via  Dynamic  Proxy

public class MyDynamicProxy {! public static void main(String argv[]){!   //… create proxied Task here!}}!

MyRunnable task = new MyRunnable();!InvocationHandler handler = new !                   MyInvocationHandler(task);!Runnable proxy = !    (Runnable)Proxy.newProxyInstance(!       MyRunnable.class.getClassLoader(), !       new Class[]{Runnable.class}, handler);!ExecutorService exec = !           Executors.newSingleThreadExecutor();!exec.submit(proxy);

Page 66: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 66

Result  of  execute  Task  via  Dynamic  Proxy

Pre  Invoke  of  orign  methodOriginal  Method  InvokePost  Invoke  of  orign  method

ExecutorService exec =  ! Executors.newSingleThreadExecutor();!exec.submit(proxy);!

Useful  for  AOP

Page 67: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 67 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 67

Memo

InvocationHandler  is  

implemented  by  App  Server

*  GlassFish  v4.0  

    org.glassfish.enterprise.concurrent.inter

nal.  

    ContextProxyInvocationHandler

Page 68: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 68

Configuration  on  ServerSide1

Page 69: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 69 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 69

@Stateless!public class ContextServiceManager {! @Resource(name = "concurrent/DefaultContextService")! ContextService ctxSvc;!!  public void execSimpleContextService() {! ExecutorService singleThreadExecutor = ! Executors.newSingleThreadExecutor(threadFactory);! MyRunnableTask task = new MyRunnableTask();! Runnable proxiedTask =! ctxSvc.createContextualProxy(task,Runnable.class);! singleThreadExecutor.submit(proxiedTask);}}! !

CreateDynamic  Proxy

Task  Execution  with  Context2

Page 70: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 70 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 70

Original  Task

Task  which  is  created  byDynamic  Proxy

Memo

It  is  possible  to  run  the  Task  on  EE  with  Context.  

Page 71: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 71

Detail  of  Internal  BehaviorThreadFactory

Page 72: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 72 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 72

Memo • we can implement custom managed thread

pool on the program side not server side

and can execute from the created pool.

※ It is possible to customize the way to

create a Thread by program.

Page 73: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 73

Configuration  on  ServerSide1

Page 74: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 74 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 74

@Resource(name = "concurrent/! DefaultManagedThreadFactory")!ManagedThreadFactory threadFactory;!public void execThreadFactory() {! MyRunnableTask task = new MyRunnableTask();! Thread taskThread = ! threadFactory.newThread(task);! taskThread.start();!}!

 Create  Thread  via  ThreadFactory(It  is  for  long  running  process)

2

Simple

Page 75: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 75 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 75

ExecutorService threadPoolExecutor = ! Executors.newFixedThreadPool(4,threadFac);!!!threadPoolExecutor = new ThreadPoolExecutor(4, 4,!                    0L, TimeUnit.MILLISECONDS,!                    new LinkedBlockingQueue<Runnable>(), !                    threadFac);!

 It  is  possible  to  create  custom  Thread  Pool  by  using  ThreadPoolExecutor

Above  two  code  is  same

java.util.concurrent.ThreadPoolExecutor

Page 76: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 76 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 76

@Resource(name = "concurrent/! DefaultManagedThreadFactory")!ManagedThreadFactory threadFactory;!public void execThreadFactory() {!  MyRunnableTask task = new MyRunnableTask();!  ExecutorService exec = !           new ThreadPoolExecutor(4, 4,!           0L, TimeUnit.MILLISECONDS,! new LinkedBlockingQueue<Runnable>(), !           threadFactory);!  exec.submit(task);}!

Create  new  Thread  from  Custom  Thread  Pool

Page 77: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 77

Finally

Page 78: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 78 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 78

Restriction  :

We  can  use  with  CDI  only  for

   @ApplicationScoped

   @Dependent

Note  :  Lifecycle  of  CDI

Page 79: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 79 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 79

Restriction

You  canʼ’t  use  on  Application  

Client  Container

Page 80: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 80 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 80

Restriction

We  canʼ’t  use  with  

Fork/Join  (ForkJoinPool).

Page 81: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 81 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 81

Restriction

We  canʼ’t  invoke  lifecycle  method  of  

ExecutorService.

(ex.  shutdown,  shutdownNow)

※  ManagedExecutorService

※  ManagedScheduledExecutorService

Page 82: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 82 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 82

ConclusionEffective  use  of  computer  assets    from  Async  to  Concurrent

Safe  and  easy  way  to  create  the  thread  on  Java  EE  environment

Flexible  customization

Page 83: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 83 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 83

Related  Session[CON7948]  :  JSR  236:  Introduction  to  Concurrency  Utilities  for  Java  EE  1.0

Thursday,  Sep  26,  12:30  PM  -‐‑‒  1:30  PM  Parc  55  -‐‑‒  Cyril  Magnin  I

Anthony  Lai  –  Oracle  (Spec  Lead)Fred  Rowe  –  IBM  

Page 84: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 84 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 84

Resource

Sample  Source  Code        https://github.com/yoshioterada/                                ConcurrentUtil4EE

JSR  236  Related  Page        http://jcp.org/en/jsr/detail?id=236        https://java.net/projects/                              concurrency-‐‑‒ee-‐‑‒spec

Page 85: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 85

Graphic Section Divider

Page 86: JavaOne 2013 San Francisco Asyn-ConcurrencyOnEE7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 86