This document discusses running long-running tasks asynchronously in background threads in Java and WebObjects. It covers:
- Using Runnable and Callable interfaces to define asynchronous tasks
- Executing tasks using the ExecutorService interface and submitting tasks to get Future objects
- The ERXExecutorService class, which provides a thread-safe ExecutorService for WebObjects
- Monitoring and controlling tasks using interfaces like ERXStatusInterface
- Passing EOF objects between threads safely using global IDs
- Customizing the results page using IERXPerformWOActionForResult
Java Concurrency, Memory Model, and TrendsCarol McDonald
This document discusses concurrency in Java. It covers benefits and risks of threads, goals of concurrency utilities in Java, examples of executor services and thread pools, and best practices for thread safety including using immutable objects, atomic variables, and concurrent collections.
This document discusses various programming paradigms and concurrency concepts in Java. It covers single and multi-process programming, multi-threading, processes, threads, synchronization, deadlocks, and strategies for designing objects to be thread-safe such as immutability, locking, and containment. It also summarizes high-level concurrency utilities in Java like locks, executors, concurrent collections, and atomic variables.
The document discusses threads and concurrency in iOS development. It begins by introducing threads and their downsides, such as overhead and difficulty of management. It then introduces Grand Central Dispatch (GCD) and blocks as higher-level solutions for concurrency. GCD automates thread management and uses blocks to encapsulate units of work. The document also discusses using NSThread as a last resort for scenarios where GCD is not sufficient.
Java has a solid Memory Model, and there are a couple of excellent libraries for concurrency. When you start working with threads however, pitfalls start appearing - especially if the program is supposed to be fast and correct. This session shows proven solutions for some typical problems, showing how to view program code from a concurrency perspective: Which threads share which data, and how? How to reduce the impact of locks? How to avoid them altogether - and when is that worth it?
This document discusses concurrency utilities introduced in Java 8 including parallel tasks, parallel streams, parallel array operations, CompletableFuture, ConcurrentHashMap, scalable updatable variables, and StampedLock. It provides examples and discusses when and how to properly use these utilities as well as potential performance issues. Resources for further reading on Java concurrency are also listed.
This document provides an overview of several Android development topics, including the Simple framework for serializing XML into Java objects, the Android process and thread model, AsyncTask for asynchronous operations, the Volley networking framework, and debugging using Eclipse. It describes the core components and best practices for each topic at a high level.
The document discusses the benefits of exercise for mental health. Regular physical activity can help reduce anxiety and depression and improve mood and cognitive functioning. Exercise causes chemical changes in the brain that may help boost feelings of calmness, happiness and focus.
The document discusses threads, which allow for multiple paths of execution within an application. All user interface updates must occur on the main thread. While performing background tasks, one can use timers, performSelector methods, or manual NSThreads to ensure the main thread remains responsive for UI updates. JSON provides a simple format for communicating data between client and server applications on iPhone, and the SBJSON framework can be used to parse JSON strings into Objective-C objects.
Java Concurrency, Memory Model, and TrendsCarol McDonald
This document discusses concurrency in Java. It covers benefits and risks of threads, goals of concurrency utilities in Java, examples of executor services and thread pools, and best practices for thread safety including using immutable objects, atomic variables, and concurrent collections.
This document discusses various programming paradigms and concurrency concepts in Java. It covers single and multi-process programming, multi-threading, processes, threads, synchronization, deadlocks, and strategies for designing objects to be thread-safe such as immutability, locking, and containment. It also summarizes high-level concurrency utilities in Java like locks, executors, concurrent collections, and atomic variables.
The document discusses threads and concurrency in iOS development. It begins by introducing threads and their downsides, such as overhead and difficulty of management. It then introduces Grand Central Dispatch (GCD) and blocks as higher-level solutions for concurrency. GCD automates thread management and uses blocks to encapsulate units of work. The document also discusses using NSThread as a last resort for scenarios where GCD is not sufficient.
Java has a solid Memory Model, and there are a couple of excellent libraries for concurrency. When you start working with threads however, pitfalls start appearing - especially if the program is supposed to be fast and correct. This session shows proven solutions for some typical problems, showing how to view program code from a concurrency perspective: Which threads share which data, and how? How to reduce the impact of locks? How to avoid them altogether - and when is that worth it?
This document discusses concurrency utilities introduced in Java 8 including parallel tasks, parallel streams, parallel array operations, CompletableFuture, ConcurrentHashMap, scalable updatable variables, and StampedLock. It provides examples and discusses when and how to properly use these utilities as well as potential performance issues. Resources for further reading on Java concurrency are also listed.
This document provides an overview of several Android development topics, including the Simple framework for serializing XML into Java objects, the Android process and thread model, AsyncTask for asynchronous operations, the Volley networking framework, and debugging using Eclipse. It describes the core components and best practices for each topic at a high level.
The document discusses the benefits of exercise for mental health. Regular physical activity can help reduce anxiety and depression and improve mood and cognitive functioning. Exercise causes chemical changes in the brain that may help boost feelings of calmness, happiness and focus.
The document discusses threads, which allow for multiple paths of execution within an application. All user interface updates must occur on the main thread. While performing background tasks, one can use timers, performSelector methods, or manual NSThreads to ensure the main thread remains responsive for UI updates. JSON provides a simple format for communicating data between client and server applications on iPhone, and the SBJSON framework can be used to parse JSON strings into Objective-C objects.
Presentation describes basic concepts of thread pool such as:
- interacting with queues,
- using pools from Executors class,
- task rejecting
- using ThreadFactory for thread creating
- Future and Callable interfaces,
- basic API
- possibilities for extending
This 50 minutes talk covers the novelties of Java EE 7 (easier to understand if you already know Java EE 6). It comes from the talk I gave with Arun Gupta at JavaOne 2013
How to build to do app using vue composition api and vuex 4 with typescriptKaty Slemon
In this tutorial, we will build a to-do app using Vue Composition API & Vuex 4 with Typescript. We will learn and explore Composition API & Options API as well
The document provides an overview of new concepts and features in Java EE 6, including profiles like Web Profile 1.0 that define subsets of the platform, new specifications like Managed Beans 1.0 and Interceptors 1.1, and updates to existing specifications such as EJB 3.1, JPA 2.0, Servlet 3.0, and JSF 2.0. It discusses concepts like pruning of specifications, portable JNDI names, embeddable containers, and the move of Facelets as the preferred view definition language for JSF.
Concurrent Programming in Java discusses various approaches to concurrency in Java including threads, executors, fork/join, parallel streams, CompletableFuture, and RXJava. It explains challenges with threads like interference, deadlocks, and performance overhead. It then covers enhancements in Java 5+ including executors and concurrent collections. Later sections discuss functional-style concurrency with CompletableFuture and RXJava, which allow composing asynchronous operations without blocking.
The document discusses parallel programming in .NET. It covers two main strategies for parallelism - data parallelism and task parallelism. For data parallelism, it describes using Parallel.For to partition work over collections. For task parallelism, it discusses using the Task Parallel Library to create and run independent tasks concurrently, allowing work to be distributed across multiple processors. It provides examples of creating tasks implicitly with Parallel.Invoke and explicitly by instantiating Task objects and passing delegates.
This document summarizes key concepts related to dependency injection (DI) and the Java Contexts and Dependency Injection (CDI) specification, including:
1. DI allows injecting dependencies into components rather than having components directly instantiate or look up dependencies, improving loose coupling.
2. CDI builds on DI and allows injecting not just dependencies but any object into Java components using the @Inject annotation without requiring XML configuration.
3. Qualifiers like @Named allow disambiguating between multiple implementations of a service when injecting dependencies.
The document discusses efficient threading techniques on Android. It begins by explaining that the UI thread must be optimized to avoid jank. It then covers various threading approaches including native threads, Java threads, executors, HandlerThreads, AsyncTask, services, IntentServices, AsyncQueryHandler, and loaders. Each technique has advantages for different use cases such as one-shot tasks, concurrent execution, sequential execution, task management, and asynchronous data operations. The goal is to understand which technique to use for background thread execution based on the specific needs of the task.
The document discusses Android threading and how to handle long running tasks to avoid blocking the UI thread. It covers the main UI thread, how to run tasks on a background thread using Thread and Runnable, and how to update the UI from the background thread using runOnUiThread(), post(), postDelayed() and AsyncTask. AsyncTask is recommended as it handles threading for you by running background tasks on a worker thread and calling publishProgress() to update the UI on the main thread.
introduction, The Resolution of Property Names on Objects.
Closure
A "closure" is an expression (typically a function) that can have
free variables together with an environment that binds those
variables (that "closes" the expression)
The document discusses CompletableFuture in Java. It begins with an introduction to java.util.Future and its limitations. It then discusses how CompletableFuture allows asynchronous and parallel operations through callbacks and chaining of tasks. This improves performance over serial execution. It provides examples of CompletableFuture methods like supplyAsync, thenApply, thenCombine, and allOf. Finally, it discusses how CompletableFuture can be used to build powerful and scalable libraries.
This document discusses how Scala, Akka, and Docker help OT achieve its goals of building scalable applications. It describes OT's objectives, an introduction to Scala and why it is used, how Akka and Docker enable concurrency, distribution, and easy deployment. The technologies help with scaling applications, testing components, and achieving OT's vision of being the best secure technology company.
Java EE 7 Batch processing in the Real WorldRoberto Cortez
This talk will explore one of the newest API for Java EE 7, the JSR 352, Batch Applications for the Java Platform. Batch processing is found in nearly every industry when you need to execute a non-interactive, bulk-oriented and long running operation task. A few examples are: financial transactions, billing, inventory management, report generation and so on. The JSR 352 specifies a common set of requirements that every batch application usually needs like: checkpointing, parallelization, splitting and logging. It also provides you with a job specification language and several interfaces that allow you to implement your business logic and interact with the batch container. We are going to live code a real life example batch application, starting with a simple task and then evolve it using the advanced API's until we have a full parallel and checkpointing reader-processor-writer batch. By the end of the session, attendees should be able to understand the use cases of the JSR 352, when to apply it and how to develop a full Java EE Batch Application.
Basic Introduction to programming functions, Contents include.
- Definition of function
- Structure of function
- Function calling
- Function Prototyping
- Scope of the function
- Input parameters to a function
- Returning from the function
- Types of function calling
Thread allows running code on a background thread but cannot directly update the UI. Handler allows scheduling messages and runnables to execute on a thread's message queue. AsyncTask simplifies background threading by running background work on a separate thread and publishing results on the UI thread.
The Java component in Mule allows developers to package custom Java code that executes when a message is received. There are two types of Java components in Mule: DefaultJavaComponent and PooledJavaComponent. Java components can be configured using object factories like prototype-object and singleton-object. Entry point resolvers determine which method of the Java component gets invoked when a message is received, and include options like reflection-entry-point-resolver, property-entry-point-resolver, and method-entry-point-resolver. Interceptors can also be added to Java components to provide additional logic before the message is processed.
Spring boot is a suite, pre-configured, pre-sugared set of frameworks/technologies to reduce boilerplate configuration providing you the shortest way to have a Spring web application up and running with smallest line of code/configuration out-of-the-box.
👉 Watch the video: https://www.youtube.com/watch?v=WiQqqB9MlkA 👈
Elegant Solutions for Everyday Python Problems - Pycon 2018
Are you an intermediate python developer looking to level up? Luckily, python provides us with a unique set of tools to make our code more elegant and readable by providing language features that make your code more intuitive and cut down on repetition. In this talk, I’ll share practical pythonic solutions for supercharging your code.
Specifically, I'll cover:
What magic methods are, and show you how to use them in your own code.
When and how to use partial methods.
An explanation of ContextManagers and Decorators, as well as multiple techniques for implementing them.
How to effectively use NamedTuples, and even subclass and extend them!
Lastly, I'll go over some example code that ties many of these techniques together in a cohesive way. You'll leave this talk feeling confident about using these tools and techniques in your next python project!
This document discusses multithreading and concurrency in .NET. It covers key concepts like processes and threads, and how they relate on an operating system level. It also discusses the Thread Pool, Task Parallel Library (TPL), Tasks, Parallel LINQ (PLINQ), and asynchronous programming patterns in .NET like async/await. Examples are provided for common threading techniques like producer/consumer and using the Timer class. Overall it serves as a comprehensive overview of multithreading and concurrency primitives available in the .NET framework.
Async and parallel patterns and application design - TechDays2013 NLArie Leeuwesteijn
TechDays2013 NL session on async and parallel programming. Gives an overview of todays relevant .net technologies, examples and tips and tricks. This session will help you to understand and select and use the right async/parallel technology to use in your .net application. (arie@macaw.nl)
Presentation describes basic concepts of thread pool such as:
- interacting with queues,
- using pools from Executors class,
- task rejecting
- using ThreadFactory for thread creating
- Future and Callable interfaces,
- basic API
- possibilities for extending
This 50 minutes talk covers the novelties of Java EE 7 (easier to understand if you already know Java EE 6). It comes from the talk I gave with Arun Gupta at JavaOne 2013
How to build to do app using vue composition api and vuex 4 with typescriptKaty Slemon
In this tutorial, we will build a to-do app using Vue Composition API & Vuex 4 with Typescript. We will learn and explore Composition API & Options API as well
The document provides an overview of new concepts and features in Java EE 6, including profiles like Web Profile 1.0 that define subsets of the platform, new specifications like Managed Beans 1.0 and Interceptors 1.1, and updates to existing specifications such as EJB 3.1, JPA 2.0, Servlet 3.0, and JSF 2.0. It discusses concepts like pruning of specifications, portable JNDI names, embeddable containers, and the move of Facelets as the preferred view definition language for JSF.
Concurrent Programming in Java discusses various approaches to concurrency in Java including threads, executors, fork/join, parallel streams, CompletableFuture, and RXJava. It explains challenges with threads like interference, deadlocks, and performance overhead. It then covers enhancements in Java 5+ including executors and concurrent collections. Later sections discuss functional-style concurrency with CompletableFuture and RXJava, which allow composing asynchronous operations without blocking.
The document discusses parallel programming in .NET. It covers two main strategies for parallelism - data parallelism and task parallelism. For data parallelism, it describes using Parallel.For to partition work over collections. For task parallelism, it discusses using the Task Parallel Library to create and run independent tasks concurrently, allowing work to be distributed across multiple processors. It provides examples of creating tasks implicitly with Parallel.Invoke and explicitly by instantiating Task objects and passing delegates.
This document summarizes key concepts related to dependency injection (DI) and the Java Contexts and Dependency Injection (CDI) specification, including:
1. DI allows injecting dependencies into components rather than having components directly instantiate or look up dependencies, improving loose coupling.
2. CDI builds on DI and allows injecting not just dependencies but any object into Java components using the @Inject annotation without requiring XML configuration.
3. Qualifiers like @Named allow disambiguating between multiple implementations of a service when injecting dependencies.
The document discusses efficient threading techniques on Android. It begins by explaining that the UI thread must be optimized to avoid jank. It then covers various threading approaches including native threads, Java threads, executors, HandlerThreads, AsyncTask, services, IntentServices, AsyncQueryHandler, and loaders. Each technique has advantages for different use cases such as one-shot tasks, concurrent execution, sequential execution, task management, and asynchronous data operations. The goal is to understand which technique to use for background thread execution based on the specific needs of the task.
The document discusses Android threading and how to handle long running tasks to avoid blocking the UI thread. It covers the main UI thread, how to run tasks on a background thread using Thread and Runnable, and how to update the UI from the background thread using runOnUiThread(), post(), postDelayed() and AsyncTask. AsyncTask is recommended as it handles threading for you by running background tasks on a worker thread and calling publishProgress() to update the UI on the main thread.
introduction, The Resolution of Property Names on Objects.
Closure
A "closure" is an expression (typically a function) that can have
free variables together with an environment that binds those
variables (that "closes" the expression)
The document discusses CompletableFuture in Java. It begins with an introduction to java.util.Future and its limitations. It then discusses how CompletableFuture allows asynchronous and parallel operations through callbacks and chaining of tasks. This improves performance over serial execution. It provides examples of CompletableFuture methods like supplyAsync, thenApply, thenCombine, and allOf. Finally, it discusses how CompletableFuture can be used to build powerful and scalable libraries.
This document discusses how Scala, Akka, and Docker help OT achieve its goals of building scalable applications. It describes OT's objectives, an introduction to Scala and why it is used, how Akka and Docker enable concurrency, distribution, and easy deployment. The technologies help with scaling applications, testing components, and achieving OT's vision of being the best secure technology company.
Java EE 7 Batch processing in the Real WorldRoberto Cortez
This talk will explore one of the newest API for Java EE 7, the JSR 352, Batch Applications for the Java Platform. Batch processing is found in nearly every industry when you need to execute a non-interactive, bulk-oriented and long running operation task. A few examples are: financial transactions, billing, inventory management, report generation and so on. The JSR 352 specifies a common set of requirements that every batch application usually needs like: checkpointing, parallelization, splitting and logging. It also provides you with a job specification language and several interfaces that allow you to implement your business logic and interact with the batch container. We are going to live code a real life example batch application, starting with a simple task and then evolve it using the advanced API's until we have a full parallel and checkpointing reader-processor-writer batch. By the end of the session, attendees should be able to understand the use cases of the JSR 352, when to apply it and how to develop a full Java EE Batch Application.
Basic Introduction to programming functions, Contents include.
- Definition of function
- Structure of function
- Function calling
- Function Prototyping
- Scope of the function
- Input parameters to a function
- Returning from the function
- Types of function calling
Thread allows running code on a background thread but cannot directly update the UI. Handler allows scheduling messages and runnables to execute on a thread's message queue. AsyncTask simplifies background threading by running background work on a separate thread and publishing results on the UI thread.
The Java component in Mule allows developers to package custom Java code that executes when a message is received. There are two types of Java components in Mule: DefaultJavaComponent and PooledJavaComponent. Java components can be configured using object factories like prototype-object and singleton-object. Entry point resolvers determine which method of the Java component gets invoked when a message is received, and include options like reflection-entry-point-resolver, property-entry-point-resolver, and method-entry-point-resolver. Interceptors can also be added to Java components to provide additional logic before the message is processed.
Spring boot is a suite, pre-configured, pre-sugared set of frameworks/technologies to reduce boilerplate configuration providing you the shortest way to have a Spring web application up and running with smallest line of code/configuration out-of-the-box.
👉 Watch the video: https://www.youtube.com/watch?v=WiQqqB9MlkA 👈
Elegant Solutions for Everyday Python Problems - Pycon 2018
Are you an intermediate python developer looking to level up? Luckily, python provides us with a unique set of tools to make our code more elegant and readable by providing language features that make your code more intuitive and cut down on repetition. In this talk, I’ll share practical pythonic solutions for supercharging your code.
Specifically, I'll cover:
What magic methods are, and show you how to use them in your own code.
When and how to use partial methods.
An explanation of ContextManagers and Decorators, as well as multiple techniques for implementing them.
How to effectively use NamedTuples, and even subclass and extend them!
Lastly, I'll go over some example code that ties many of these techniques together in a cohesive way. You'll leave this talk feeling confident about using these tools and techniques in your next python project!
This document discusses multithreading and concurrency in .NET. It covers key concepts like processes and threads, and how they relate on an operating system level. It also discusses the Thread Pool, Task Parallel Library (TPL), Tasks, Parallel LINQ (PLINQ), and asynchronous programming patterns in .NET like async/await. Examples are provided for common threading techniques like producer/consumer and using the Timer class. Overall it serves as a comprehensive overview of multithreading and concurrency primitives available in the .NET framework.
Async and parallel patterns and application design - TechDays2013 NLArie Leeuwesteijn
TechDays2013 NL session on async and parallel programming. Gives an overview of todays relevant .net technologies, examples and tips and tricks. This session will help you to understand and select and use the right async/parallel technology to use in your .net application. (arie@macaw.nl)
Since these presentations were spare time hobby - I've decided to share them :)
Hopefully someone will find them useful.
This part continues 1. part with more design patterns like Command, State, NullObject.
The fork/join framework, which is based on the ForkJoinPool class, is an implementation of the Executor interface. It is designed to efficiently run a large number of tasks using a pool of worker threads. A work-stealing technique is used to keep all the worker threads busy, to take full advantage of multiple processors
This document discusses principles for architecting JavaScript applications to be testable. It recommends:
1. Using interfaces rather than implementations to define behavior and allow for loose coupling and swapping of implementations.
2. Applying design patterns like decorator and abstract factory to handle cross-cutting concerns like logging and profiling separately from the core functionality.
3. Injecting all dependencies through constructor injection to make dependencies explicit and avoid tight coupling.
4. Programming to interfaces to allow for mocking and isolation of units for testing purposes.
Developing enterprise applications today using JavaFX is a challenge. The industry has not matured enough to identify patterns and practices. Consequently practioners (architects and developers alike) commit the same mistakes again and again. There is a complete lack of non-UI frameworks that make JavaFX application development easy and fast. FxObjects attempts to address that gap. The 0.1 version released provides powerful features.
Multi-threading in the modern era: Vertx Akka and QuasarGal Marder
Everybody wants scalable systems. However, writing non-blocking applications in Java is not an easy task. In this session, we'll go over 3 different frameworks for managing multi-treading and concurrency support (Akka, Vertx and Quasar).
The Mayans Lost Guide to RxJava on AndroidFernando Cejas
This document provides an introduction and overview of RxJava. Some key points:
- RxJava is a library for composing asynchronous and event-based programs using observable sequences. It implements Reactive Extensions (ReactiveX) for the Java VM.
- Using RxJava can help address issues with concurrency, callbacks, and composing asynchronous operations in Java. It promotes a reactive style of programming.
- The core abstractions in RxJava are Observables (which emit notifications), Subscribers (which receive notifications), and Operators (which allow transformation and manipulation of observable sequences).
- Examples are provided of how to use RxJava with Clean Architecture, including reactive presenters, use cases that
The document provides an overview of the Play Framework using Scala. It discusses key features of Play including hot reloading, type safety, and predefined modules. It also covers installing Play, the MVC architecture, developing REST APIs, adding dependencies, routing, and configuration. Common commands like sbt run and sbt compile are listed. The document demonstrates creating a part-of-speech tagger using Play and Scala.
Java APIs- The missing manual (concurrency)Hendrik Ebbers
This isn’t a talk about microservices, NoSQL, container solutions or hip new frameworks. This talk will show some of the standard Java APIs that are part of Java since version 5, 6, 7 or 8. All those features are very helpful to create maintainable and future-proof applications, regardless of whether JavaEE, Spring, JavaFX or any other framework is used. The talk will give an overview of some important standard concepts and APIs of Java like annotations, null values and concurrency.
Building Concurrent WebObjects applications with ScalaWO Community
This document discusses using Scala for concurrent programming in WebObjects applications. It begins by explaining why concurrent programming is important due to increasing numbers of processor cores. It then discusses challenges with traditional threading and locks and introduces the actor model as an easier and more scalable approach using message passing. The document demonstrates how to build concurrent WebObjects applications using Scala actors for processing tasks like video encoding. It shows how properties can configure WebObjects for concurrent requests and how ERXEC provides thread safety. Benchmarks show the Scala actor approach outperforms traditional threading. The document argues that Scala is a powerful, safe and easy language for concurrent programming in WebObjects.
Akka provides tools for building concurrent, scalable and fault-tolerant systems using the actor model. The key tools provided by Akka include actors for concurrency, agents for shared state, dispatchers for work distribution, and supervision hierarchies for fault handling. Akka actors simplify concurrency through message passing and isolation, and provide tools for scaling and distributing actors across nodes for increased throughput and fault tolerance.
New abstractions for concurrency make writing programs easier by moving away from threads and locks, but debugging such programs becomes harder. The call-stack, an essential tool in understanding why and how control flow reached a certain point in the program, loses meaning when inspected in traditional debuggers. Futures, actors or iteratees make code easier to write and reason about, and in this talk I'll show a simple solution to make them easier to debug. The tool I present integrates well with the Eclipse plugin for Scala, and shows how a "reactive debugger" might look like.
Aplicações assíncronas no Android com Coroutines & JetpackNelson Glauber Leal
The document discusses asynchronous applications in Android using Coroutines & Jetpack. It introduces coroutines as lightweight threads that make asynchronous programming easier by replacing callbacks with suspending functions. It covers key coroutine concepts like Job, Context, Scope and Dispatcher. It also discusses how coroutines can be used with Lifecycle, ViewModel and WorkManager components in Jetpack to build asynchronous Android applications.
This document discusses Durable Functions, which allow for writing long-running serverless workflows in Azure Functions. It describes how Durable Functions enable orchestrating function chains, fan-out/fan-in patterns, stateful singletons, and human interactions. It also covers key concepts like event sourcing, the durable task framework, and constraints around orchestration code.
This document discusses Express.js, a popular Node.js web application framework. It begins by explaining that Express makes developing websites, web apps, and APIs easier by providing route support and templating engine integration. It then demonstrates how to install Express and a templating engine like Jade. Several code examples are provided, including creating a simple REST API with routes, using Express to serve multiple pages with query parameters, and building a RESTful API for a resource like dogs. Resources for further learning about Express and Node.js are listed at the end.
Similar to Concurrency and Thread-Safe Data Processing in Background Tasks (20)
This document describes KAAccessControl, a framework for managing user access control and permissions. It provides concise summaries in 3 sentences or less that provide the high level and essential information from the document.
The framework allows defining roles, profiles, lists and managing user permissions through annotations and configuration files. It handles authentication but does not provide the authentication mechanism. The framework manages the current user's profile and permissions and allows impersonating other users through its user service class. Components check permissions by annotating allowed roles and querying the framework's access control services.
The document describes an in-memory OLAP engine created by Samuel Pelletier to enable fast querying of multidimensional data with millions of facts. It loads data into memory as plain old Java objects (POJOs) for faster access compared to entity objects or SQL queries. Dimensions are modeled as classes to index the facts and compute summarized results. The engine is multithreaded and designed for simplicity and minimal dependencies.
Using Nagios to monitor your WO systemsWO Community
Nagios is an open source monitoring tool that has been available since 1999. It is commonly used to monitor servers, services, and applications. The document discusses how to install and configure Nagios on various platforms like CentOS, Ubuntu, and Mac OS X. It also provides examples of how to monitor common services like HTTP, MySQL, disk space, and custom applications using Nagios plugins. Graphing and alerting capabilities are discussed as well. The presentation concludes with a demonstration and Q&A section.
This document discusses various tools and techniques for building and deploying software, including Git, Git hooks, Puppet, native packages, and Maven. It provides examples of using post-receive Git hooks to deploy code to servers, configuring Puppet modules to install packages and configure services, creating native packages with tools like fpm and Ant, and bundling deployment scripts within packages.
The document discusses various strategies for achieving high availability of web applications and databases. It covers evaluating business requirements, DNS configuration, using cloud infrastructure or owning hardware, basic setups with application and database servers, database replication and clustering options, load balancing tools for Linux and cloud environments, auto scaling features, and monitoring. The key strategies presented include replicating databases, load balancing web traffic, auto-scaling cloud resources, and configuring failover between redundant application and database servers.
This document discusses enabling SOAP web services using ERJaxWS in WebObjects. It provides examples of how to create a SOAP service from Java classes or a WSDL, call an external SOAP service, handle data mapping and custom types, define web faults, create stateful services, add security, and troubleshoot SOAP services. Resources for further information on JAX-WS, JAXB, and SOAP are also included.
Chaining the Beast - Testing Wonder Applications in the Real WorldWO Community
This document discusses the importance of testing applications in the real world. It covers various types of testing including catching regressions, checking new features, and addressing issues like incorrect data or slow page responses. Specific testing methodologies are mentioned, like verifying models and business logic. The importance of usability testing is also covered, such as checking the appearance and interactivity of applications. Automated testing tools like Selenium are recommended for testing functionality across different browsers. Building invariant test pages can help find faults and browser-specific problems.
The document discusses stateful controllers in Direct To Web (D2W) applications built with WebObjects. It provides background on D2W and how controllers were traditionally implemented using ERDBranchDelegate and NextPageDelegate. Stateful controllers improve upon this by allowing controller classes to be reused across multiple pages while maintaining state between pages. This is done by overriding branchChoicesForContext to programmatically define branch choices and storing necessary objects like the editing context. The document provides examples of how stateful controllers can implement common page flows and interactions through utility methods while keeping code DRY and reusable.
This document discusses deploying WebObjects applications on Windows. It covers setting up the Windows and WebObjects prerequisites, configuring the basic WOStart application launcher and WOSetup, demoing the setup process, and using JavaMonitor and WOTaskD to manage multiple applications across hosts. It also discusses potential issues like debugging WOStart and the WOAdaptor, using IIS or Apache as the web server, and common pitfalls in a Windows deployment. URLs are provided for downloading needed tools and components.
The document discusses WOUnit, a unit testing framework for Wonder. It provides features like mocking the editing context, creating dummy objects to bypass validations, and spying on objects. Sample tests are shown to test validation rules and relationships. WOUnit aims to make testing simple, fast and support Wonder features like editing contexts through assertions and annotations like @Rule, @Dummy and @Spy.
This document discusses alternatives to using WebObjects for developing web applications. It summarizes the key aspects of a stack that could satisfy former WebObjects developers, including:
- Dependency injection frameworks like Spring and Google Guice that allow loose coupling between classes.
- HTML frameworks like Tapestry that are similar to WebObjects in allowing infinitely nestable page components.
- JAX-RS as a REST framework specification implemented by libraries like Jersey that maps HTTP requests to Java methods.
- Migrating from WebObjects by keeping its philosophies but rewriting code from scratch using these new frameworks, with tools to import existing data models and port components like DirectToWeb and DirectToJavaClient.
Apache Cayenne is an open source object-relational mapping framework for Java. It has been an Apache project since 2006 and has over 17 committers and 9 project management committee members. Cayenne provides tools for mapping database schemas to Java objects and vice versa, as well as tools for querying, caching query results, and handling object lifecycles. It aims to simplify working with relational databases for Java developers in a similar way to how Enterprise Objects Framework simplified it for Objective-C developers.
This document provides an overview and demonstrations of advanced Apache Cayenne concepts including:
1. Reusing Cayenne and service code between admin apps and discussing object context management.
2. Lifecycle events can be received via callbacks or listeners, with callbacks used for simple initialization and listeners for more complex workflows.
3. Caching in Cayenne includes object caching of entities by ID and query caching of result lists by generated keys, with local caching at the context level and shared caching at the domain level.
4. Demonstrations of object caching, query caching, and turning off cross-context synchronization, using query caching with expiration policies, and considering optimistic locking for performance.
The document discusses the steps for migrating an existing project to Wonder, including:
1) Moving the codebase to Git version control for branching during the migration process.
2) Preparing the codebase by adding packages, creating custom subclasses for components like the editing context and direct actions, and renaming any enum collisions.
3) Starting the actual wonderization by importing Wonder frameworks and removing duplicate jars.
This document discusses iOS application architecture and REST client implementation. It covers common iOS concepts like MVC, UIKit, table views and their data sources. It also describes a Comet architecture using a REST API and database to retrieve and display product data in a table. The controller implements the table view data source and delegate methods to display the data and handle user interactions like tapping rows.
This document discusses using iOS apps as clients for ERREST servers. It provides an example architecture of an iOS app connecting to an ERREST backend using REST calls. It also includes code snippets showing how to make REST requests using classes like PLRestful and CometAPI that handle the network requests and JSON parsing. The document is intended to explain how to build iOS clients for existing ERREST backends rather than how to code the iOS apps themselves.
This document discusses the "Framework Principal" pattern which allows optimizing resource usage across multiple applications by initializing shared services and configurations in a single starter class. The Framework Principal runs very early and can be used to launch services independently of any application based on configuration properties. It provides examples of how to configure different applications to use the same Framework Principal by specifying different property files and user names for production vs sandbox environments. This allows launching shared services only once across multiple applications rather than separately in each one.
This document discusses filtering data in Direct to Web (D2W) by limiting the visibility of data based on the current user or company. It presents two solutions:
1. Modifying fetch specifications at the editing context level to add relationship qualifiers restricting results to the current company. This works but is low-level.
2. Using query and relationship components in D2W that call business logic to generate the appropriate qualifiers and restricted data sources. This provides a cleaner, more reusable approach compared to the first solution.
The document also discusses enhancing relationship components to support restricting fetch specifications to simplify generating qualifiers across different entities and relationships. In summary, it focuses on programmatically filtering data in D2
The document discusses the WOver, a small mobile robot built using a Raspberry Pi single board computer connected via serial interface to control an Asuro driving module. It provides instructions to connect to its WiFi network and control interface webpage to drive the robot. Details are given on the hardware components used, including the Raspberry Pi, Asuro driving module, and custom operating system on the module to receive motor control commands from the Raspberry Pi. Potential next steps discussed include adding database, games, sensors, power management, camera, and benchmarks.
Localizing your apps for multibyte languagesWO Community
This document discusses considerations for localizing apps to support multibyte languages. It covers setting the encoding in Eclipse, Ant builds, and database connections to UTF-8. It also discusses features of Japanese like reading direction from right to left, lack of word spacing, and the different character sets of kanji, hiragana, katakana and their encodings. The document recommends converting all characters to single byte widths before storing in databases for ease of use and searching.
Taking AI to the Next Level in Manufacturing.pdfssuserfac0301
Read Taking AI to the Next Level in Manufacturing to gain insights on AI adoption in the manufacturing industry, such as:
1. How quickly AI is being implemented in manufacturing.
2. Which barriers stand in the way of AI adoption.
3. How data quality and governance form the backbone of AI.
4. Organizational processes and structures that may inhibit effective AI adoption.
6. Ideas and approaches to help build your organization's AI strategy.
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdfflufftailshop
When it comes to unit testing in the .NET ecosystem, developers have a wide range of options available. Among the most popular choices are NUnit, XUnit, and MSTest. These unit testing frameworks provide essential tools and features to help ensure the quality and reliability of code. However, understanding the differences between these frameworks is crucial for selecting the most suitable one for your projects.
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxSitimaJohn
Ocean Lotus cyber threat actors represent a sophisticated, persistent, and politically motivated group that poses a significant risk to organizations and individuals in the Southeast Asian region. Their continuous evolution and adaptability underscore the need for robust cybersecurity measures and international cooperation to identify and mitigate the threats posed by such advanced persistent threat groups.
This presentation provides valuable insights into effective cost-saving techniques on AWS. Learn how to optimize your AWS resources by rightsizing, increasing elasticity, picking the right storage class, and choosing the best pricing model. Additionally, discover essential governance mechanisms to ensure continuous cost efficiency. Whether you are new to AWS or an experienced user, this presentation provides clear and practical tips to help you reduce your cloud costs and get the most out of your budget.
5th LF Energy Power Grid Model Meet-up SlidesDanBrown980551
5th Power Grid Model Meet-up
It is with great pleasure that we extend to you an invitation to the 5th Power Grid Model Meet-up, scheduled for 6th June 2024. This event will adopt a hybrid format, allowing participants to join us either through an online Mircosoft Teams session or in person at TU/e located at Den Dolech 2, Eindhoven, Netherlands. The meet-up will be hosted by Eindhoven University of Technology (TU/e), a research university specializing in engineering science & technology.
Power Grid Model
The global energy transition is placing new and unprecedented demands on Distribution System Operators (DSOs). Alongside upgrades to grid capacity, processes such as digitization, capacity optimization, and congestion management are becoming vital for delivering reliable services.
Power Grid Model is an open source project from Linux Foundation Energy and provides a calculation engine that is increasingly essential for DSOs. It offers a standards-based foundation enabling real-time power systems analysis, simulations of electrical power grids, and sophisticated what-if analysis. In addition, it enables in-depth studies and analysis of the electrical power grid’s behavior and performance. This comprehensive model incorporates essential factors such as power generation capacity, electrical losses, voltage levels, power flows, and system stability.
Power Grid Model is currently being applied in a wide variety of use cases, including grid planning, expansion, reliability, and congestion studies. It can also help in analyzing the impact of renewable energy integration, assessing the effects of disturbances or faults, and developing strategies for grid control and optimization.
What to expect
For the upcoming meetup we are organizing, we have an exciting lineup of activities planned:
-Insightful presentations covering two practical applications of the Power Grid Model.
-An update on the latest advancements in Power Grid -Model technology during the first and second quarters of 2024.
-An interactive brainstorming session to discuss and propose new feature requests.
-An opportunity to connect with fellow Power Grid Model enthusiasts and users.
Main news related to the CCS TSI 2023 (2023/1695)Jakub Marek
An English 🇬🇧 translation of a presentation to the speech I gave about the main changes brought by CCS TSI 2023 at the biggest Czech conference on Communications and signalling systems on Railways, which was held in Clarion Hotel Olomouc from 7th to 9th November 2023 (konferenceszt.cz). Attended by around 500 participants and 200 on-line followers.
The original Czech 🇨🇿 version of the presentation can be found here: https://www.slideshare.net/slideshow/hlavni-novinky-souvisejici-s-ccs-tsi-2023-2023-1695/269688092 .
The videorecording (in Czech) from the presentation is available here: https://youtu.be/WzjJWm4IyPk?si=SImb06tuXGb30BEH .
GraphRAG for Life Science to increase LLM accuracyTomaz Bratanic
GraphRAG for life science domain, where you retriever information from biomedical knowledge graphs using LLMs to increase the accuracy and performance of generated answers
Programming Foundation Models with DSPy - Meetup SlidesZilliz
Prompting language models is hard, while programming language models is easy. In this talk, I will discuss the state-of-the-art framework DSPy for programming foundation models with its powerful optimizers and runtime constraint system.
Digital Marketing Trends in 2024 | Guide for Staying AheadWask
https://www.wask.co/ebooks/digital-marketing-trends-in-2024
Feeling lost in the digital marketing whirlwind of 2024? Technology is changing, consumer habits are evolving, and staying ahead of the curve feels like a never-ending pursuit. This e-book is your compass. Dive into actionable insights to handle the complexities of modern marketing. From hyper-personalization to the power of user-generated content, learn how to build long-term relationships with your audience and unlock the secrets to success in the ever-shifting digital landscape.
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfMalak Abu Hammad
Discover how MongoDB Atlas and vector search technology can revolutionize your application's search capabilities. This comprehensive presentation covers:
* What is Vector Search?
* Importance and benefits of vector search
* Practical use cases across various industries
* Step-by-step implementation guide
* Live demos with code snippets
* Enhancing LLM capabilities with vector search
* Best practices and optimization strategies
Perfect for developers, AI enthusiasts, and tech leaders. Learn how to leverage MongoDB Atlas to deliver highly relevant, context-aware search results, transforming your data retrieval process. Stay ahead in tech innovation and maximize the potential of your applications.
#MongoDB #VectorSearch #AI #SemanticSearch #TechInnovation #DataScience #LLM #MachineLearning #SearchTechnology
In the rapidly evolving landscape of technologies, XML continues to play a vital role in structuring, storing, and transporting data across diverse systems. The recent advancements in artificial intelligence (AI) present new methodologies for enhancing XML development workflows, introducing efficiency, automation, and intelligent capabilities. This presentation will outline the scope and perspective of utilizing AI in XML development. The potential benefits and the possible pitfalls will be highlighted, providing a balanced view of the subject.
We will explore the capabilities of AI in understanding XML markup languages and autonomously creating structured XML content. Additionally, we will examine the capacity of AI to enrich plain text with appropriate XML markup. Practical examples and methodological guidelines will be provided to elucidate how AI can be effectively prompted to interpret and generate accurate XML markup.
Further emphasis will be placed on the role of AI in developing XSLT, or schemas such as XSD and Schematron. We will address the techniques and strategies adopted to create prompts for generating code, explaining code, or refactoring the code, and the results achieved.
The discussion will extend to how AI can be used to transform XML content. In particular, the focus will be on the use of AI XPath extension functions in XSLT, Schematron, Schematron Quick Fixes, or for XML content refactoring.
The presentation aims to deliver a comprehensive overview of AI usage in XML development, providing attendees with the necessary knowledge to make informed decisions. Whether you’re at the early stages of adopting AI or considering integrating it in advanced XML development, this presentation will cover all levels of expertise.
By highlighting the potential advantages and challenges of integrating AI with XML development tools and languages, the presentation seeks to inspire thoughtful conversation around the future of XML development. We’ll not only delve into the technical aspects of AI-powered XML development but also discuss practical implications and possible future directions.
Building Production Ready Search Pipelines with Spark and MilvusZilliz
Spark is the widely used ETL tool for processing, indexing and ingesting data to serving stack for search. Milvus is the production-ready open-source vector database. In this talk we will show how to use Spark to process unstructured data to extract vector representations, and push the vectors to Milvus vector database for search serving.
Introduction of Cybersecurity with OSS at Code Europe 2024Hiroshi SHIBATA
I develop the Ruby programming language, RubyGems, and Bundler, which are package managers for Ruby. Today, I will introduce how to enhance the security of your application using open-source software (OSS) examples from Ruby and RubyGems.
The first topic is CVE (Common Vulnerabilities and Exposures). I have published CVEs many times. But what exactly is a CVE? I'll provide a basic understanding of CVEs and explain how to detect and handle vulnerabilities in OSS.
Next, let's discuss package managers. Package managers play a critical role in the OSS ecosystem. I'll explain how to manage library dependencies in your application.
I'll share insights into how the Ruby and RubyGems core team works to keep our ecosystem safe. By the end of this talk, you'll have a better understanding of how to safeguard your code.
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Concurrency and Thread-Safe Data Processing in Background Tasks
1. MONTREAL 1/3 JULY 2011
Concurrency and Thread-Safe Data
Processing in Background Tasks
Kieran Kelleher
Green Island Consulting LLC
SmartleadsUSA LLC
SmartMix Technologies LLC
2. Why Background Threads?
• “Background” = Not in the Request-Response thread (WOWorkerThread)
• We can execute long-running logic asynchronously in a background thread.
• An action MAY be always or sometimes too long
• Examples
• importing a mailing list of 50 records versus a list of 100,000 records.
• Generating a report off a selection of 50 EOs versus 100,000 EOs.
• your app interacting with remote web services (connection timeouts, etc.)
• interacting with a merchant payment gateway (Credit Card processing)
• Administration & Bulk Data Processing Operations
3. Objectives
• How to run simple background tasks with the least effort on your behalf.
• Start an asynchronous task
• Use a long response page to start a task, monitor and handle a task result
• with basic user feedback (busy)
• with better user feedback (progress, status)
• How to work with EOF in the context of background threads.
• How to pass arguments and return results (including EOs) from asynchronous tasks.
• How to run a multi-threaded bulk data processing asynchronous task to get more done faster.
• Introduce convenient classes in Wonder that are related to running tasks in background threads.
4. Anatomy of a “Task”
public class SimpleRunnable implements Runnable {
public void run() {
//Do a whole lot of stuff here
}
}
public class SimpleCallable implements Callable<ResultType> {
public ResultType call() {
//Do a whole lot of stuff here
return _someResult;
}
}
5. Executing a Task
• Use java.util.concurrent.*
• Convenient, easy to use.
• In summary: Basic concurrency classes to understand
• Runnable, Callable, ExecutorService, Future
• java.util.concurrent.ExecutorService interface
• executorService.execute( task );
• Future future = executorService.submit( task );
• java.util.concurrent.Future interface
• future.get() or future.get(timeout, timeUnit)
• future.isDone()
6. Executing a Task
// Creating an ExecutorService in plain Java
ExecutorService executorService = Executors.newCachedThreadPool();
// Getting a reference to the WebObjects-friendly singleton ExecutorService
ExecutorService executorService = ERXExecutorService.executorService()
// Starting an asynchronous task (aka run it in another thread)
Runnable task = new MyRunnableTask();
executorService.execute( task );
// Starting an asynchronous task and keeping an eye on it
Future future = executorService.submit( task );
// Starting a task in a WebObjects action
public WOActionResults dispatchBackgroundTask() {
MyTask task = new MyTask();
ERXExecutorService.executorService().execute(task);
return null;
}
8. ERXExecutorService
creates a ERXTaskThreadPoolExecutor returns ERXFutureTask
ERXExecutorService extends ThreadPoolExecutor
implements Future
implements ExecutorService
(utility class)
has a
ERXThreadFactory
implements ThreadFactory
• Usage
creates
• ExecutorService es = ERXExecutorService.executorService();
ERXTaskThread
• es.execute( runnable ); extends Thread
• Future future = es.submit( task );
• You generally don’t need to directly use the stuff to the right :-)
9. Benefits of using ExecutorService instances
returned by ERXExecutorService
• Allows for loosely coupled plain Runnable and Callable tasks.
• No subclassing necessary to get WO integration!
• EC Safety Net: Automatically unlocks all EC’s at the end of task execution (no subclassing needed)
• NOT a reason to ignore locking!
• TODO: ERXThreadStorage “safe” cloning.
• By the way...
• ERXTaskThread subclass of Thread used
• supports use of ERXExecutionStateTransition interface in your task.
10. The “Ideal” Long Response Page?
• Provides feedback to the user
• Simple UI and easy to understand user experience
• Can be reusable and easy (even pleasant) to implement
• ! WOLongResponsePage
• Controls the user by making them wait
• May not be a good idea for very long tasks
13. CCAjaxLongResponsePage
// Basic usage: run a task in long response page and return to the same page
public WOActionResults dispatchBackgroundTaskInLongResponsePage() {
Runnable task = new MyRunnableTask();
CCAjaxLongResponsePage nextPage = pageWithName(CCAjaxLongResponsePage.class);
nextPage.setTask(task);
return nextPage;
}
#####################################################################
# Optional configuration properties
#####################################################################
# A default status message to display if the long running task does not implement ERXStatusInterface
er.coolcomponents.CCAjaxLongResponsePage.defaultStatus=Please wait...
# Stylesheet for CCAjaxLongResponsePage
er.coolcomponents.CCAjaxLongResponsePage.stylesheet.framework = ERCoolComponents
er.coolcomponents.CCAjaxLongResponsePage.stylesheet.filename = CCAjaxLongResponsePage.css
# Useful for developing a custom CSS style-sheet. When set to true, this flag prevents AJAX refresh on all containers
# on the CCAjaxLongResponsePage and keeps the page open indefinitely even after the task has completed.
er.coolcomponents.CCAjaxLongResponsePage.stayOnLongResponsePageIndefinitely = false
# Default refresh interval for CCAjaxLongResponsePage
#er.coolcomponents.CCAjaxLongResponsePage.refreshInterval = 2
#Defines a default controller class, other than the hard-coded default, for handling task errors for the application
er.coolcomponents.CCAjaxLongResponsePage.nextPageForErrorResultControllerClassName=com.myproject.MyErrorController
14. Monitoring & Controlling Tasks
• ERXStatusInterface
• public String status();
• ERXTaskPercentComplete
• public Double percentComplete();
• IERXStoppable
• public void stop();
• Only ONE method in each interface!! :-)
16. EOF Background Tasks
• Good Practices
• Only pass EOGlobalIDs (or raw rows) between threads
• Manual lock/unlock. --- EC lock() / try / finally / unlock()
• Avoid using default EOObjectStoreCoordinator
• Things to remember
• Task constructor code does not run in the task thread.
• Pass in an EO in constructor - convert to EOGlobalID
17. FYI, About the Demo EOModel
(Number Crunching for the sake of it)
ResultItem
ResultItem
TaskInfo ResultItem
ResultItem
Entity ResultItem
ResultItem
Entity
Represents a single Represents result of one loop iteration.
execution of a task 1) Checking if a number if Prime
2) Checking if a Prime is a Factorial Prime
19. How It Works
Originating Page CCAjaxLongResponsePage
Callable nextPage.setTask(..) Callable
IERXPerformWOActionForResult
nextPage.setNextPageForResultController(..) IERXPerformWOActionForResult Result Page
20. IERXPerformWOActionForResult
• Interface
• public WOActionResults performAction();
• public void setResult(Object result);
• Utility Implementation
• ERXNextPageForResultWOAction
• new ERXNextPageForResultWOAction(resultPage, "resultKey");
21. Customize end of task WOActionResults behavior
// Example of action in originating page to return a long response page
public WOActionResults performTaskWithCustomResultController() {
// Create the controller for handling the result and returning the next page after the task is done
IERXPerformWOActionForResult controller = new ERXNextPageForResultWOAction(pageWithName(MyResultPage.class), "resultKeyInPage");
// Create the task
Callable<EOGlobalID> task = new MyCallableTask();
// Create the CCAjaxLongResponsePage instance
CCAjaxLongResponsePage nextPage = pageWithName(CCAjaxLongResponsePage.class);
// Push controller and the task into CCAjaxLongResponsePage
nextPage.setNextPageForResultController(controller);
nextPage.setTask(task);
// Return the CCAjaxLongResponsePage instance
return nextPage;
}
22. Avoiding the default EOObjectStoreCoordinator
in your task
// Using an OSC from a pool of OSC dedicated to background tasks. Pool size configurable.
EOObjectStoreCoordinator osc = ERXTaskObjectStoreCoordinatorPool.objectStoreCoordinator();
EOEditingContext ec = ERXEC.newEditingContext( osc );
ec.lock();
try {
// Do stuff
} finally {
ec.unlock();
}
# Configure the default OSC pool size for background tasks with property
er.extensions.concurrency.ERXTaskObjectStoreCoordinatorPool.maxCoordinators = 4
// Convenience class ERXAbstractTask
// @see ERXAbstractTask#newEditingContext()
public class MyRunnable extends ERXAbstractTask
Just extend ERXAbstractTask and call newEditingContext() !
23. Handling the return object
// If you implement your own IERXPerformWOActionForResult and result is an EOGlobalID
if (_result instanceof EOGlobalID) {
// Create a new EC
EOEditingContext ec = ERXEC.newEditingContext();
// Let's ensure fresh ec since we are likely coming out of a background task
ec.setFetchTimestamp(System.currentTimeMillis());
_result = ec.faultForGlobalID((EOGlobalID) _result, ec);
}
_nextPage.takeValueForKey(_result, _nextPageResultKey);
26. Multi-threaded task notes
• Parent task can delegate batches of work to child tasks
• Concept - many child tasks serviced by finite thread count ExecutorService
• Use EOGlobalIDs (or raw rows) as parameters to the child tasks.
• DO NOT pass EOs directly to child tasks.
• Fixed thread pool
• static var: pool is shared between all instances of the task (resource conservative)
• instance var: pool is dedicated to each task (careful)
• Take care to correctly size the ERXTaskObjectStoreCoordinatorPool
• er.extensions.concurrency.ERXTaskObjectStoreCoordinatorPool.maxCoordinators = n
• Use Futures to track child task completion. Don’t exit until all child tasks have completed.
27. Working with Fixed Thread Pool ExecutorService
ExecutorService es = ERXExecutorService.newFiniteThreadPool(4);
boolean isRejected = true;
while ( isRejected ) {
try {
Future<?> future = es.submit(childTask);
} catch (RejectedExecutionException e) {
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
// Handle that
}
}
}
28. Passing Parameters to a Task
private final EOGlobalID _myObjectID
// Example Task Constructor
public MyUpdateTask(MyEntityClass eo) {
if (eo.isNewObject()) {
throw new IllegalArgumentException("MyEntityClass cannot be a new unsaved object");
}
// Grab GID reference before the task is started.
_myObjectID = eo.editingContext().globalIDForObject(eo);
}
29. Problems and Solutions (1/2)
• Memory when Processing Huge Data Sets
• Allocate More Memory
• Force garbage collection (for example if above a % usage)
• Recycle EOEditingContexts periodically (see demo T06xxx.java)
• Large toMany Relationships
• Remove the toMany from the EOModel and use
ERXUnmodeledToManyRelationship
• @see example usage in ‘BackgroundTasks’ demo:
• TaskInfo.resultItems relationship.
30. Problems and Solutions (2/2)
• Prevent bottleneck in default EOObjectStoreCoordinator
• ERXTaskObjectStoreCoordinatorPool.objectStoreCoordinator()
• er.extensions.concurrency.ERXTaskObjectStoreCoordinatorPool.maxCoordinators = n
• Implement IERXRefreshPage interface on result page to prevent stale EO result.
• in refresh() call ERXEOControlUtilities.refreshObject( eo );
• @see demo TaskInfoPage and logic in ERXNextPageForResultController
• Use Fresh Data in your background tasks
• ec.setFetchTimestamp(System.currentTimeMillis());
• ERXEOControlUtilities.refreshObject( eo );
31. More Information
• Demo App: wonder/Examples/Misc/BackgroundTasks
• Java API Docs
• Runnable, Callable, ExecutorService, Future, Executors
• Wonder classes and javadoc
• CCAjaxLongResponsePage
• IERXPerformWOActionForResult / ERXNextPageForResultWOAction, IERXRefreshPage
• ERXStatusInterface, ERXTaskPercentComplete, IERXStoppable
• ERXExecutorService
• ERXAbstractTask, ERXTaskObjectStoreCoordinatorPool
• Effective Java, 2nd Edition by Joshua Bloch, chapter 10
32. MONTREAL 1/3 JULY 2011
Q&A
Concurrency and Thread-Safe Data Processing in Background Tasks
Kieran Kelleher