860 likes | 1.02k Views
[ 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.
E N D
[ 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
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.
It is very easy to implement concurrent application on EE 7 environment. Customizable flexibly
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
History of Async Application in Java Java SE Environment
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
History of Java SE Thread Java SE 7 JSR-166y Fork/Join ・・・・・・・・・・・・・・・・・・ 2014 2011 Java SE 8 Lambda Expression & JSR-166e Concurrency Utilities
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
Generated Thread Indefinitely Thread-1 Thread-2 Thread-3 ・・・ new Thread(r).start(); Thread-n
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 スタック
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
Java Concurrency Utilities • Easy API to implement concurrency application • Provide simple and easy API • Scalability, Performance, Maintainability, Thread safe, easy to understand
JSR-166 Overview • Async task operation • Concurrency Collection • lock, synchronizer • Atomic operation
Useful classes • Executors, Thread Pool, Futures • Collection: Queues, Blocking Queues, Concurrent HashMap • Lock, synchronization: Semaphores, Barriers, Atomic variable • Others …
public interface Executor{ void execute(Runnable command); } ExecutorInterface Async invocation
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
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
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
Benefit of Concurrency Utilities Execute Thread more Efficiently Possible to manage the lifecycle of Thread
History of Async on Java EE JMS(MDB) Async Servlet Async EJB
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
JMS & MDB More Easy : Java EE 7
Delegate the operation to External Message Provider jms/MyQueue Queue Name JNDI Naming Space Destination App Server Administrator Conn Factory Message Provider jms/MyConFactory
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
@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)
@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)
Servlet 3.0: since Java EE 6 (asyncSupported = true)
@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
EJB 3.1 : since Java EE 6 @Asynchronous
@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)
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
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
Memo It is easy to implement !! It is possible to Customize !! Small Package : Total 12 class
Usecasesenario? For long running process Effective use of hardware! For executing regularly
Usecasesenario Would like to run a Task on Java EE environment Which is implemented on Java SE environment.
Important Interfaces Best 4 • ManagedExecutorService • ManagedScheduledExecutorService • ManagedThreadFactory • ContextService
Easy development To create Async Task (ManagedExecutorService)
Memo Most easy way !!
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
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
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
@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
Scheduling the Async Task (ManagedScheduledExecutorService)
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