When to be careful about multithreading in EJBs? - multithreading

I understand that App Server takes care of the threading so the developer should only concentrate on the business logic...
but consider an example. A stateless EJB has a member of type CountManager.
#WebService
#Stateless
public class StatelessEJB {
private CountManager countManager;
...
public void incrementCount() {countManager.incrementCount();}
public int getCount(){return countManager.getCount();}
}
And the CountManager
public class CountManager {
public void increaseCount() {
// read count from database
// increase count
// save the new count in database table.
}
public int getCount() {
// returns the count value from database.
}
}
The developer should think about multi-threading here. If you make CountManager also an EJB, I guess problem won't go away.
What would be the general guideline for developer to watch out for?
Update:
Changed the code. Assume that the methods of EJB are exposed as webservice, so we have no control what order client calls them. Transaction attribute is default. Does this code behave correctly under multi threaded scenario?

The fact that EJB are thread-safe doesn't mean that different methods invocations will give you consistent results.
EJB gives you the certainty that every method in your particular EJB instance will be executed by exactly one thread. This doesn't save you from multiple users accessing different instances of your EJB and inconsistent results dangers.
Your CountManager seems to be a regular Java class which means that you hold a state in Stateless EJB. This is not good and EJB thread-safety won't protect you from anything in such case. Your object can be accessed through multiple EJB instances at the same time.
Between your client's first method invocation StatelessEJB.incrementCount() (which starts a transaction - default TransactionAttribute) and the second client's method invocation StatelessEJB.getCount() (which starts new transaction) many things might happen and the value of the count could be changed.
If you'd change it to be an EJB I don't think you'd be any more safe. If it's a SLSB than it still can't have any state. If the state is not realized as a EJB field variable but a database fetched data, than it's definitely better but still - the transaction is not a real help for you because your WebService client still executes these two methods separately therefore landing in two different transactions.
The simple solution would be to:
use the database (no state in SLSB) which can be synchronized with your EJB transaction,
execute both of these methods within the transaction (like incrementAndGet(-) method for WebService client).
Than you can be fairly sure that the results you get are consistent.

Notice that is not really a problem of synchronization or multi-threading, but of transactional behavior.
The above code, if run inside an EJB, will take care of race conditions by delegating transaction support to the data base. Depending on the isolation level and transactional attributes, the data base can take care of locking the underlying tables to ensure that the information remains consistent, even in the face of concurrent access and/or modifications.

Related

Should I use event design when handling no-idempotent invocation?

I'm working on an air booking project.
The image below shows the domain model we develop so far.
We define a domain service (AirBookService) which encapsulates booking, ticketing and other operations. Our suppliers provides Remote-Procedure-Call api to handle these requests, so we implement the domain service by adding an anti-corruption-layer(we have multiple suppliers).
This solution works fine when dealing with imdenpotent rpc calls such as getting price. However, there are risks when dealing with non-imdenpotent rpc calls.
For example
public class TransactionalReservationHandlingServiceImpl .... {
#Transactional
#Override
public void modifyTraveler(String resId, String tktId, AirTravler traveler) {
AirReservation res = reservationRepository.findBy(resId);
res.modify(tktId, traveler);
airBookService.modify(res, traveler);
reservationRepository.store(res);
}
}
I place airBookService.modify() behind res.modify(), so the rpc call could be avoided if some local domain logic is broken. But what if the rpc call succeeds and local transaction fails? We have a disparity between traveler in our application and that in supplier's application.
Is it worth handling rpc calls and local modification in seperate transactions?
My concern is:
a) It will surely introduce some extra complexity if doing so. like messaging.
b) I don' have much experience in event handling.
c) The failure chances are very low even if we use rpc call in the transaction boundary, mostly caused by concurrency problem and contetion of AirReservation is relatively low in real world.
Below is my event attempt:
#Transactional
#Override
public void modifyTraveler(String resId, String tktId, AirTravler traveler) {
AirReservation res = reservationRepository.findBy(resId);
ModifyTravelerEvent event = airBookService.modify(res, traveler);
handlingEventRepository.store(event);
events.notifyTravelerModified(event);// using messaging
}
#Transactional
#Override
public void modifyTraveler(String eventSequence) {
ModifyTravelerEvent event = handlingEventRepository.of(eventSequence);
AirReservation res = reservationRepository.findBy(resId);
event.handle(res);
reservationRepository.store(res);
handlingEventRepository.store(event );
}
The advantage is local modification is seperated from rpc calls.
But this introduces:
1.Multiple resource management issue(datasource and messaging)
2.I have to create a lot of ad-hoc event for modify traveler, demand ticket and any other AirBookService operations.
I'm in a dilemma, not satisfied with current design but quite hesitate with the new event design.
Any idea is appreciated, thanks in advance.
In your first example you mix your local modification with your remote modification. You worry that if your local modification fails after your remote modification succeeds you cannot roll back your remote modification anymore. So unmixing your two modifcations is definitely the way to go.
The simplest way to do this would be to swap the lines airBookService.modify call and the reservationRepository.store call:
public class TransactionalReservationHandlingServiceImpl .... {
#Transactional
#Override
public void modifyTraveler(String resId, String tktId, AirTravler traveler) {
// local modification
AirReservation res = reservationRepository.findBy(resId);
res.modify(tktId, traveler);
reservationRepository.store(res); // <- remember this should not actually store anything until after the commit
// remote modification
airBookService.modify(res, traveler);
}
}
Since your local modification is transactional it will only commit after a successful remote modification. Any kind of local problems that could have occurred would probably already have occurred. Of course, there is still a minuscule chance that committing the transaction itself fails. Therefore to be truly transactional, you would have to be able to roll back your remote modification. Since, I take it, you are not able to do so, true transactionality is actually impossible. The above construct is therefore the safest possible way in terms of consistency to do a local and remote modifications at the same time, since the chance that the commit of the local modification itself fails is negligible. I say this, because even if you would introduce messaging there is still a similar slight chance that the message itself is not committed after the remote modification.
The above construct however does have one big issue: it would probably hamper performance pretty seriously (you don't want your transactions lingering too long). Messaging is therefore a very reasonable solution to this problem. It also has other advantages, like persistence, auditing and replaying of messages. Your messaging attempt therefore is quite legit in this respect. Your code however does seriously break the single responsibility rule since the messaging itself is mixed with the modification within the same method calls.
If you are concerned with too much boilerplate around messaging you should definitely check out akka.io. Spring JMS and ActiveMQ are also a pretty powerful combination if you are not looking for an entire paradigm shift, but just for a decent messaging solution. Using one of these two technologies I've suggested you can create a powerful framework for your local calls that are paired with remote calls that allows you to avoid a lot of boilerplate.
I hope this helps. Good luck!

Delphi (Indy) Threadsafe classes

Let's say I have some class, TMaster, which asa field includes a TIdTCPServer. Some method of the TMaster class is responsible for the OnExecute event of the TIdTCPServer.
Firstly, is this threadsafe and acceptible? Secondly, let's assume my class has many other private fields (Name, Date, anything...) can the OnExecute event - which is really a method INSIDE the TMaster class, write to these variables safely?
I guess I mean to ask if private fields are threadsafe in this situation?
I am really new to threading and any help will be greatly appreciated!
Thanks,
Adrian!
The way I approach this is not to have the fields used by the events belong to the TidTCPServer
owner, but define a custom TidContext descendant and add the fields to that class.
Then you simply set the ContextClass property on the server class to the type of the of your custom context. This way each Connection/Thread will get its own custom context containing its own private fields, this way there is no issue with concurrent thread access to the same fields.
if you have a list of objects that need to be accessed by the different contexts you have two options.
1) create copies the objects and store them in a private field in for each context instance
This can be done in the OnConnect Event.
2) Protect the objects from concurrent thread access using a synchroniser eg TIdCriticalSection, TMultiReadExclusiveWriteSynchronizer or semaphore,
which method you use depends on each individual situation.
if you need to manipulate any vcl components remember this can't safely be done outside the main vcl thread therefore you should create your own tidnotify decendants for this. performing this sort of operation using tidsynch can lead to deadlocks when stoping the tidtcpserver if it is in the middle of a vclsynch operation.
this is just some of what I have learned over the course of a few years using Indy.
TIdTCPServer is a multi-threaded component. No matter what you wrap it in, the OnExecute event will always be triggered in the context of worker threads, one for each connected client, so any code you put inside the handler must be thread-safe. Members of the TMaster class need adequate protection from concurrent access by multiple threads at the same time.

How to handle serialization when using a worker thread from wicket?

In our wicket application I need to start a long-running operation. It will communicate with an external device and provide a result after some time (up to a few minutes).
Java-wise the long running operation is started by a method where I can provide a callback.
public interface LegacyThingy {
void startLegacyWork(WorkFinished callback);
}
public interface WorkFinished {
public void success(Whatever ...);
// failure never happens
}
On my Wicket Page I plan to add an Ajax Button to invoke startLegacyWork(...) providing an appropriate callback. For the result I'd display a panel that polls for the result using an AbstractTimerBehavior.
What boggles my mind is the following problem:
To keep state Wicket serializes the component tree along with the data, thus the data needs to be wrapped in serializable models (or detachable models).
So to keep the "connection" between the result panel and the WorkFinished callback I'd need some way to create a link between the "we serialize everything" world of Wicket and the "Hey I'm a Java Object and nobody manages my lifetime" world of the legacy interface.
Of course I could store ongoing operations in a kind of global map and use a Wicket detachable model that looks them up by id ... but that feels dirty and I don't assume that's the correct way. (It opens up a whole can of worms regarding lifetime of such things).
Or I'm looking at a completly wrong angle on how to do long running operations from wicket?
I think the approach with the global map is good. Wicket also uses something similar internally - org.apache.wicket.protocol.http.StoredResponsesMap. This is a special map that keeps the generated responses for REDIRECT_TO_BUFFER strategy. It has the logic to keep the entries for at most some pre-configured duration and also can have upper limit of entries.

struts action singleton

Why is the struts action class is singleton ?
Actually I am getting point that it is multithreaded. but at time when thousand of request hitting same action, and we put synchronized for preventing threading issue, then it not give good performance bcoz thread going in wait state and it take time to proced.
Is that any way to remove singleton from action class ?
for more info Please visit : http://rameshsengani.in
You are asking about why the Action class is a singleton but I think you also have some issues understanding thread safety so I will try to explain both.
First of all, a Struts Action class is not implemented as a singleton, the framework just uses one instance of it. But because only one instance is used to process all incoming requests, care must be taken not to do something with in the Action class that is not thread safe. But the thing is: by default, Struts Action classes are not thread safe.
Thread safety means that a piece of code or object can be safely used in a multi-threaded environment. An Action class can be safely used in a multi-threaded environment and you can have it used in a thousand threads at the same time with no issues... that is if you implement it correctly.
From the Action class JavaDoc:
Actions must be programmed in a thread-safe manner, because the controller will share the same instance for multiple simultaneous requests. This means you should design with the following items in mind:
Instance and static variables MUST NOT be used to store information related to the state of a particular request. They MAY be used to share global resources across requests for the same action.
Access to other resources (JavaBeans, session variables, etc.) MUST be synchronized if those resources require protection. (Generally, however, resource classes should be designed to provide their own protection where necessary.
You use the Struts Action by deriving it and creating your own. When you do that, you have to take care to respect the rules above. That means something like this is a NO-NO:
public class MyAction extends Action {
private Object someInstanceField;
public ActionForward execute(...) {
// modify someInstanceField here without proper synchronization ->> BAD
}
}
You don't need to synchronize Action classes unless you did something wrong with them like in the code above. The thing is that the entry point of execution into your action is the execute method.
This method receives all it needs as parameters. You can have a thousand threads executed at the same time in the execute method with no issues because each thread has its own execution stack for the method call but not for data that is in the heap (like someInstanceField) which is shared between all threads.
Without proper synchronization when modifying someInstanceField all threads will do as they please with it.
So yes, Struts 1 Action classes are not thread safe but this is in the sense that you can't safely store state in them (i.e.make them statefulf) or if you do it must be properly synchronized.
But if you keep your Action class implementation stateless you are OK, no synchronization needed and threads don't wait for one another.
Why is the struts action class is singleton ?
It's by design. Again the JavaDoc explains it:
An Action is an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request
The request parameters are tied to the web tier and you don't want to send that type of data into your business logic classes because that will create a tight coupling
between the two layers which will then make it impossible to easily reuse your business layer.
Because transforming web objects into model objects (and I don't mean the ActionForm beans here) should be the main purpose of Action classes, they don't need to maintain any state (and shoudn't) and also, there is no reason to have more instances of these guys, all doing the same thing. Just one will do.
If you want you can safely maintain state in your model by persisting info to a database for example, or you can maintain web state by using the http session. It is wrong to maintain state in the Action classes as this introduces the need for syncronisation as explained above.
Is there a way to remove singleton from action class?
I guess you could extend Struts and override the default behavior of RequestProcessor.processActionCreate to create yourself an Action per request
but that means adding another layer on top of Struts to change its "normal" behavior. I've already seen stuff like this go bad in a few applications so I would not recommend it.
My suggestion is to keep your Action classes stateless and go for the single instance that is created for it.
If your app is new and you absolutely need statefull Actions, I guess you could go for Struts 2 (they changed the design there and the Action instances are now one per request).
But Struts 2 is very different from Struts 1 so if you app is old it might be difficult to migrate to Struts 2.
Hope this makes it clear now.
This has changed in Struts2 http://struts.apache.org/release/2.1.x/docs/comparing-struts-1-and-2.html
*Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues. (In practice, servlet containers generate many throw-away objects per request, and one more object does not impose a performance penalty or impact garbage collection.) *
I don't know much about struts, but it appears that this changed in Struts 2, so perhaps you should switch to Struts 2?

How do you create a non-Thread-based Guice custom Scope?

It seems that all Guice's out-of-the-box Scope implementations are inherently Thread-based (or ignore Threads entirely):
Scopes.SINGLETON and Scopes.NO_SCOPE ignore Threads and are the edge cases: global scope and no scope.
ServletScopes.REQUEST and ServletScopes.SESSION ultimately depend on retrieving scoped objects from a ThreadLocal<Context>. The retrieved Context holds a reference to the HttpServletRequest that holds a reference to the scoped objects stored as named attributes (where name is derived from com.google.inject.Key).
Class SimpleScope from the custom scope Guice wiki also provides a per-Thread implementation using a ThreadLocal<Map<Key<?>, Object>> member variable.
With that preamble, my question is this: how does one go about creating a non-Thread-based Scope? It seems that something that I can use to look up a Map<Key<?>, Object> is missing, as the only things passed in to Scope.scope() are a Key<T> and a Provider<T>.
Thanks in advance for your time.
It's a bit unclear what you want - you don't want scopes that are based on threads, and you don't want scopes that ignore threads.
But yes, scopes are intended to manage the lifecycle of an object and say when an instance should be reused. So really you're asking "what are the other possibilities for re-using an instance beyond 'always use the same instance', 'never use the same instance', and 'use an instance depending on the execution environment of the current thread'?"
Here's what comes to mind:
Use the same instance for a fixed amount of time. The example here would be of a configuration file that's reloaded and reparsed every ten minutes.
Perform some network call to query whether a given object should be re-used (maybe it's a fast call to determine whether we need to reconstruct the object, but the call for reconstructing the object is slow)
Re-use the same object until some outside call comes in telling us to reload
Re-use the same object per thread, but not with a scope that's explicitly entered and left like the servlet scopes. (So one instance per thread)
A "this thread and child threads" scope that is based on an InheritableThreadLocal, not a plain ThreadLocal.
Related to that, a Scope and a threadpool-based ExecutorService that work togehter so that instances are shared between a thread and jobs it submits for background execution.
Pull instances out of a pool; this is tricky, since we'd need a good way to return objects to the pool when finished. (Maybe you could combine this idea with something like the request scope, so that objects can be returned to the pool when the request ends)
A scope that composes two or more other scopes, so for example we could get a configuration object that is re-read every 10 minutes except that the same instance is used through the lifetime of a given request.

Resources