32
© 2015 IBM Corporation AAI-2236 Using the New Java Concurrency Utilities with IBM WebSphere Kevin Sutter, STSM WebSphere Java EE Architect

AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Embed Size (px)

Citation preview

Page 1: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

© 2015 IBM Corporation

AAI-2236Using the New Java Concurrency Utilitieswith IBM WebSphere

Kevin Sutter, STSMWebSphere Java EE Architect

Page 2: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Agenda

• Introduction

• Managed services

• Additional APIs

• Additional Resources

1

Page 3: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Introduction

2

2003 2006 2008 2012 2013

JSR 236released as part

of Java EE 7

JSR237 ismerged into

JSR236

JSR236 (Timers)and JSR237 (Work

Managers) filed

CommonJ APIreplaced with

extension of Java SEconcurrency API

JSR 236restarted

JSR Timeline

Page 4: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Introduction

Goals

• Provide easy-to-use support to developers for both simple andadvanced concurrency patterns

• Provide a path to migrate standalone apps using Java SEConcurrency Utilities (JSR-166) to the Java EE platform with aconsistent API

• Provide an easy-to-understand API for developers to createapplications using concurrency design principles

• Make it easy to add concurrency to existing Java EEapplications

3

Page 5: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Introduction

• Extension of the Java SE Concurrency Utilities API

• Addresses long standing tenant of EE app servers that well-behaved applications should not create threads

• WebSphere (like other application servers) provided othermechanisms for creating and managing threads, such asAsynchronous Beans, CommonJ Timer and Work Manager.

• Asynchronous task lifecycle management, monitoring andnotification

• Flexible propagation of common Java EE contexts to tasks

4

Available 4Q2014 via Liberty Repository!

Page 6: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Agenda

• Introduction

• Managed services

• Additional APIs

• Summary

• Additional Resources

5

Page 7: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Services

Overview

• JSR 236 defines four services to be provided by an applicationserver

• ManagedExecutorService

• ManagedScheduledExecutorService

• ManagedThreadFactory

• ContextService

• Services are accessed by application via:• resource injection using @Resource

• JNDI lookup

• default instances

• Configured through vendor-defined properties

6

Page 8: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Services

ManagedExecutorService overview

• Provides a familiar API for concurrent processing of tasks inJava EE

• Extends java.util.concurrent.ExecutorService of

Java SE concurrency API

• Allow execution of asynchronous tasks on server managedthreads

• Tasks must implement either:– java.lang.Runnable

– java.util.concurrent.Callable

7

Page 9: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Services

ManagedExecutorService API

• Supports Java EE context propagation including JNDI naming,classloader, and security contexts

• Not transactional contexts

• Because the service is managed by the server, calling any ofthe lifecycle API methods results in IllegalStateException

• Like Java SE, task(s) submission returns one or moreFuture(s). These are used to:

• check for task execution status

• wait for and retrieve task result

• cancel task

8

Page 10: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Services

ManagedExecutorService Example

@WebServlet(asyncSupported=true)

public class MyServlet extends HttpServlet {

@Resource ManagedExecutorService managedExecutorService;

protected void doGet(HttpServletRequest request,HttpServletResponse response {

final AsyncContext asyncContext = request.startAsync();

Runnable myTask = new Runnable() {

public void run() {

asyncContext.complete();

}

};

Future future = managedExecutorService.submit(myTask);

}

9

Page 11: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Services

ManagedScheduledExecutorService overview

• Provides a familiar API for scheduling asynchronous tasks inJava EE

• Supports Java EE context propagation including JNDI naming,classloader, and security contexts

• Not transactional contexts

• Used for scheduling tasks to run:

• periodically

• after specified delay

• at some custom schedule

10

Page 12: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Services

ManagedScheduledExecutorService API

• Extends both ManagedExecutorService andjava.util.concurrent.ScheduledExecutorService

interfaces

• Like ManagedExecutorService, calling any of the lifecycleAPI methods results in IllegalStateException

• In addition to schedule methods inherited from Java SE API,adds methods to support custom scheduling

• schedule with Trigger interface

11

Page 13: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Services

ManagedScheduledExecutorService Trigger API

• Interface implemented by application developer to supportflexible, custom scheduling

• Scheduling rules may be:

• simple: a single, absolute date/time

• complex: calendar logic

• Trigger is submitted along with a task using a schedule

method in ManagedScheduledExecutorService

12

Page 14: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Services

ManagedScheduledExecutorService Trigger 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);

}

}

13

Page 15: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Services

ManagedThreadFactory overview

• Provides the means for Java EE applications to obtaincontainer-managed threads

• Supports Java EE context propagation including JNDI naming,classloader, and security contexts

• Not transactional contexts

14

Page 16: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Services

ManagedThreadFactory API

• Extends java.util.concurrent.ThreadFactory

• Same API: Thread.newThread(Runnable)

• Supports Java EE context propagation including JNDI naming,classloader, and security contexts

• Not transactional contexts

• Threads from factory are:

• contextualized with container context

• required to implement the ManagableThread interface

15

Page 17: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Services

ManagedThreadFactory Example

// Create a ThreadPoolExecutor using a ManagedThreadFactory.

@Resource ManagedThreadFactory threadFactory;

public ExecutorService getManagedThreadPool() {

// All threads will be contextualized with the context

// of the creating application component.

return new ThreadPoolExecutor(5, 10, 5, TimeUnit.SECONDS,

new ArrayBlockingQueue<Runnable>(10), threadFactory);

}

16

Page 18: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Services

ContextService overview

• Creates dynamic proxy objects• objects are contextualized with container context upon creation

• object methods execute with that captured context

• Used by the other services to contextualize task and threads

• May be used directly for advanced use cases:• request contextualization of Trigger methods

• request contextualization of task listener notification methods

• propagate custom contexts

• Execution properties control how contextualization occurs

17

Page 19: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Services

ContextService API

• Methods to create 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)

18

Page 20: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Services

ContextService Example

public class MyRunnable implements Runnable {

public void run() {

System.out.println("MyRunnable.run with Java EE Context");

}

}

@Resource ThreadFactory threadFactory;

@Resource ContextService ctxService;

MyRunnable myRunnableInstance = new MyRunnable();

Runnable rProxy =ctxService.createContextualProxy(myRunnableInstance, Runnable.class);

ExecutorService exSvc = Executors.newThreadPool(10, threadFactory);

Future future = exSvc.submit(rProxy);

19

Page 21: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Agenda

• Introduction

• Managed services

• Additional APIs

• Additional Resources

20

Page 22: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Additional APIs

Transaction Management

• Transactions are not propagated to the threads on which tasksare run

• Application may obtain a UserTransaction from JTA

• Contextual proxy objects can run in the transaction context ofthe invoking thread, controlled by the execution propertyManagedTask.TRANSACTION

• default is ManagedTask.SUSPEND

• ManagedTask.USE_TRANSACTION_OF_EXECUTION_THREAD

21

Page 23: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Additional APIs

ManagedTaskListener

• Tasks events are emitted to listeners viaManagedTaskListener methods when tasks are:

• submitted

• unable to start or cancelled

• starting

• completed, either successfully or with exceptions

• Useful for:

• monitoring task progress

• resubmitting failed tasks

• ManagedTaskListener methods execute with unspecified

context by default

22

Page 24: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Additional APIs

ManagedTask

• Any task can optionally implement ManagedTask interfacewhich provides:

• ManagedTaskListener for lifecycle events notification

• task identification

• any desired execution properties

• Other standard execution ManagedTask properties

• IDENTITY_NAME – used to provide a task name

• LONGRUNNING_HINT – hint of task length

• TRANSACTION – controls transaction participation

– SUSPEND

– USE_TRANSACTION_OF_EXECUTION_THREAD

23

Page 25: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Additional APIs

ManagedExecutors

• Similar to Executors utility class of Java SE concurrency

package, contain methods for:

• Creating a ManagedTask capable of receiving notifications viathe specified ManagedTaskListener and with any specified

execution properties

• Testing whether current thread is a ManageableThread that hasbeen marked for shutdown

24

Page 26: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Agenda

• Introduction

• Managed services

• Additional APIs

• Additional Resources

25

Page 27: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Additional Resources

• JSR236 specification and API docs

• http://jcp.org/en/jsr/detail?id=236

• JSR236 forum

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

• Java EE 7 API docs

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

26

Page 28: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Sampling of Related Sessions…

• AAI-1713A: Introduction to Java EE 7• Monday, 2-3pm, Mandalay Bay, Reef Ballroom E

• AAI-1641A: Introduction to Web Sockets• Monday, 5-6pm, Mandalay Bay, Reef Ballroom E

• AAI-1313A: Agile Development Using Java EE 7 with WebSphere Liberty Profile(LAB)• Tuesday, 8-10am, Mandalay Bay, South Seas Ballroom D

• AAI-2236A: Using the New Java Concurrency Utilities with IBM WebSphere• Tuesday, 2-3pm, Mandalay Bay, Reef Ballroom D

• AAI-2235A: OpenJPA and EclipseLink Usage Scenarios Explained• Wednesday, 5:30-6:30pm, Mandalay Bay, Surf Ballroom A

• AAI-1610A: Configuring IBM WebSphere Application Server for EnterpriseMessaging Needs• Wednesday, 5:30-6:30pm, Mandalay Bay, Surf Ballroom E

• AAI-3085A: Don’t Wait! Develop Responsive Applications with Java EE7 Instead• Thursday, 10:30-11:30am, Mandalay Bay, Lagoon L

27

Page 29: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Questions?

28

Page 30: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Notices and DisclaimersCopyright © 2015 by International Business Machines Corporation (IBM). No part of this document may be reproduced ortransmitted in any form without written permission from IBM.

U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract withIBM.

Information in these presentations (including information relating to products that have not yet been announced by IBM) has beenreviewed for accuracy as of the date of initial publication and could include unintentional technical or typographical errors. IBMshall have no responsibility to update this information. THIS DOCUMENT IS DISTRIBUTED "AS IS" WITHOUT ANY WARRANTY,EITHER EXPRESS OR IMPLIED. IN NO EVENT SHALL IBM BE LIABLE FOR ANY DAMAGE ARISING FROM THE USE OFTHIS INFORMATION, INCLUDING BUT NOT LIMITED TO, LOSS OF DATA, BUSINESS INTERRUPTION, LOSS OF PROFITOR LOSS OF OPPORTUNITY. IBM products and services are warranted according to the terms and conditions of theagreements under which they are provided.

Any statements regarding IBM's future direction, intent or product plans are subject to change or withdrawal withoutnotice.

Performance data contained herein was generally obtained in a controlled, isolated environments. Customer examples arepresented as illustrations of how those customers have used IBM products and the results they may have achieved. Actualperformance, cost, savings or other results in other operating environments may vary.

References in this document to IBM products, programs, or services does not imply that IBM intends to make such products,programs or services available in all countries in which IBM operates or does business.

Workshops, sessions and associated materials may have been prepared by independent session speakers, and do notnecessarily reflect the views of IBM. All materials and discussions are provided for informational purposes only, and are neitherintended to, nor shall constitute legal or other guidance or advice to any individual participant or their specific situation.

It is the customer’s responsibility to insure its own compliance with legal requirements and to obtain advice of competent legalcounsel as to the identification and interpretation of any relevant laws and regulatory requirements that may affect the customer’sbusiness and any actions the customer may need to take to comply with such laws. IBM does not provide legal advice orrepresent or warrant that its services or products will ensure that the customer is in compliance with any law.

Page 31: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Notices and Disclaimers (con’t)

Information concerning non-IBM products was obtained from the suppliers of those products, their publishedannouncements or other publicly available sources. IBM has not tested those products in connection with thispublication and cannot confirm the accuracy of performance, compatibility or any other claims related to non-IBMproducts. Questions on the capabilities of non-IBM products should be addressed to the suppliers of those products.IBM does not warrant the quality of any third-party products, or the ability of any such third-party products tointeroperate with IBM’s products. IBM EXPRESSLY DISCLAIMS ALL WARRANTIES, EXPRESSED OR IMPLIED,INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR APARTICULAR PURPOSE.

The provision of the information contained herein is not intended to, and does not, grant any right or license under anyIBM patents, copyrights, trademarks or other intellectual property right.

• IBM, the IBM logo, ibm.com, Bluemix, Blueworks Live, CICS, Clearcase, DOORS®, Enterprise DocumentManagement System™, Global Business Services ®, Global Technology Services ®, Information on Demand,ILOG, Maximo®, MQIntegrator®, MQSeries®, Netcool®, OMEGAMON, OpenPower, PureAnalytics™,PureApplication®, pureCluster™, PureCoverage®, PureData®, PureExperience®, PureFlex®, pureQuery®,pureScale®, PureSystems®, QRadar®, Rational®, Rhapsody®, SoDA, SPSS, StoredIQ, Tivoli®, Trusteer®,urban{code}®, Watson, WebSphere®, Worklight®, X-Force® and System z® Z/OS, are trademarks ofInternational Business Machines Corporation, registered in many jurisdictions worldwide. Other product andservice names might be trademarks of IBM or other companies. A current list of IBM trademarks is available onthe Web at "Copyright and trademark information" at: www.ibm.com/legal/copytrade.shtml.

Page 32: AAI-2236 Using the new Java Concurrency Utilities with IBM WebSphere

Thank YouYour Feedback is

Important!

Access the InterConnect 2015Conference CONNECT AttendeePortal to complete your sessionsurveys from your smartphone,

laptop or conference kiosk.