JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

description

Presentation about the newly released JSR236 spec that Anthony Lai (Oracle) and Fred Rowe (IBM) did for session CON7948 at JavaOne SF 2013. JSR 236 is part of EE7 platform and defines extensions to the SE concurrency APIs to allow them to be used in an app server environment.

Transcript of JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

Page 1: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

Page 2: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

JSR 236: Introduction to Concurrency Utilities for Java EE 1.0Anthony LaiOracle

Fred RoweIBM

Page 3: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.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.

Page 4: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

Program Agenda

Overview

Managed Objects

Features

Summary

Resources

Page 5: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

Overview

Provide a simple and flexible standard API for application component providers to design applications using concurrency design principles

Provide a simple migration path from Java SE Concurrency Utilities (JSR-166) to the Java EE platform by providing consistency between the two platforms

Allow application component providers to easily add concurrency to existing Java EE applications

Support simple and advanced concurrency patterns without sacrificing usability

Goals

Page 6: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

Overview

2003 – JSR 236 and JSR237 filed. CommonJ API provides context aware Work Managers and Timers to Java EE applications

2006 – CommonJ API replaced by API that extends from Java SE concurrency utilities

2008 – Merged into JSR 236 2008 – 2012 … 2012 – JSR 236 restarted 2013 – JSR 236 released and become part of Java EE 7

History

Page 7: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

Overview

Simple, standardized API for using concurrency from application components

Extension of Java SE Concurrency Utilities APIs (JSR-166) Provide low-level asynchronous processing capabilities to Java EE

application components in a safe, reliable, consistent manner Manage and monitor the lifecycle of asynchronous operations

Main Features

Page 8: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

Overview

Provides 4 types of managed objects that implement these interfaces in javax.enterprise.concurrent package:

– ManagedExecutorService– ManagedScheduledExecutorService– ManagedThreadFactory– ContextService

Container context propagation Transaction management Task events notification

Main Features

Page 9: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

Program Agenda

Overview

Managed Objects

Features

Summary

Resources

Page 10: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

Managed Objects

Managed Objects are provided by the Java EE Product Provider Applications access managed objects by

– JNDI lookup

– resource injection using @Resource

Configurable Pre-configured default managed objects are available

– e.g. java:comp/DefaultManagedThreadFactory

Overview

Page 11: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ManagedThreadFactory

A standard way for applications to obtain a container-managed threads from Java EE Containers

Supports context propagation Can be used with asynchronous processing API in Servlets Can be used for creating custom executors in advanced use cases

Overview

Page 12: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ManagedThreadFactory

Interface extends from java.util.concurrent.ThreadFactory– Same API: Thread.newThread(Runnable)– Container context captured at ManagedThreadFactory creation

will be propagated to the thread returned Threads returned by newThread() method are required to implement

the ManagableThread interface– boolean isShutdown()

Can be used with Java SE concurrency utilities APIs where ThreadFactory is needed. e.g. in java.util.concurrent.Executors

API

Page 13: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ManagedThreadFactory

Thread interrupted when ManagedThreadFactory shuts down Runnable implementations should check ManagableThread.isShutdown() when interrupted

– clean up if it returns true

Shutdown

Page 14: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ManagedThreadFactory

// Create a ThreadPoolExecutor using a ManagedThreadFactory.@Resource ManagedThreadFactory tf;

public ExecutorService getManagedThreadPool() {// All threads will run as part of this application component.return new ThreadPoolExecutor(5, 10, 5,

TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(10),

tf);}

Example 1

Page 15: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ManagedThreadFactory

@WebServlet(asyncSupported=true)

public class TestServlet extends HttpServlet { @Resource private ManagedThreadFactory managedThreadFactory;

protected void doGet(HttpServletRequest req, HttpServletResponse res {

final AsyncContext asyncContext = req.startAsync();

Runnable runnable = new Runnable() {public void run() { …

asyncContext.complete();}

};

Thread thread = managedThreadFactory.newThread(runnable); thread.start();

…}

}

Example 2 – Use with Asynchronous Servlet

Page 16: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ManagedExecutorService

For running tasks asynchronously on threads provided by Java EE product provider

– Tasks must implement either java.util.concurrent.Callable or java.lang.Runnable

Supports context propagation Allow application developers to use familiar Java SE APIs for

concurrent processing of tasks in Java EE

Overview

Page 17: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ManagedExecutorService

Extends from java.util.concurrent.ExecutorService– execute, submit, invokeAll, invokeAny

– No new APIs

Future is returned upon task submission– Checks for the task execution status

– Cancels the task

– Waits and retrieves result

Lifecycle APIs disabled – throws IllegalStateException– awaitTermination, isTerminated, isShutdown, shutdown, shutdownNow

API

Page 18: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ManagedExecutorServiceExample 1

@Resource ManagedExecutorService mes;

void someMethod() { Callable<Integer> c = new Callable<>() { Integer call() { // Interact with a database...return answer. }

//Submit the task and do something else. Future result = mes.submit(c); ... //Get the result when ready... int theValue = result.get(); ...

Page 19: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ManagedExecutorServiceExample 2 – Use with Asynchronous Servlet

@WebServlet(asyncSupported=true)

public class TestAsyncMESServlet extends HttpServlet { @Resource private ManagedExecutorService managedExecutorService;

protected void doGet(HttpServletRequest req, HttpServletResponse res {

final AsyncContext asyncContext = req.startAsync();

Runnable runnable = new Runnable() {

public void run() {

asyncContext.complete();}

};

managedExecutorService.submit(runnable);

…}

}

Page 20: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ManagedExecutorService

Managed Thread Pool Executor Component Relationship

Page 21: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ManagedScheduledExecutorService

For scheduling tasks to run– after a given delay

– periodically

– at some custom schedule

Tasks are run on threads that are provided by the Java EE container Supports context propagation Allows application developers to use familiar Java SE APIs for

submitting scheduled tasks in Java EE

Overview

Page 22: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ManagedScheduledExecutorService

Extends from ManagedExecutorService Extends from java.util.concurrent.ScheduledExecutorService

– schedule, scheduleAtFixedRate, scheduleWithFixedDelay

Lifecycle APIs disabled – throws IllegalStateException– awaitTermination, isTerminated, isShutdown, shutdown, shutdownNow

Extension API to support custom scheduling – schedule with Trigger

API

Page 23: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ManagedScheduledExecutorServiceAPI from ScheduledExecutorService

<V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit);

ScheduledFuture<?> schedule(Runnable command, long delay,

TimeUnit unit);

ScheduledFuture<?> scheduleAtFixedFate(Runnable command,

long initialDelay, long period, TimeUnit unit);

ScheduledFuture<?> scheduledWithFixedDelay(Runnable command,

long initialDelay, long delay, TimeUnit unit);

Page 24: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ManagedScheduledExecutorServiceAPI for Custom Scheduling

<V> ScheduledFuture<V> schedule(Callable<V> callable, Trigger trigger);

ScheduledFuture<?> schedule(Runnable command, Trigger trigger);

Page 25: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ManagedScheduledExecutorServiceTrigger

For supporting custom scheduling rules– Can be simple: single, absolute date/time

– Can be complex calendar logic

– Next trigger time can be calculated based on previous trigger execution date/time and result

Implemented by application developers Submitted along with a task using the schedule method in ManagedScheduledExecutorService

Page 26: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ManagedScheduledExecutorServiceTrigger API

boolean skipRun(LastExecution lastExecutionInfo, Date scheduledRunTime)

Date getNextRunTime(LastExecution lastExecutionInfo, Date taskScheduledTime)

Page 27: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ManagedScheduledExecutorServiceTrigger Example

public class SimpleFixedDateTrigger implements Trigger { private Date fireTime; public SimpleFixedDateTrigger(Date triggerDate) { fireTime = triggerDate; } public Date getNextRunTime( LastExecution lastExecutionInfo, Date taskScheduledTime) { if(taskScheduledTime.after(fireTime)) { return null; } return fireTime; } public boolean skipRun(LastExecution lastExecutionInfo, Date scheduledRunTime) { return scheduledRunTime.after(fireTime); } }

Page 28: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ContextService

For creating contextual proxy objects– Application context is captured upon creation

– Proxy object methods will run within the captured context at a later time

For use in advanced use cases– E.g. to propagate user identity

– E.g. to request task listener notifications to be run under container context

Uses dynamic proxy mechanism in java.lang.reflect package

Overview

Page 29: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ContextService

Contextual proxy objects customizable through execution properties– Transaction property

– Vendor specific properties, e.g. vendorA.security_token_expiration

API for returning the execution properties on the given contextual object proxy instance

– Map<String,String> getExecutionProperties(Object contextualProxy)

Execution Properties

Page 30: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ContextService

For creating contextual proxy objects:– <T> T createContextualProxy(T instance, Class<T> intf)

– Object createContextualProxy(Object instance, Class<?>... Interfaces)

– <T> T createContextualProxy(T instance, Map<String,String> executionProperties, Class<T> intf)

– Object createContextualProxy(Object instance, Map<String,String> executionProperties, Class<?>... Interfaces)

API

Page 31: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ContextServiceExample 1

@Resource ContextService ctxSvc;MyAppIntf proxy = ctxSvc.createContextualProxy (myAppImpl, MyAppIntf.class);

// invoke at a later time, possibly in a different app // componentproxy.doSomething();

Page 32: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ContextServiceExample 2

// In applicationpublic interface MessageProcessor {

public void processMessage(Message msg)…

}

// Within servlet or EJB method…@Resource ContextService ctxSvc;

void businessMethod() {MessageProcessor msgProcessor = …// Wrap with the current contextMessageProcessor proxy =

ctxSvc.createContextualProxy (msgProcessor, MessageProcessor.class);

// Store the contextual proxy object somewhere for running later.store.putIt(proxy);…

Page 33: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ContextServiceExample 2 (cont’d)

// Elsewhere, in a different thread, retrieve the MessageProcessor contextual proxy // object from the storeMessageProcessor proxy = store.getIt();

// The proxy method processMessage() is invoked on// this thread, but with the context of the servlet or// EJB that created it. proxy.processMessage(msg);

Page 34: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

Program Agenda

Overview

Managed Objects

Features

Summary

Resources

Page 35: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

Context Propagation

Types of container context to be propagated– Class loading, JNDI namespace, security identity

Configurable Extensible Supported in all 4 types of managed objects

Overview

Page 36: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

Context Propagation

Application context captured at– Task submission

– ManagedThreadFactory creation

– Contextual proxy object creation

Application context propagated to thread– Before task execution

– During invocation of contextual proxy object methods (with the exception of hashCode, equals, toString and all other methods declared in Object)

Overview (cont’d)

Page 37: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

Transaction Management

Transactions are not propagated to the threads where tasks are run UserTransaction from JTA is available Contextual proxy objects from ContextService can be run on the

same transaction context of the invoking thread– Configurable via execution property ManagedTask.TRANSACTION

ManagedTask.SUSPEND (default) ManagedTask.USE_TRANSACTION_OF_EXECUTION_THREAD

Overview

Page 38: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

Task Events Notifications

Task lifecycle events notifications via ManagedTaskListener interface methods when task is:

– submitted

– not able to start or is cancelled

– about to start

– completed running, either succeeded or failed with exception

Can be used for logging tasks progress Can be used for remedial actions such as resubmit a failed task

Overview

Page 39: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

Task Events NotificationsManagedTaskListener

ManagedTaskListener implementations typically provided by application component

Listeners can be associated with tasks that are submitted to ManagedExecutorService or ManagedScheduledExecutorService

Notification methods are run in unspecified context by default– Can be made contextual with contextual proxy object for ManagedTaskListener

Page 40: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

Task Events NotificationsManagedTaskListener API

void taskSubmitted(Future<?> future, ManagedExecutorService executor, Object task)

void taskStarting(Future<?> future, ManagedExecutorService executor, Object task)

void taskAborted(Future<?> future, ManagedExecutorService executor, Object task, Throwable exception)

void taskDone(Future<?> future, ManagedExecutorService executor, Object task, Throwable exception)

Page 41: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

Task Events NotificationsRegistering ManagedTaskListener

// Runnable implements ManagedTaskpublic class TaskWithListener implements Runnable, ManagedTask { ... public ManagedTaskListener getManagedTaskListener() { return aManagedTaskListener; }}//use ManagedExecutors utility to associate a ManagedTaskListener to a task Runnable aTask; ManagedTaskListener myTaskListner; Runnable taskWithListener = ManagedExecutors.managedTask(aTask, myTaskListener);

...ManagedExecutorService executor = ...;executor.submit(taskWithListener);

Page 42: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ManagedTaskOverview

Any task submitted to an ManagedExecutorService or an ManagedScheduledExecutorService can optionally implement ManagedTask

Provides– Identifying information about the task

– ManagedTaskListener for lifecycle events notification

– Any additional execution properties

Page 43: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ManagedTaskAPI

API– Map<String, String> getExecutionProperties()

– ManagedTaskListener getManagedTaskListener()

Execution properties– LONGRUNNING_HINT

– IDENTITY_NAME

– TRANSACTION SUSPEND USE_TRANSACTION_OF_EXECUTION_THREAD

Page 44: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ManagedExecutorsOverview

Utility class in javax.enterprise.concurrent package Provided by Java EE for use by application components Contains methods for

– Testing whether current thread is a ManageableThread that has been marked for shutdown

– Creating a ManagedTask that connects the given Callable/Runnable with a given ManagedTaskListener and with any given execution properties

Page 45: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

ManagedExecutorsAPI

public static boolean isCurrentThreadShutdown() public static Runnable managedTask(Runnable task, ManagedTaskListener taskListener) throws IllegalArgumentException

public static Runnable managedTask(Runnable task, Map<String,String> executionProperties, ManagedTaskListener taskListener) throws IllegalArgumentException

public static <V> Callable<V> managedTask(Callable<V> task, ManagedTaskListener taskListener) throws IllegalArgumentException

public static <V> Callable<V> managedTask(Callable<V> task, Map<String,String> executionProperties, ManagedTaskListener taskListener) throws IllegalArgumentException

Page 46: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

Program Agenda

Overview

Managed Objects

Features

Summary

Resources

Page 47: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

Summary

Provides asynchronous capabilities to Java EE application components

Allows Java SE developers simple migration path to Java EE Provides managed objects to applications for submitting tasks

and obtaining managed threads Features such as propagation of container context Java EE application developers now have tools to have more

advanced control of asynchronous processing

Page 48: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

Program Agenda

Overview

Managed Objects

Features

Summary

Resources

Page 49: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

Resources

Spec and API docs– http://jcp.org/en/jsr/detail?id=236

– http://docs.oracle.com/javaee/7/api

– http://concurrency-ee-spec.java.net

Java EE 7 SDK– http://www.oracle.com/javaee

Please send feedback to– [email protected]

Page 50: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

Page 51: JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)

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

Graphic Section Divider