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

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.

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!

What is the Cocoa-way of observing progress of a background task?

Imagine the following situation: you have a background task (the term "task" here means a random computational unit, not an NSTask!), that is implemented using any of the modern technology such as Grand Central Dispatch or Operation Queues. Some controller object on main thread wants to monitor the progress of this background task and report it to a user.
Task progress can have following characteristics:
Be indeterminate or determinate
Because controller object must know when to switch NSProgressIndicator to the appropriate style. We can use a convention that progress is treated as indeterminate until the actual progress value raises from zero.
Progress value itself
A simple float value
Localized description of a current phase
NSString, because communication with user is good
What design suits these requirements at best while being the most Cocoa-ish?
There can be variants.
Delegation
Before firing up the task set your controller object as delegate.
#protocol MyBackgroundTaskDelegate
#required
- (void) progress: (float) value; // 0.0…1.0
#optional
- (void) workingOn: (NSString*) msg; // #"Doing this, doing that…"
#end
Actually, i successfully used this template many times, but it feels a little too verbose.
Block callback
Very similar to delegation, but keeps code in one place.
// Starting our background task...
[MyTask startComputationWithProgressHandler: ^(float progress, NSString* msg)
{
// Switching to the main thread because all UI stuff should go there...
dispatch_async(dispatch_get_main_queue(), ^()
{
self.progressIndicator.progress = progress;
self.informationalMessage = msg;
});
}];
KVO or polling of a progress properties
In this case background task object must have two properties similar to these:
#property(readonly, atomic) float progress;
#property(readonly, atomic) NSString* message;
And a client (our controller object) should set itself as an observer of these properties. The major flaw i see in this solution is that KVO-notifications always arrive on the same thread that caused the change. While you can force your observer (callback) method to run on a particular GCD queue it may not be always appropriate.
NSNotificationCenter
Background task sends notifications and client listens to them.
Is there any other patterns applicable to this situation? What solution can be treated as a most modern and Cocoa-ish?
When it comes to What is the Cocoa-way of observing progress of a background task? I would say delegation and NSNotificationCenter because blocks and KVO were introduced later, and hence didn't originally exist in the first Cocoa code writting years. In fact optional protocol methods were not present in previous objc versions too, everything was required by default.
From that you can actually see that blocks are a simpler way of implementing adhoc delegates, where the receiver of the block declares what parameters are passed to the block, and you are free to do whatever you want with them in your block. And KVO seems to be a less boilerplate way of implementing NSNotification with a more standardized approach to properties, useful for joining the UI created in what previously was called Interface Bilder, and simplifying the "what the hell do I have to do to know when this value changes" which requires a lot of documentation with NSNotification and long constants.
But I still think that there are places for each of these techniques: blocks are nice for mini-adhoc protocols, but would be a serious bother if you need a medium or higher interface area or bidirectional interface, and KVO doesn't help with watching global variables or values outside of a class/object, or stuff you don't want to make part of your public interface.
So my definitive answer is:
1 to 1 simple communication: blocks
1 to 1 complex communication: delegates/protocols
1 to many simple communication: KVO (where possible)
1 to many complex communication: NSNotifications
As always, pick the best tool for each problem, and consider I'm guilty of implementing all of the above in none of the suggested ways!
For the type of task you describe, I feel that NSNotificationCenter is the best option for a generic pattern. The reason is that you can't know, generally, how many external observers there are. The notification system already supports an arbitrary number of observers for an event, whereas the other non-polling options (delegation and blocks) are more typically one-to-one unless you do extra work to support multiple registrations.
As you pointed out yourself, polling is a bad idea if you can avoid it.
In my experience delegation or block callback are the best design choices. Choosing one over the other is mostly dictated by which one is more convenient to code and support for the particular situation. Both are asynchronous. Block callbacks usually reduce the necessity for additional instance variables since blocks capture variables within their scope. Of course for both it's necessary to be aware on which thread the call back is executed or delegate method is called.
I'd go with KVO because you get it for free when using #properties basically.
BUT
I would not recommend using plain KVO. because that will always call - observerValueOfKeyPath... and once you observe multiple keypaths it gets annoying to maintain. you have this mega function with lots of if(keyPath==bla)......
I recommend MAKVONotificationCenter by MikeAsh for this. It also saves you from many a crash when you forget to remove an observer when you dont need it anymore

When to be careful about multithreading in EJBs?

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.

Creating Dependencies Within An NSOperation

I have a fairly involved download process I want to perform in a background thread. There are some natural dependencies between steps in this process. For example, I need to complete the downloads of both Table A and Table B before setting the relationships between them (I'm using Core Data).
I thought first of putting each dependent step in its own NSOperation, then creating a dependency between the two operations (i.e. download the two tables in one operation, then set the relationship between them in the next, dependent operation). However, each NSOperation requires it's own NSManagedContext, so this is no good. I don't want to save the background context until both tables have been downloaded and their relationships set.
I've therefore concluded this should all occur inside one NSOperation, and that I should use notifications or some other mechanism to call the dependent method when all the conditions for running it have been met.
I'm an iOS beginner, however, so before I venture down this path, I wouldn't mind advice on whether I've reached the right conclusion.
Given your validation requirements, I think it will be easiest inside of one operation, although this could turn into a bit of a hairball as far as code structure goes.
You'll essentially want to make two wire fetches to get the entire dataset you require, then combine the data and parse it at one time into Core Data.
If you're going to use the asynchronous API's this essentially means structuring a class that waits for both operations to complete and then launches another NSOperation or block which does the parse and relationship construction.
Imagine this order of events:
User performs some action (button tap, etc.)
Selector for that action fires two network requests
When both requests have finished (they both notify a common delegate) launch the parse operation
Might look something like this in code:
- (IBAction)someAction:(id)sender {
//fire both network requests
request1.delegate = aDelegate;
request2.delegate = aDelegate;
}
//later, inside the implementation of aDelegate
- (void)requestDidComplete... {
if (request1Finished && request2Finished) {
NSOperation *parse = //init with fetched data
//launch on queue etc.
}
}
There's two major pitfalls that this solution is prone to:
It keeps the entire data set around in memory until both requests are finished
You will have to constantly switch on the specific request that's calling your delegate (for error handling, success, etc.)
Basically, you're implementing operation dependencies on your own, although there might not be a good way around that because of the structure of NSURLConnection.

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?

Resources