simple example@ptr to method[[Essential c++]]

I tried repeatedly but unsuccessfully to wrap my mind around ptr to methods, until I hit P130 [[essential c++]].

Your class should have a bunch of sister methods with identical params and identical returns. Remember every ptr VARIABLE[1] exists as (compile time) symbol table entry with
– a name,
– a value (address of the pointee) and
– a declared type

This pointer var can point to any of those sister methods, but not any look-alike methods in other classes.

[1] there’s no such thing as a “pointer” — only pointer _variables_ and pointee addresses.

non-trivial Spring features in my recent projects

FactoryBean —
lookup-method — method injection using CGLIB
InitializingBean — an alternative to init-method
Auto wiring
component-scan
@RunWith for unit testing
property place holders
converters
jms messageConverters
TestContextManager.java

–SmartLifecycle.java — Simply Magical ! Used to auto start threads when our custom ApplicationContext starts

— @Resource — on a field “cusip” would mean “Mr XMLBeanFactory, please inject into this.cusip an XML bean named cusip”. System implicitly declares this *field* in the xml bean definition of this class, but you need to declare the “cusip” bean.

Q: Just where and how does my aa_reoffer JMS test start the broker daemon thread?
A: Neoreo QueueFactoryBean (FactoryBean derivative) has a getObject(). In it, we create a new JmsTemplate and call execute() on it. This Spring method creates a full-blown jms session, which creates the daemon on demand.

architectural design xp]job candidate (trading sys

(Some personal observations, to be posted on my blog)

If a job description says … architectural design experience desired…, but the role is NOT the architect, then I bet the new hire is NOT really welcome to comment on architectural decisions.

I have seen enough to be convinced that each small development team (3 – 10 developers) only has one architect. “No 2 tigers in 1 mountain.” as the Chinese saying goes.

If a new hire has a lot of architect experience, he (or she) had better keep a low profile on that. Whether the system is in early or final design stage, the designated architect inevitably has some good ideas how she (or he) wants it done. Most software designs have non-trivial flaws and painful trade-offs, so it’s easy to question her design.

( Requirements are best understood after system roll-out, and very vague in the design stage. Requirements are always subject to change, so every architect endeavors to future-proof her design, which is always a hit and miss — we always overshoot there and under-design here. )

The system architect won’t admit it but she seldom enjoys challenging questions on her design. If the question gives her a chance to show off her design, fine. Otherwise, those questions waste more time and adds more confusion than value. Some questions may bring rare insight and help the design, but i’m no expert on the communication process required for such questions to be openly asked. There are many wrong ways to ask such a right question.

As job descriptions put it, employers genuinely “desire” some amount of architect experience in a new hire. Perhaps such an experience helps the new hire work with the existing architect. A soccer team desires players with center-midfield experience. Doesn’t mean you and the existing center midfielder should both play that position.

RBC iview 2

Q: How do you size your JVM memory? Beside -Xmx?
A: initial size is important, cos dynamic resizing is bad for performance.

How would u choose between dist cache vs database?

Why volatile has problem with long/double? How do you solve it?

Your exception strategy? return null? return error code?

What’s the benefit compared to a hierarchy of exception classes?

What if your queue becomes full when your consumer is offline?

Q: What’s the middle layer between your web server and the database in a high volume web site? None?
A: Before dist cache was easily available, a lot of popular websites were fine without it. One solution was adding enough memory (100G) in DB server so the entire DB is in memory, to eliminate disk I/O. Another solution is one-master-many-slave one-way replications, so RO operations are highly concurrent and hit replicated DB servers nearby. In my department, we split position data into 11 premises to speed things up, without any dist cache sandwiched between web server and DB. We do have a cache holding account data. We use RV to update the cache.

PnL attribution — first lesson

For any derivative risk engine, one of the most essential information
business wants to see everyday is PnL attribution.
http://en.wikipedia.org/wiki/PnL_Explained illustrates that a typical
report has
Column 1: PnL — This is the PnL as calculated outside of the PnL
Explained report
Column 2: PnL Explained — This is the sum of the explanatory columns
Column 3: PnL Unexplained — This is calculated as PnL – PnL
Explained (i.e., Column 1 – Column 2)
Column 4: Impact of Time (theta) — This is the PnL due to the change in time.
Column 5: Impact of Prices (delta) — This is the change in the value
of a portfolio due to changes in underlier price
Column 7: Impact of Volatility (vega) — This is the PnL due to
changes in (implied) volatility
Column xxxx: new trades, cancels,
http://pnlexplained.com/PEP_PnL_Explained_FAQ.html shows that usually
the attribution numbers (theta att, delta att, vega att…) add up to
be close to total unrealized PnL (Column 1). The mismatch is known as
PnL unexplained (Column 3)
A market maker should be delta-hedged (regulatory pressure) so delta
attribution is kept low — MM should stay unaffected by stormy
markets. See http://bigblog.tanbin.com/2011/12/buy-side-vs-sell-side-trader-real-diff.html
Let’s take volatility attribution for example.
http://www.pnlexplained.com/ has a nice hierarchical diagram showing
the breakdown of vol attribution.

dependency injection – promises && justifications

* “boilerplate code slows you down”.
* “code density”
* separating behavior from configuration. See post on “motivation of spring”
* code reuse, compile-time dependency. cut transitive dependency. — u can move the aircon without moving the house. “to build one class, you must build the entire system”
* “tests are easier to write, so you end up writing more tests.”
* easy to mock

These are the promises and justifications as authors and experienced users described.

SL WCF async call – a real example

In one of my SL apps, client need to
1) connect (via ConnectAsync/ConnectCompleted) to a WCF server so as to subscribe to a stream of server-push heartbeat messages. These heartbeats must update the screen if screen is ready.

2) client also need a timer to drive periodic pings using getXXXAsync/getXXXCompleted. If ping succeeds/fails, we would like to update the status bar. Therefore the callbacks had batter come after screen setup.

3) at start time client makes one-time get1Async/get1Completed, get2Async/get2Completed, get3Async/get3Completed calls to receive initial static data so as to populate the GUI. I wrapped these calls in a static Download6() method.

*) basically all these data from server (either server-pushed or callbacks) “WANT” to update screen provided static data is loaded, which is done by D6 callbacks. So D6 callbacks had better happen before heartbeats come in, or heartbeat processing would hit empty static data and cause problems. Also, D6 callbacks must execute after screen setup, because those callbacks need to update screen.

That’s basically the requirements. In my initial (barely working) solution everything except timer stuff happens on the main thread.

1) at start time, main thread invokes D6. The callbacks would come back and wait for the main thread to execute them — troublesome but doable
2) main thread makes initial ConnectAsync. The callback would hit main thread too
3) before these callbacks, main thread finishes painting the screen and setting up the view model objects.
4) now the D6 and ConnectCompleted callbacks hit main thread in random order. D6 callbacks tend to happen before server pushes heartbeats.
5) upon ConnectCompleted, we subscribe to heartbeats
6) Timer has an initial delay (about 10s) so usually starts pinging after the dust settles. The Async and Completed calls execute on 2 different non-main-threads.

All the “scheduling” depends on event firing. It’s not possible to “do step 1, then at end of it do step 2…” on main thread.

I now prefer to move the connect, d6 etc off main thread, so the callbacks would hit some other threads. More importantly, this way I have a chance to utilize locks/wait-handles/events to properly serialize the Get/Connect calls, the timer-start and the subscription to server-push heartbeats. This means Step B starts only after Step A completes all callbacks. This was not possible earlier as it would block the main thread and freeze the screen.

WCF async call in SL – 2 funny rules

Rule AB0) in all cases, Main thread must not be blocked during the WCF call. Some part of the flow must happen on the Main thread.[1]

A) You can make an xxxAsync call from either Main thread (Thread1 in debugger) or a non-Main-thread such as thread pool or timer.

Rule 1) Main thread will execute xxxAsync(), then finish whatever it has to do, then execute the callback when it becomes idle. The callback ALWAYS executes on the same Main thread.

Rule 2) non-Main thread executes xxxAsync(), then the callback usually executes on the same (or another) non-main-thread.

B) Synchronous? It took me a bit of effort to make the call synchronously. But obey Rule AB0. See http://www.codeproject.com/Articles/31018/Synchronous-Web-Service-Calls-with-Silverlight-Dis

 var channelFactory = new ChannelFactory("*");
var simpleService = channelFactory.CreateChannel();
var asyncResult = simpleService.BeginGetGreeting("Daniel", null, null);
string greeting = simpleService.EndGetGreeting(asyncResult); 
 

————-
I find it a good rule to avoid calling xxxAsync on Main thread in non-trivial SL apps. I now do it on other threads. It often involves more BeginInvoke, but eliminates a lot of future restrictions.

Incidentally, if the callback is on non-Main thread but needs to modify View or Model, then you need to use BeginInvoke or SynchronizationContext

[1] Suppose you put UI thread on some wait handle or grabbing a lock so it blocks, to be released by the “wcf thread”. If you do that, then “wcf thread” would also block waiting for some part of the processing to run on the Main thread. This is a fairly classic deadlock situation.

c#event^delegate, again

There are many excellent online introductions of the relationship between events and delegates. Here’s some personal observations —

1) first there’s a difference between an event-field vs an event occurence. When we say “This class has an event” or “subscribe to this event” we mean the field. However, when we say “fire this eventA” we use this big gun named eventA to fire a missile.

2) Virtually everyone commit the crime of ambiguity when they say a “delegate” rather than “a delegate Type” or “a delegate Instance”.

3) we must point out there are
* delegate types
* delegate instances
* delegate variables — local variables, method parameters
* a delegate field
** a special case — If the delegate field has an “event” modifier, then the field becomes an event field.
It’s confusing and unproductive to compare event fields to delegate instances, or delegate types. Many casual discussions of event vs delegate often bring the delegate instances into the picture, adding to the confusion. Always bear that in mind whenever there is similarity/confusion between delegateInstance vs events.

An event field is better compared to a delegate variable, but an event field is Best compared to a non-event delegate field. A non-event delegate field behaves differently from event fields. I think it’s supported and more flexible but rarely used. See
http://pro-thoughts.blogspot.sg/2008/08/delegates-and-events-what-does-event.html