Adam Bien's Weblog
Legally Starting Threads/Synchronizing EJBs - Hell Or Heaven
EJB spec does not allow starting and managing threads ...in general. With @Singleton you can do whatever you want even:
With Bean Managed Concurrency demarcation, the container allows full concurrent access to the Singleton bean instance. It is the responsibility of the bean developer to guard its state as necessary against synchronization errors due to concurrent access. The bean developer is permitted to use the Java language level synchronization primitives such as synchronized and volatile for this purpose. [EJB 3.1 spec, page 111]You only need to apply an additional annotation on a @Singleton and do whatever you want - at least synchronization-wise:
@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class InefficientHelloWorld {
//AtomicInteger would be a lot better.
private static volatile int counter = 0;
//synchronized just for demo purposes, o.k with CMT.Bean.
public synchronized void sayHello(){
new Thread(new Runnable() { //still not allowed - but it works
public void run() {
//out.println is not a best practice either...
System.out.println("Hello World: " + counter++);
}
}).start();
}
}
In the majority of all cases it is better to use just @Stateless beans and just let the container manage threads and synchronization for you. @Asynchronous is far better and easier to use , than the example above.
The "working" example was pushed into http://kenai.com/projects/javaee-patterns/. The name of the project is "BeanManagedConcurrency". Starting and managing threads in the application code is hard to implement, monitor and debug - it is by no means a best practice. [See Lightweight Asynchronous Facade pattern, page 65 in "Real World Java EE Patterns Rethinking Best Practices" book for more in-depth discussion]
Posted at 12:07PM Mar 15, 2010 by Adam Bien in Real World Java EE Patterns - Rethinking Best Practices | Kommentare[11]
[my tweets]
Rss My book: Real World Java EE - Rethinking Best Practices
Modules, Cycles, Unwanted Friends - The Modularity Challenges In Enterprise Projects
Building modules and components is not that hard. You "only" have to encapsulate the internal component implementation and expose a clean and easy to use interface. ...at least on paper. In practice you will be confronted with the following challenges in the early iterations:
- The external interface is too coarse and far less interesting for internal reuse, than you had thought.
- The interesting things are residing inside the component. They are, however, well encapsulated and not accessible from the outside.
customermgmt and address / geo-location service. The module customermgmt exposes CRUD services and the address component extensive search capabilities. So far the world is perfect. Now: a customer has an address - how to model that? The external, customer contract will have to reference the address somehow. That is often modeled as a direct relation between DTOs (just a getter). The external view of the customer component is now dependent on the address component. The implementation is still independent. The relation between the customer and the address has to be persisted somehow. And now the trouble starts. Now the implementation of the customer component is dependent on the address component - because of direct (JPA) link between both modules. Now the internal implementation *and* the component contract are dependent on each other. You are using JPA 1.0 - and your database experts just don't want to introduce an additional mapping table between the customer and the address. So you have to model a bi-directional relation between the customer entity and the address (introducing a back-link with a mappedBy attribute). Now you get a bidirectional dependency between the implementation of your component - the external dependency of the customer can remain unidirectionally dependent on the address. This is only true if you are using DTOs. So you get two components which should be independent of each others, but are actually tightly coupled. Your modules have to expose everything - if you are using Java EE 6 - the DTOs and JPA-entities are dependent of each other - probably only the very thin boundary may remain independent. In practice you will get e.g. an
invoice module in addition, which will be dependent on both the customer and the address....
You can do the following to "improve" the situation:
- Factor out all entities into a common package. Often called "domain", "model" or even "common". Such a common package is not cohesive (it contains multiple business concepts) and also not very good to maintain (the generic names have nothing to do with the actual business). This approach looks great ...on paper.
- Drop JPA-relations and introduce proxy-objects, which contain the ID and can be resolved on demand. This will significantly increase the amount of code and will hit your performance. You will be not able to use joins...
- Allow bidirectional friend-dependencies between modules. In that case it will be hard to introduce a framework like OSGi, jigsaw or something else. But you can still put all "business components" into few modules. Then the real benefit of OSGi, Jigsaw etc is questionable.
- Remove OR-mappers and go with "plain" JDBC. Let the DB handle the dependencies for you. In most cases this is not really a maintainable option.
So, you shouldn't kill any OSGi project - you should implement some typical use cases (PoCs) with modularity solution of your choice before the project really starts. This is actually independent of any framework like OSGi, jigsaw or EMS (esoteric module system) :-).
[See also "Real World Java EE Patterns, Rethinking Best Practices" book, Page 267, (Monolithic or Loosely Coupled?) for more in-depth discussion]
Posted at 11:32AM Mar 11, 2010 by Adam Bien in Real World Java EE Patterns - Rethinking Best Practices | Kommentare[4]
[my tweets]
Rss My book: Real World Java EE - Rethinking Best Practices
How To Kill An OSGi Project - With 10 Questions
OSGi focusses on modularity and it is right now (future may change it) the only viable way to split your application into modules with well-defined dependencies. It solves, however, "only" the technical problem - which is actually relatively easy. Before you going to introduce OSGi into your project, answer the following questions:
- What is your versioning scheme for modules(bundles)? Do you care about minor versions, major versions etc?
- Whats your scm strategy - do you plan to open and maintain a branch for every version of a module? How many branches do you plan to maintain? (with svn? :-))
- How many versioned modules will be active at the same time in production?
- How the system is going to be tested? Each module and all the combination of modules. Every version will increase the complexity significantly.
- What is your release-management strategy? Do you really plan to provide customer-specific module combinations? What is your bug-fixing / patch strategy (trunk, branch)?
- Do you really want to replace modules in running system? If it is a serverside system - what happens with in-flight transactions?
- If it is an Eclipse-RCP application - are you even allowed to expose the plugins to the end-user? (in the majority of my projects, we had to disable the update manager in production :-))
- What is your software distribution system - many companies have already a software-distribution system in place. Often not only the application, but also the JVM are packaged into one binary file and entirely installed. Incremental updates are often impossible.
- What is exactly the contract between the modules? Only a Java-Interface? If so - what to do with direct relations between JPA-entities. If you disallow direct JPA-relations - you will probably see a huge "domain" package with all domain objects inside it. You will need to provide "friend" relations between modules as well.
- Is maven the canonical representation of modules, OSGi, or both? A single representation would be the best. Will maven module versions be reflected in the OSGi bundle versions?
[See also "Real World Java EE Patterns, Rethinking Best Practices" book, Page 253, (Premature Encapsulation Is the Root of All Evil) for more in-depth discussion]
Posted at 10:28AM Mar 08, 2010 by Adam Bien in Real World Java EE Patterns - Rethinking Best Practices | Kommentare[12]
[my tweets]
Rss My book: Real World Java EE - Rethinking Best Practices
Jigsaw / JDK 1.7 will be the solution for 80% of the modularization challenges
Jigsaw will come with JDK 1.7 and is now part of the openjdk project and so opensource. Other JDK implementations could simply reuse it.It will become interesting, because:
- It will be shipped with every Oracle / Sun JDK 1.7 (at least it was the plan)
- Jigsaw will partition JDK 1.7 and will be loaded before most of the rt.jar code. So is already there - no reason to introduce another framework
- Its pragmatic: you can split packages across modules. Package splitting isn't a best practice, but makes the incremental modularization of legacy projects a lot easier
- Modules are loaded statically - no reloading. This is good enough for the most projects. Its funny - but in most NetBeans RCP / Eclipse RCP projects we had to deactivate the ability to load modules dynamically in production :-). Server operators don't like dynamic behavior either.
- It seems like there will be only one classloader, which will load all modules. This will eliminate majority of NoClassDefFoundErrors.
- javac will be jigsaw aware - this is a major advantage. Module dependencies should be checked as early as possible - it fits well with the nature of Java.
- Jigsaw should increase the classloading performance and significantly reduce the size of the jars and so the deployment
Posted at 11:00AM Feb 26, 2010 by Adam Bien in Real World Java EE Patterns - Rethinking Best Practices | Kommentare[26]
[my tweets]
Rss My book: Real World Java EE - Rethinking Best Practices
Spring vs. Vanilla Java EE, Real World Java EE Workshop and The Perfect Storm
Next week will be all about Java EE 6. At the ejug conference in Vienna I will start (23.02) with a "fight" against Juergen Hoeller and discuss the Spring vs. Java EE thing. We did it already last year - but now Java EE 6 is out with an API designed by SpringSource. I will also give a dedicated Java EE 6 / EJB 3.1 / CDI / REST / JPA session about Xtreme Lightweight Architectures (you could also call that "weightless" :-)).
The next day (24.02), at the Jax London conference (The Perfect Storm session), I will use more the IDE and "hack" a Java EE 6 application live on stage. I will try to kill some Java patterns with Java FX as well.
The last day (25.02), again in Vienna, I will give a whole day workshop "Real World Java EE (Patterns) - Rethinking Best Practices", somehow related to my latest book. We should have enough time to discuss project specific things and issues. I will try to explain as much as possible with working code...
I'm also already looking forward to the SDC 2010 conference in Gothenborg!
Posted at 09:00AM Feb 19, 2010 by Adam Bien in Real World Java EE Patterns - Rethinking Best Practices | Kommentare[5]
[my tweets]
Rss My book: Real World Java EE - Rethinking Best Practices
Simplest Possible EJB 3.1 Timer
@Singleton
public class TimerService {
@EJB
HelloService helloService;
@Schedule(second="*/1", minute="*",hour="*", persistent=false)
public void doWork(){
System.out.println("timer: " + helloService.sayHello());
}
}
A timer doesn't have to be a singleton - it can be a @Stateless and even a @Stateful bean. The method doWork() will be invoked every second. There is no registration or configuration needed.
How to compile:
You will need the EJB 3.1 API in the classpath, or at least the @Singleton, @Schedule and @EJB annotation.
How to deploy:
Just JAR or WAR the interceptor with an EJB and put the archive into e.g: [glassfishv3]\glassfish\domains\domain1\autodeploy
Btw. the initial deployment of the entire WAR took on my machine:
INFO: Loading application SimpleTimer at /SimpleTimer
INFO: SimpleTimer was successfully deployed in 363 milliseconds.
How to use:
Another service can be easily injected to the timer and so invoked periodically:
@Stateless
public class HelloService {
public String sayHello(){
return "Hello from control: " + System.currentTimeMillis();
}
}
And: there is no XML, strange configuration, libraries, additional dependencies needed...You will find the whole executable project (tested with Netbeans 6.8 and Glassfish v3) in: http://kenai.com/projects/javaee-patterns/ [project name: SimpleTimer].
[See also "Real World Java EE Patterns - Rethinking Best Practices"]
Posted at 10:03AM Feb 09, 2010 by Adam Bien in Real World Java EE Patterns - Rethinking Best Practices | Kommentare[6]
[my tweets]
Rss My book: Real World Java EE - Rethinking Best Practices
kenai.com is dead - long live kenai (under different name)
Even got this email:
"In an effort to get information out to the Kenai community quickly, while trying to manage the integration of our two companies, I think we did a poor job at communicating our plans for Kenai.com to you. I would like to remedy that now. Our strategy is simple. We don't believe it makes sense to continue investing in multiple hosted development sites that are basically doing the same thing. Our plan is to shut down kenai.com and focus our efforts on java.net as the hosted development community. We are in the process of migrating java.net to the kenai technology. This means that any project currently hosted on kenai.com will be able to continue as you are on java.net. We are still working out the technical details, but the goal is to make this migration as seamless as possible for the current kenai.com projects. So in the meantime I suggest that you stay put on kenai.com and let us work through the details and get back to you later this month.
Thanks for your feedback and patience."
These are actually great news. Hopefully all the kenai.com infrastructure like mercurial (subversion isn't fun), jira and hudson will be supported by java.net. So I'm waiting with the migration of "Real World Java EE Patterns" project and will even commit some more content soon. The great story about mercurial: the whole repository with history etc. sits on my machine and can be pushed wherever I want :-). kenai.com is/was an interesting platform - suitable not only for opensource projects.
Posted at 02:07PM Feb 06, 2010 by Adam Bien in Real World Java EE Patterns - Rethinking Best Practices | Kommentare[0]
[my tweets]
Rss My book: Real World Java EE - Rethinking Best Practices
Object Pooling Can Be Still Useful - For Entirely Different Reasons
Pooling was initially introduced as a tuning action for the slow performance of object creation and garbage collection in particular. On a modern JVM > 1.4 pooling is no more needed for the optimization of memory management in a typical business application. It can even have a negative effect on the garbage collector performance. In special cases, like creating millions of instances in every method call, it could still pay off.
Instance pooling, however is still interesting for objects with slow custom "post construction". In some cases you want to inject some dependencies after the object creation, read some configuration etc. This can be slow and doesn't have to be performed over and over again. In such cases object pooling will improve the overall performance.
Instead of prematurely optimize your application, I would rather build the simplest possible thing and measure the performance continuously (e.g. with VisualVM). In most cases you will be surprised where the actual bottlenecks actually are.
Posted at 09:00AM Feb 02, 2010 by Adam Bien in Real World Java EE Patterns - Rethinking Best Practices | Kommentare[2]
[my tweets]
Rss My book: Real World Java EE - Rethinking Best Practices
Do We Need Stateless Session Bean Pooling?
Pooling is still mentioned in the EJB 3.1 / Java EE 6 specification. The question is: do you have to care? The answers are:
- Pooling is not a requirement, it is just an assumption: "...Since stateless session bean instances are typically pooled, the time of the client’s invocation of the create method need not have any direct relationship to the container’s invocation of the PostConstruct/ejbCreate method on the stateless session bean instance..."[EJB 3.1 spec, page 78]
- EJB container can either pool the instances or create a new one for each request
- The most important thing is, that every transaction (often request), gets an independent instance. Then you don't have to care about low level locking mechanisms. This can be achieved with or without (=creating a new instance for each request) pooling.
- Pooling is no more needed in modern JVMs for performance reasons in general. This, however, is highly dependent on the JVM and garbage collector configuration.
- With pools you can throttle the concurrency, because most (all I know) application servers allow you the configuration of max number of instances. You can control the concurrency of every bean type (Boundary) in a fine grained way. This is important for the avoidance of DoS attacks and dealing with legacy resources.
Posted at 11:11AM Jan 15, 2010 by Adam Bien in Real World Java EE Patterns - Rethinking Best Practices | Kommentare[11]
[my tweets]
Rss My book: Real World Java EE - Rethinking Best Practices
What is the difference between pooling and caching?
The difference is simple. Pooling is appropriate if you don't care about the internal state of a particular class / type. Pooling is mainly motivated by technical reasons like performance, latency or memory optimizations.
Caching is all about state. You want to retain the state for performance reasons and store (cache) it in objects between calls. So instead loading the state from the database in every request, you could cache the data between requests in valid objects.
Posted at 11:03AM Jan 11, 2010 by Adam Bien in Real World Java EE Patterns - Rethinking Best Practices | Kommentare[1]
[my tweets]
Rss My book: Real World Java EE - Rethinking Best Practices

