1 / 86

[ CON10982 ] Implementation of Async and Concurrent Applications in the Java EE Environment

[ CON10982 ] Implementation of Async and Concurrent Applications in the Java EE Environment. Yoshio Terada Java Evangelist http://yoshio3.com. If you have some questions, could you give me a message on Twitter with following hash tag ? [#CON10982] My Twitter ID : @ yoshioterada.

lis
Download Presentation

[ CON10982 ] Implementation of Async and Concurrent Applications in the Java EE Environment

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. If you have some questions, could you give me a message on Twitter with following hash tag ? [#CON10982] My Twitter ID : @yoshioterada

  3. 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.

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

  5. Structure of My Sesiosn 40 Min With Demo 15-20 Min With Demo Review of Async/Concurrency on Java SE & Java EE6 Concurrency Utilities on Java EE 7

  6. History of Async Application in Java Java SE Environment

  7. Hisotry of Java Thread JDK1.0 Thread Runnable J2SE 1.4 J2SE1.2 2006 2004 Java SE 6 JSR-166x 2002 2000 1998 1997 1996 Java SE 5 JSR-166 Concurrency Utilities J2SE 1.3 JDK1.1

  8. History of Java SE Thread Java SE 7 JSR-166y Fork/Join ・・・・・・・・・・・・・・・・・・ 2014 2011 Java SE 8 Lambda Expression & JSR-166e Concurrency Utilities

  9. No more Recommend This way 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);//Serveropeartion }}; new Thread(r).start(); } } } Create new Thread for request Ex : Impl of MultiThread Web Server

  10. Generated Thread Indefinitely Thread-1 Thread-2 Thread-3 ・・・ new Thread(r).start(); Thread-n

  11. Ex : Stack area is also allocated -Xss Thread-1 Stack Thread-1 Thread-2 Stack Thread-2 Thread-3 Stack Thread-3 … … Thread-n Stack Thread-n スタック

  12. Disadvantage of unlimited thread Load of Java VM and OS Memory Consumption for each thread UpperLimit of the number of thread creation Overhead of the context switch

  13. Java Concurrency Utilities • Easy API to implement concurrency application • Provide simple and easy API • Scalability, Performance, Maintainability, Thread safe, easy to understand

  14. JSR-166 Overview • Async task operation • Concurrency Collection • lock, synchronizer • Atomic operation

  15. Useful classes • Executors, Thread Pool, Futures • Collection: Queues, Blocking Queues, Concurrent HashMap • Lock, synchronization: Semaphores, Barriers, Atomic variable • Others …

  16. public interface Executor{ void execute(Runnable command); } ExecutorInterface Async invocation

  17. public interface ExecutorService extends Executor{ void shutdown(); List<Runnable> shutdownNow(); booleanisShutdown(); booleanisTerminated(); booleanawaitTermination(long timeout, TimeUnitunit); <T> Future<T> submit(Callable<T> task) // and more … } ExecutorService Interface Lifecycle management, get return value

  18. static int CPU_NUM = Runtime.getRuntime().availableProcessors(); ExecutorServicepool = 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

  19. ExecutorService execution using fixed Thread Pool ExecutorService pool = Executors.newFixedThreadPool(CPU_NUM); pool.execute(r); newFixedThreadPool LinkedBlockingQueue (FIFO) • Reuse the created Thread • Number of max Thread • Queing of incoming request ThreadFactory … T2 T3 T4 Tn T1

  20. Benefit of Concurrency Utilities Execute Thread more Efficiently Possible to manage the lifecycle of Thread

  21. History of Async on Java EE JMS(MDB) Async Servlet Async EJB

  22. History of Async on Java EE J2EE 1.4 J2EE 1.2 JMS 2009 2006 2003 2001 1999 Java EE 6 Async Servlet Async EJB 1998 J2EE 1.3 MDB Java EE 5 JPE

  23. JMS & MDB More Easy : Java EE 7

  24. Delegate the operation to External Message Provider jms/MyQueue Queue Name JNDI Naming Space Destination App Server Administrator Conn Factory Message Provider jms/MyConFactory

  25. Developer refer to the JNDI Resource Injection JNDI Name Space jms/MyFactory jms/MyQueue Destination Conn Factory Developer Queue Name JMS Client Message Provider JMS Client connect to Message Provider via JNDI lookup

  26. @Stateless public class MailAddressRegisterEJB { @Resource(mappedName = "java:comp/JMSConFact") ConnectionFactoryconn; @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)

  27. @MessageDriven(mappedName = "jms/mailRegistQueue") public class SendMessageMDB implements MessageListener{ public SendMessageMDB(){} @InjectMailSendermailSender; @Override public void onMessage(Message message) { try { TextMessagemsg = (TextMessage) message; mailSender.sendMessage(msg.getText()); } catch (JMSExceptionjmse) { jmse.printStackTrace(); } }} Receive: MDB (Java EE 7)

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

  29. @WebServlet(name = "MailSenderServlet", urlPatterns= {"/MailSenderServlet"}, asyncSupported= true) public class MailSenderServlet extends HttpServlet{ protected void processRequest( HttpServletRequestrequest, HttpServletResponseresponse) throws ServletException, IOException{ AsyncContext ac = request.startAsync(); ac.start(new MailSenderRunnable(ac)); }} Servlet 3.0 : Async Servlet

  30. EJB 3.1 : since Java EE 6 @Asynchronous

  31. @Stateless public class SyncEmailSenderEJB { @Inject MailSendermailsend; public void syncSendMessage(String email){ mailsend.sendMessage(email); } @Asynchronous public void asyncSendMessage(String email){ mailsend.sendMessage(email); }} EJB 3.1 (Java EE 6)

  32. Concurrency Utilities for EE

  33. Not recommended to create Thread on Java EE environment. Application Servers Web/EJB Container Thread run outside of the Container EJB JSP Servlet Runnable Other Java EE functionality (JAX-RS,JavaMail, CDI, etc) Callable Java SE

  34. Concurrency Architecture on EE 7 Application Servers Web/EJB Container Runnable EJB JSP Servlet Callable Concurrency Utilitiesfor EE ManagedExecutor Service ManagedScheduledExecutorService ContextService ManagedThreadFactory Other Java EE function (JAX-RS,JavaMail, CDI, etc) Java SE

  35. Memo It is easy to implement !! It is possible to Customize !! Small Package : Total 12 class

  36. Usecasesenario? For long running process Effective use of hardware! For executing regularly

  37. Usecasesenario Would like to run a Task on Java EE environment Which is implemented on Java SE environment.

  38. Important Interfaces Best 4 • ManagedExecutorService • ManagedScheduledExecutorService • ManagedThreadFactory • ContextService

  39. Easy development To create Async Task (ManagedExecutorService)

  40. Memo Most easy way !!

  41. Step to create Async Task 1 2 Implements some Task A implements Runnable B implements Callable Configure Server side Possible to use the default configuration 3 Implement Async Task Use the configured managed Thread by resource Injection

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

  43. public class MyCallableTask implements Callable<String> { @Override public String call() throws Exception { return “Hello World”; } } 1 Implement Callable Task ● Possible to get the return value ● Possible to throw the Exception

  44. Configuration on Server Side

  45. @Stateless public class MyManagedExecutorService{ @Resource(name = "concurrent/DefaultManagedExecutorService") ManagedExecutorServicemanagedExecsvc; public void execExecutorService() { MyRunnableTasktask = new MyRunnableTask(); managedExecsvc.submit(task); MyCallableTasksingleTask = new MyCallableTask("Foo Bar"); Future<String> singleFuture = managedExecsvc.submit(singleTask);} Inject the resource 3 Exec Async Task on EJB

  46. Scheduling the Async Task (ManagedScheduledExecutorService)

  47. Scheduling Async Task Impl 1 2 Implement the Task A implements Runnable B implements Callable Configure on Server Side Possible to use default configuration 3 Implement Async Task Use the configured managed Thread by resource Injection

  48. Server Side Configuration

More Related