superclass param, subclass argument

      Dog(Number o) {
      }
      Dog(Integer s) {
      }
      public static void main(String[] a) {
            Number ptr = new Integer(22);
            /**
             * won’t call the (Integer) ctor.
             * Won’t compile if you remove the (Number) ctor. Compiler doesn’t know
             * ptr points to an Interger object. Compiler only knows ptr is a Number (or
             * subclass) object. Runtime type of the pointer ptr is known only at runtime.
             */
            new Dog(ptr);
      }
}
Advertisements

RBS IV – risk

Q: have u used atomic variables like AtomicInteger?

Q: A web app showing on demand employee address + employee investment valuation which could take a while to compute and return. As a server side java guy, how do you show the employee address on the browser and then show the valuation when it becomes available.
A: I often have another thread (pool) for long-running jobs

Q: is there some rule saying a web app should not start new threads?

Q: what DB tuning techniques did you use?

Q: if you have so much data in DB and it is a bottleneck, did you try to avoid the DB?

Q: did you try partitioning?

Q: why does polymorphism only apply to methods and not fields?

##what zbs skills differentiate java trading developers

I said before that core java trading system developers need a few special skills

1) multi-threading
2) messaging
3) data structures and algorithms
?) distributed caching — trading system often avoid hitting database, so they keep large amounts of data in memory
?) java tuning
?) distributed computing using RMI, web services, ejb etc
?) Spring DI beyond MVC
?) serialization

#1 and 2 are the most broadly recognized requirements.

Now I feel most of these skills are built on top of fundamental java skills. Messaging system uses threading, serialization, data structures. Caching uses threading, data structures, serialization …

I don’t know a well-defined list of “fundamental java skills” but interviewers often zoom into threading, collections and OO. Among these, threading presents the highest complexity, but most applications stick to well-tested fool proof patterns.

I feel java generic collections (in a multi-threaded environment) is perhaps the 2nd in complexity. (I realized this after reading c++. C++ generic collections are quite a bit messier than java.) Most java developers I know never need to go beyond scratching the surface of generics.

In conclusion, to pass interviews, over-prepare on threading and collections, and prepare for high-level questions on messaging. To be a good trading programmer, become really good at threading and serialization… among other things

net revenue, unrealized pnl

For a financial controller overseeing a trading desk, MTD [1] net revenue is the profit or loss of a trading account [2]. One way to compute this number is

 

  Realized pnl + unrealized pnl [3] – sales force commissions [4] paid out + interest accrued while holding the security

 

[1] or daily or YTD – just some period

[2] or a group of trading accounts

[3] paper loss or paper profit

[4] aka sales credit

##growing in java: where to focus when learning c++/c#

I feel stronger than a rookie java developer because we are comfortable with both GTD and IV:
1) IDE
** (remote) debugging. Also consider my Perl sss()
2) threading — idioms, principals
** thread creation, synchronized, wait…
** threadlocal
** thread pool
** immutable
3) reflection + proxy
) syntax of overriding, constructors, final, singletons, generics
) design patterns — large idioms
) unit test

other signs of strength:
) generics — creating generic classes
) serialization
) garbage collections
) RMI
) inner classes
) collections and data structures — choosing

What about spring, hibernate …? I feel these fads come and go.

trading sys arch IV : cod`IV@best practice

Most of the SG/HK employers (UBS, RBS, Mdaq) perceive a wall street veteran (like me) more as an architect/tech-lead candidate than a senior dev. However, the tough tests are coding tests.

You would think an architect interview would not focus so much on the fine details. Well, many details (by definition of the word) are not important to an arch interview, but some (1%?) of the details are. Fundamentally, this is because any large of small software architecture is always conceived and ultimately implemented using __basic_comp_science_constructs, such as stackVar/heapVar/staticVar, thread safe iterators (loops), queues (linked list), circular array, concurrency primitives …

Another reason — the team lead would define and enforce low-level design and coding standard.

Fact is, these architect roles are extremely hands-on. In low-latency architect roles, a key value-add is the experience, insight, techniques, tools on low-level optimizations.

Among the 3 types of domain knowledge (see my other blog), your jargon/math experience is not relevant in a coding test. How about your trading arch experience? Relevant to some extent.

hibernate mock interview question

short and imprecise? ok
[m=answer found in official hibernate manual such as http://www.hibernate.org/hib_docs/v3/reference/en/html/tutorial.html ]
page numbers -> [[ java enterprise in a nutshell ]]

  1. how do you process a bunch of records when you select half the columns? What kind of data structure does hibernate return? P 650
  2. how do u update a “disconnected object”
  3. why proxy?
  4. Lazy loading? (seems to be important)
  5. write a finder statement used in your (pushmail) DAO class to illustrate the difference hql ^ sql
  6. big signature of Session.load(). AR-revealing!
  7. access modifier for fields in a domain object? P 630
  8. name the 2 types of hib config files
  9. generator class=”native” means? P 627
  10. what typical java types to use for persistent fields?
  11. what happens if there’s a clash in an id field/column when writing to DB? P627
  12. describe exactly when hibernate writes to DB. I think this is covered in my blog. P643
  13. what’s a bag?
  14. describe the session object
  15. describe the query object
  16. what’s the difference between the properties file vs the xml file
  17. what performance issues did you face using hibernate?
  18. how did you integrate hibernate with proc?
  19. 2 types of hibernate caching? (2nd-level caching)

non-iview questions:
* how does hibernate manage connection pool(s)? P641
* what if you try to load one object and all the linked objects are loaded and it takes huge memory and db query resources?

q[explicit] 2 ways to call ctor

A conversion ctor can be invoked 2 ways
B b1 = 123;
B b2 (123);

Similarly, a copy ctor can be triggered 2 ways
B b1 = anotherB;
B b2 (anotherB);

The “explicit” keyword on a ctor disallows the “=” version….

Q(Obscure): why put “explicit” on the no-arg ctor?
A: I see no practical usage. https://stackoverflow.com/questions/48677746/explicit-default-constructor shows an example and some explanation.

struct C{
    explicit 
    C(){}
};
struct K{
    C c;
};
int main(){
    K myk{}; //fails with error: converting to 'C' from initializer list would use explicit constructor 'C::C()'
}

common quote pricing rules + live feeds for munis

Rule: (same as FX day trader, and applicable to market making only) based on inventory changes
Rule: dollar cost averaging
Rule: based on BMA index, which is typically 70% of Libor, assuming a 30% tax exemption
Rule: on the muni desk, the swap positions and quotes are priced using SIFMA swap index and ED futures
Rule: on the muni desk, the T (and futures) positions and quotes are priced using T/T-futures price feed
Rule: based on ETF prices. If one of our quoted bonds is part of one (or several) ETF, we price our bid/ask using live ETF prices
Rule: based on Evaluation prices, received twice daily (JJ Kenny and InteractiveData)
Rule (one of the most important): based on MSRB last-traded quantity/price reported to MSRB
Rule: based on “pins” controlled by senior traders of the desk
Rule: based on The One Muni Curve of the trading desk
Rule: stock (hedging) positions (not quotes) are priced using stock price feeds

Other feeds – ION, SBA (SmallBizAdmin) feed

“Based on” generally
Always apply a bid/ask spread matrix (call dates/quantity as x/y dimensions)
Always apply a commission matrix
Apply odd lot discount matrix
Always convert from clean to dirty price
Always check for occurrence of bid/ask inversion

##5 notable value-types in dotnet

CancellationToken
TimeSpan
DateTime
Guid
System.Nullable — parametrized struct

— /also-rans/ —
System.Drawing.Point
Decimal – just another Float
all “simple types”
all enum types

I feel  these are often immutable. Even if mutable, given the pbclone semantics it’s almost useless to provide mutator methods anyway. However, to understand mutable structs, consider the most improtant value type — int.

In a standard “for (int idx…” idx is mutable, but when you make a copy of idx (or pass in/out a function) the copy is detatched from the mutable int variable.

kill a stuck thread using SureStop – practically

Suppose you suspect your thread is stuck in a nonresponsive I/O call, or a super slow and unnecessary compute job, or more importantly a *deadlock*, you need to restart JVM. However, in some contexts you have a lot of other healthy threads doing useful work halfway, so you don’t want to lose those. You want to terminate that thread.

First get a thread dump and try to detect the deadlock cycle by inspection. In “some” cases you can see signs of deadlock, so how do you kill a thread that’s holding a lock?

Well, usually the lock is held for a reason, often to prevent access to a guarded object in an inconsistent state. In that case you don’t want to risk your system *integrity* by killing the thread and exposing the inconsistent object.

Suppose you know it’s ok and want to kill the thread, here’s one proposal.

A server often has a GUI admin console showing the live threads. Thread objects register in a static lookup table, so the GUI can monitor and show their status, perhaps by JMX. On GUI, hit “kill” on the target thread. Now the admin thread will get the Thread object from the lookup table and use the SureStop utility to kill it.

Another solution — remote debugging with authentication. This gives you direct access to suspend any thread or terminate it.

Adapter pattern demystified

Doug Lea (P59) seems to suggest that an adapter is a wrapper. He also said proxy ,delegate and Composite patterns are all based on this wrapper idea. I find this simplicity refreshing and liberating, in contrast to the long-winded, strict and formal definitions.

I think “delegate” and “adaptee” are synonyms. I think “delegate”, “wrapper”, “adapter” are usually interchangeable. “Proxy” has a more specific meaning in java — reflection, web services …

Key words of Adapter pattern:
* forward — an adapter forward method calls to the adaptee object. Also known as delegating.
* HasA
* single — just a single adaptee in an adapter. Multiple adaptee is … another design.

3 storage classes for c++variables: lifetime^scope

external
static
thread_local

(Most important type for me is the external…)

https://www.programtopia.net/cplusplus/docs/storage-classes points out that these 4 describe the lifetime and visibility of a variable.

https://docs.microsoft.com/en-us/cpp/cpp/storage-classes-cpp is more authoritative.

initially there are only 2 — auto and external. They added “register” as a subtype of auto. They added static as a subclass of external.

External variables are global variables. I feel globals and file-scope static objects are stored in the same area, not on stack or heap.

large/time-consuming engine accessed via web?

In risk, stress testing, scheduling, optimization, pricing systems, a request or task might take a long time (4 hours to price exotic options) to complete. Yet, almost always, web + email can provide an adequate interface. I *used* to dismiss http as good for quick round trip GET/POST requests.

A form can submit a request into the engine and simply complete the round-trip. What happens after the round-trip?

* browser can be programmed to auto-refresh
* user can visit (or be redirected to) another URL that shows incremental output
* progress bar on browser. I have seen such things.

Behind the scene, a DB or MOM can hold the task queue.

real time trading decision making sys: more critical than risk sys

Look at pricing engine. Equally quantitative as risk system, but

* in reality(?) traders often don’t check risk numbers before placing a trade
* in fast markets you probably have to take risks and make trading decisions on the spot
* the more reliable risk numbers are more delayed and less useful in real time trading
* the more realtime risk numbers are less reliable. Look at VaR and stress testing.

Other parts of real time trading are also more heavily used than risk
+ market data
+ execution
+ algo trading
+ high frequency trading
+ smart router

custom c# struct – rarely needed

(built on P84 ProgrammingC# OReilly) Many experienced c# guys rarely feel the need to create custom structs. A few reasons —

– pbclone needs to be cheap. Won’t be cheap if there are more than 3 simple type fields inside a custom struct
** STL iterators is also designed for cheap pbclone.
** ditto C++ smart pointers

– a struct instance should be immutable. An int variable has a struct type but is Mutable. However I believe most standard c# struct types are Immutable, without mutators like MyStruct.decrement(). If you pass a struct instance by copy and then “edit” the copy, result is often counter-intuitive. Therefore if you need a custom mutable struct, consider a custom Class instead

FX fwd arbitrage – 4 b/a spreads to OVERCOME

Look at the parity between fwd/spot FX rates and the 2 interest rates (in the 2 currencies). Basic concept looks simple, but in the real market each rate is quoted in bid and ask. 8 individual numbers involved.

We pick 4 of them to evaluate ONE arbitrage strategy (fwd rate too high) and the other 4 to evaluate another arbitrate opportunity (fwd rate too low)

Across asset classes, most pricing theories assume 0 transaction cost and 0 bid/ask spread. In this case, the bid/ask spread is often the showstopper for the arbitrageur. Similar challenge exists for many option arbitrageurs.

I think [[complete guide to capital markets]] has one page illustrating this arbitrage.

non-math fin domain knowledge

I think a lot of jobs still screen me out due the “simple” domain knowledge ie the jargons. This kind of domain knowledge can be acquired in 6 – 12 months without much effort, but hard to acquire without a learning environment.

* risk
* Order Management
* IR swaps
* credit derivatives
* equity derivative
* algo trading

master list — home grown c++ jargons

(keep in the this blog …)
* a dummy type name  or a type-param is the T in
* a CONCRETE-template-class is an INSTANCE of a template, with a defined actual type or TYPE-ARG

copy-controls — copier, assignment, destructors. [[c++ primer]]
nonref — a variable that’s not pointer or reference
primitives — primitive types, primitive vars ie non-class types
copier — copy constructor
noarg — the noarg constructor
ref
ptr
heapObj — not “heapVar”
globals
lval — lvalue
locals = stackvars — local auto vars
virtuals — virtual methods
pbclone, pbref
mutators, inspectors — non-const and const functions (including “methods”)
getters, setters — methods

compareAndSet by 2 competing threads — probably safe


static boolean unsynchronizedSetter(Date expected){
Date newDate = new Date();
AtomicReference myAtomicReference = Lookup.getAtomicRef();
boolean myStatus = myAtomicReference.compareAndSet(expected, newDate); //CAS
return myStatus;
}

Q: If 2 threads execute the CAS simultaneously, which object will get stored in the atomic reference?

In a multi-processor machine, 2 threads could be performing the CAS in the same clock cycle. Suppose they both use the same myAtomicReference object to do the CAS, both use the correct value of “expected”, but they try to put in 2 distinct objects ie the 2 newDate. One of them must fail, but will myStatus be false in that thread?

I feel it’s ok if both threads get myStatus==true, in the same clock cycle or not. Right after the CAS clock cycle, the atomic reference holds one of the 2 values. But how many clock cycles later will the subsequent myStatus-dependent statement execute? No guarantee. Therefore when it does execute, the atomic reference could hold any value. myStatus==true doesn’t mean “my value was stored”.

We must also consider statement reorder and per-thread caching, as described by Doug Lea.

I guess one hardware implementation of CompareAndSwap might make the 2 threads queue up to do their updates. I guess even if the 2 processors are executing the CAS instruction in the same clock cycle, one of them is probably delayed.

In general, Simultaneous writes aren’t allowed by the memory module — just consider voltage signal in that write cycle. We won’t go into details but input voltage applied to a particular bit in RAM must be either 0 or 1, not both. This is the original meaning of electronic race-condition. Some links —

http://eom.springer.de/p/p120050.htm

http://stackoverflow.com/questions/516940/can-multiple-cpus-simultaneously-write-to-the-same-ram-location

y prepareStatement uses the connection object

 

                  PreparedStatement ps = conn.prepareStatement (sql);

 

Preparing (compiling) a preparedStatement is done on the DB server, so the java client must reach out to server.

 

PreparedStatement is faster because of pre-compiling. Pre-compiling means a 2 stepper – pre-compiling and executing-with-argument. For N iterations, You need to send 1 + N “messages” to the server. Only the first call (pre-compiling) need to use the connection object.

vague^normal^specific answers in non-tech interviews

My communication style is detail-oriented and I tune in to specific details. (That’s why I can write.) When another person’s or my own answer is rather vague or very specific, i often notice it before others do.

There are vague answers, normal answers and specific answers in any job interview. You can actually observer the interviewer’s own styleFor tech questions, the more specific, the better. For personality questions, probably not.

After you pass the tech interviews, you don’t have to sell any more. Non-tech interviewers are already sold and basically sniff for potential personality weaknesses. Non-tech interviews need to see “nothing suspicious” in you and not seeking “star qualities”. If a non-tech interview is busy or have seen many candidates, he can only remember very few things about you. If you just give stock answers, you might be less memorable, but that’s perfectly fine. They always notice that you can explain complex things, can understand and speak English — you pass.

Very specific answers to non-tech questions often show a type of personality. Leaders aren’t always that type. High-level thinker/communicator. As a leader, you often need to communicate to different team members. Not all of them detail-oriented communicators.

Non-specific answers don’t sound evasive and fake.

I often react to surprise questions with slightly vague answers. (These answers could be **better** than the detailed but contrived answers I sometimes come up with.) I feel rather bad about my imprecise *words* therein because I’m sensitive to individual words. I think most people are less sensitive to individual words but rather listen to the whole sentence and the whole person. I think a lot of IT candidates aren’t particularly articulate and eloquent and often beat around the bush with vague, bland answers.

I almost never give brief answers to behavioral questions, but some good answers are fairly short, possibly guarded or evasive, perhaps depending on the listener.

You don’t want to be evasive when answering a pointed question like “why you left that company?”

If you can’t think of specifics to substantiate your answer, then it’s probably ok to be less specific. In your effort to sell yourself and demonstrate your personal quality, you might reveal a very strong flavor of communication style. I think for technical non-lead roles, most candidates answers are not that specific but that’s fine.

If you are detailed-oriented, story-telling may come natural to you, even if you tell the story backward, even if you use imprecise words. Most of my stories are relevant, and most interviewers are interested. Some may be too busy, so it’s good to stop and test their appetite. See other post on a list of good stories.

Doug Lea’s 3 chapters

Doug Lea’s book consists of 1 overview chapter and 3 specific chapters, organized around 3 challenges and 3 java language features

· Exclusion and locking
· State dependency and wait/notify
· Thread creation

In financial apps, locking seems to be much more relevant and visible than wait/notify. It’s possible that wait/notify plays absolutely critical roles in critical financial apps, but I don’t know any.

By remote debugging, I see wait/notify exists behind the scene in low-level concurrency routines, but finance developers seldom need such knowledge.

Thread-safety, consistency, races and exclusion is primarily achieved by locking. Other exclusion techniques are much less used, and includes
* thread-safe collections
* threadlocals
* immutables

According to the Stanford lecture, it’s absolutely clear that semaphores are low-level constructs and can implement “synchronized” keyword. It uses notification to implement lock release. Simplest railway semaphore is a (binary) light that turns *on* to inform multiple waiting trains. Terminology warning — in this case,
* signal or notify means release lock and inform all blocking threads. Object.notify() means (after getting the lock) inform all threads in the waiting room, without releasing lock
* “wait” means attempt to grab the lock. Object.wait() means (after getting the lock) enter waiting room and release the lock, and upon wake-up, grab lock again and return from wait().

commodities trading sys

* trading sys — oil
* trading sys — base metal
* trading sys — precious metal
* trading sys — futures, options, …
* position calculator
* gateway/exchange
* risk attribution
* matching system
* physical scheduling
* OTC off-exchange commodity contracts

Mostly c# and java. c++ is used when a faster algorithm is needed, when no framework is needed, and in analytics..

guarantor and risk margin in FI trading – Citi context

Recently, FICC trading partners started using 3rd party guarantors. Think of guarantors as private clearing houses who provide integrity, reassurance against counterparty defaults.

Both buyer and seller could open margin accounts with the guarantor, and gain leverage. With leverage/margin comes default risk. As with futures exchange margin accounts, assets are marked to market nightly.

Guarantor takes, ideally, no risk and earns a fee. However, to maintain their zero-risk, they must carefully compute marks and issue margin calls.

At the core, the all-important marking process is basically asset valuation as-if-liquidating, and implemented using VaR. This is what (I guess) how it works — If VaR says “over next 10 days, in the 1% worst cases our smallest[1] loss is 3%”. For margin valuation purpose, we simply say equity is 3% lower than current value??

[1] Contrast conditional VAR. Largest loss is 100% loss

Q: What FICC products use guarantors?
A: Mostly fixed income, not much “CC”. Futures contracts usually need a guarantor (i guess the exchange itself — Futures always trade on exchanges). A lot of derivatives too.

Bond buyers can also benefit from a guarantor. Investor deposits an initial margin amount with the guarantor, buys the bond using the margin account, receives margin calls when valuation drops. If for 2 years she always meets the margin requirement, then she enjoys the leverage advantage — doesn’t need to put up the full capital. Guarantor basically lends money to her to finance her investment.

subvert — "private" access modifier in java — surprises

Given 2 instances of C — c1 and c2. c1 can access private members in c2. See [[hardcore java]].

What about an instance b1 of a base class B? I believe b1 can’t access them. Compiler will tell you b1 knows nothing about subclasses’ fields. Similar to the c++ slicing problem.

A sound byte — “private” is checked at compile time.

Such an understanding of “private” is critical to nested classes. See posts on nested classes.

Moving on to “protected”. B has protected m1(), so a C method can call super.m1() or equivalently m1(), but an arbitrary method of an arbitrary class can’t call m1(). Again compile-time check. This is the story of the protected clone() and finalize() in Object.java.

I feel finalize() is designed to be called as super.finalize() in an overridden finalize().

static methods perfect; static fields dangerous

Hi XR,

Over the last 5 projects, I am moving into a new design direction — use static (rather than non-static) methods whenever possible, while keeping mutable static fields to a minimum.

A digression first — a note on local “auto” variables as a superior alternative to instance fields. Instance fields represent object state, which is often shared. System complexity (as measured by testing effort) is proportional to the number of stateful variables — mostly instance fields + some static fields. In contrast, Local variables including some function parameters [3] are temporary, on the stack, far more thread-friendly, and often stateless except temporary state. The best ones are scratch pad variables that become unreachable soon, so they don’t pollute, don’t linger, and has no side effects.

[3] If an object passed in as argument has a large “scope” somewhere else, then it doesn’t enjoy the simplicity of local variables.

Similar to local vars, the best static methods are stateless and thread-friendly — these methods don’t change object state i.e. instance fields or static fields. For example, most static debugger statements are stateless; most type converters are stateless; factory methods are often stateless as they create new objects; most math functions are static; many string utils are static

Static methods are often simpler. If you were to implement the same logic with instance methods, they often end up entangled in a web of dependencies.

I can easily move a static method between classes. Perfect lego blocks.

Object dependency is a major part of system complexity. Look at dependency injection frameworks. Java Swing is complex partly for this — Compared to the average non-swing app, I feel the average swing app has more objects and more inter-dependencies.

If you design objects to represent business domain entities (like accounts, requests, patients, shipments, houses..), then instance methods represent behavior of objects; static methods represent … utilities

When I look at a non-trivial OO system, and estimate the percentage of code in instance methods vs static methods, I find invariably instance methods outnumber static methods by at least 3 times (75% vs 25%). Habitually, I refactor them into static methods whenever feasible. Time well spent, as system invariably gets simpler and cleaner.

C# elevates static methods pattern into a language feature — static class

[[the art of readable code]] P98 says — to restrict access to class members, make as many methods static as possible. This let reader know “these lines of code are isolated from those variables”

Any experience to share?

c++ creational patterns – return pointers always

Many creation patterns need to return pointers.

Must use pbref not pbclone, so the choice is between pointer vs reference. I feel pointer is more flexible than reference. If creation fails, we can return NULL.

eg: virtual ctor, esp. clone()
eg: factory http://login2win.blogspot.com/2008/05/c-factory-pattern.html, [[ModernC++Design]]
eg: builder http://en.wikibooks.org/wiki/C++_Programming/Code/Design_Patterns/Creational_Patterns

const ptr field ^ reference field

Nonstatic const field vs reference field — what’s different what’s similar? Many people ask this question, so here’s my take.

Rule: for both, ctor has no choice — must use initializer list.

The 2 constructs are similar and should be studied together.

I feel reference field is less popular than a const ptr field. Reference fields are probably too rigid. Const ptr is a “bendable rule” — mutable, const_cast…

Also, as the source code author, you can decide to remove (or re-add) the const modifier, without affecting client code.

Perhaps a ref field is more useful in class templates as a local typedef?

stepping through class/object loading, Take 2

– – – a story/hypothesis to be verified. See P240,113 [[Practical Java]] and P28,30 [[Java Precisely]] – – –

base static initializer and static initializer BLOCK run, in the order of appearance
child static initializer and static initializer block run, in the order of appearance
(see P30 [[java precisely]])

^^ milestone: classes fully loaded.

child and base instance field half-initialized to defaults — null, 0.0, false,..

^^ milestone: dummy C object allocated, which contains a dummy B object

child constructor C() *entered*
base constructor B() *entered*, as first statement in C(…)
base constructor may call an overridden method m1(), child’s m1(), so child’s m1() runs, with child’s instance fields half initialized! Note in C++, B::m1() runs. See http://www.artima.com/cppsource/nevercall.html

^^ milestone: base constructor B() returns.

child’s instance field initializers run. All fields fully initialized as programmed.
remaining statements in C() run

sync/async available for both consumer types

Both sync and async are available to both queue and topic consumers. Receive() method is specified in the MessageConsumer interface.

Asynchronous onMessage() is the celebrated selling point of JMS and MOM in general.

I used queue receiver.receive() in the SIM upfront project.

Unfamiliar to some people, a topic subscriber can also call the blocking receive() method or the non-blocking receiveNoWait() method. What if you have logic in onMessage but also need to use receive() occasionally? P74 [[JMS]] has an exmple, where a topic subscriber, upon returning from receive(), immediately calls this.onMessage(theMsgReceived).

I think this technique can be useful in Swing, where a thread sends a request to a JMS broker, and blocks in receive(). Useful if the sender thread has a lot of local data unavilable to any other (like a listener) thread.

top 5 message headers – replyTo, correlationId ..

A lot of essential JMS features are implemented as message headers. Producers set those headers (not MessageID though) to inform
– broker
– consumer

— Top headers —
Persistence mode
Expiration
MessageID — subsequently referenced by correlationID. Unlike correlationID, you can’t put your value in it — It’s system generated.
correlationID — can be set to your homemade id from DB or a previous MessageID
replyTo —
* often used with temp topics (“temp queues” in disguise)
* similar to our BWService. RV can do this easily.

cStr cheatsheet – duplicate a c-str on stack (no strdup)

http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html sample code shows that C99 supports variable-length-array, or VLA.

Now it’s easy to duplicate a c-string on stack as a local variable.

void dup(char* orig) {
char dup[strlen(orig) + 1];
strcpy(dup, orig);
cout << “– duplicate a string on stack\n” << dup << endl;
}
int main() {
char a[] = “Four score and seven years ago”;
dup(a);

cStr bread-and-butter functions

strcmp / strncmp
strcpy / strncpy
strcat / strncat
strstr
strtok

——secondary

strlen
strdup — see below

memset

memcpy / memmove (copy with buffer)

Q: why bother with these low level stuff in financial systems, when everyone is moving to C++, java and C# ?
A: low-latency — requires low-level full control
A: these are cross-platform std library functions, in man page section 3
A: lots of production code is in C, not c++
A: I feel C string functions aren’t inferior to std::string or STL vector
A: practically, if you already have a character array, it’s easiest/fastest to manipulate it this way
A: many shops use home-grown standard-conforming string implementations with vendor extensions. I vaguely remember a Barcap colleague said they use a home-grown string class custom-optimized
%%A: it takes quite a bit of vi-style “mileage” to master string manipulation. If you “invest” in std::string you may find it less widely used in some domains like trading.

Q: why use std::string?
A: one advantage is reference counting.
%%A: a wealth of convenience string utilities

[[more effC++]] item on c vs c++ points out that strdup allocates memory (heap/stack) but different environments may internally use malloc() or new(), so I’d say use strdup() only if you don’t need portability.

cStr split – short and sharp eg

See also the concise pdf on c++ streams.

Similar to std::string getline() with delimiter, C-string offers strtok, but the delimiter must be single-character, though you can put together a family of delimiters.

Note first arg must be non-const char*. You may need to first make a copy off a char const*. This string is modified, according to documentation.

#include
#include
using namespace std;

int main() {
    char months[] =
            “JAN^FEB^MAR^APR^MAY^JUN^JUL^AUG^SEP^OCT^NOV^DEC”;
    cout << months << endl;

    char const * const possibleDelimiterS = “^”; //single chars only
    for (char* token = strtok(months, possibleDelimiterS);
            token;
            token = strtok(0, possibleDelimiterS)) { //0 means “reuse”
        cout << token << "\n";
    }
}

cStr checkHasText()

bool checkHasText(char const* c){
    unsigned int const len = strlen(c);
    unsigned int i = 0;
    for (; i <= len – 1; ++i) {
        if (!isspace(c[i]))
            break;
    }
    if (i == len) {
        cout << "all space\n";
        return false;
    } else {
        cout << "has text\n";
        return true;
    }
}

Alternatively, here’s a pointer-arithmetic version, more direct, less readable

bool checkHasText(char const* c){
    for (; *c; ++c)
        if (!isspace(*c))
            break; //better than return true — can check *c
    return *c; //implicitly cast to bool.
//    if (*c) {
//        cout << "has text\n";
//    } else {
//        cout << "all space\n";
//    }
}

##differentiation ] a commodity skill market

Problem: java used in finance is becoming a commodity skill. In fact, any software skill tends to spread very quickly (esp. to the very young developers). What are the exceptions and what are the differentiations we can build up, differentiations that are recognizable by hiring managers?

  • Differentiation: c++, c#, python, perl
  • Differentiation: DB tuning. Most developers don’t face this challenge.
  • Differentiation: jvm tuning including GC
  • Differentiation: practical java performance problem-solving. Compare — I had the opportunity to deal with large DB.
  • differentiation: low latency
  • Differentiation: swing – has unique paradigm and  challenges liks EDT, models, layout … that the regular java developer won’t face

Exception: googlers and facebook developers are probably used to deal with large volume and higher performance. Outside developers face no such challenge.

Exception: Oracle employees probably know their own db much better so few developers can match their skill.

Perl global scope and lexical scope

Nikhil,

P58 of the camel book 3rd edition (excellent summary of scoping rules) says “Although at least two different scopes (lexical and package) are active everywhere in your program, a variable can only exist in one of those scopes”.

So the 2 basic types of variable scopes are lexical and package. Package scope is also known as “global scope”.

Hope this helps, otherwise, feel free to ask me.

%%tech strength/weak among Sr trad’dev candidates]NY

^ threading?
^ java overall?
^ c++ overall?
^ generic algorithms and data structures
^ generic OO
^ SQL?
STL
^ Unix?
Boost
JMS?
servlet/JSP
^ DB tuning?
Spring?
Hibernate?
^ scripting?
RV?
XML
design patterns?

Imagine you are an interviewer comparing candidates “feature-by-feature”. Some areas outweigh others. For example, many interviewers feel fundamental knowledge outweigh experience using 3rd-party tools.

JButton sizing under various layout managers

Flow layout will honor button’s preferred size.(Box layout doesn’t. Border layout doesn’t. Grid layout doesn’t. See also post on wpf vs swing layout. WPF uses min/max.)

    public static void main(String[] args) {
        JFrame frame = new JFrame(“test”);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        for (int i = 1; i < 4; i++) {
            JButton btn = new JButton(String.valueOf(i));
            btn.setPreferredSize(new Dimension(i * 60, i * 30));
            panel.add(btn);
        }
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

http://docs.oracle.com/javase/tutorial/uiswing/layout/box.html#size says —
Although BoxLayout pays attention to a component’s maximum (not preferred) size, many layout managers do not. For example, if you put a button in the bottom part of a BorderLayout, the button will probably be wider than its preferred width, no matter what the button’s maximum size is. BoxLayout, on the other hand, never makes a button wider than its maximum size.

For BoxLayout, I realize it’s tricky to control the height/width. One proven solution is setPreferred()+setMax(). If you only setMax(), then height is uncontrolled.

    public static void main(String[] args) {
        JFrame frame = new JFrame(“test”);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));//or Y
        for (int i = 1; i < 4; i++) {
            JButton btn = new JButton(String.valueOf(i));
            final Dimension dim = new Dimension(i * 40, i * 60);
            btn.setPreferredSize(dim);
            btn.setMaximumSize(dim);
            // btn.setMinimumSize(dim);
            panel.add(btn);
        }
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

named pipe simple eg #unix socket

$ mkfifo –mode=0666 /tmp/myfifo # create a named pipe, with a file name

$ cat /etc/passwd > /tmp/myfifo # writer will block until some reader comes up on the receiving end.

Now open another terminal

$ cat < /tmp/myinfo # or

$ tail -f /tmp/myfifo

http://developers.sun.com/solaris/articles/named_pipes.html shows pros and cons. http://www.linuxjournal.com/article/2156 is a simple tutorial.

Motivation? Allow totally unrelated programs to communicate with each other

A side note to be elaborated in another blog — name pipe is a FIFO stream, whereas unix domain socket can be data gram or stream (like TCP)

eclipse features i learnt recently

* add source code to spring.jar
* limit Problem view (compile errors) to just the project i’m in
* you can remote debug even if your project has compile errors
* export libraries from a project
* launch configuration, using ant targets — clean, build
* search filter in Preferences
* suspend all threads upon an exception
* do not convert line delimiter when checking out from cvs
* change the order of libraries on a build path, to avoid loading a bad version of a class.
* switch between 2 JRE run-time libraries.
*To “show system threads” like GC thread in eclipse, Go to the thread view, look for a small triangle to the far right -> java -> you get a few options on thread listing.

* If you add this line to your method javadoc, then the mouse-over javadoc in eclipse will show a hyperlink to the replace() method javadoc

     * @see java.util.concurrent.ConcurrentMap#replace(Object, Object, Object)

* separate workspace dir from source code physical dir
* eclipse -clean
* refresh a project to fix incomplete build path
* show empty/parent directories in Package view
* Advantage of Outline view over Package view — If cursor is in method1(), then method1() will be highlighted in Outline view, not in Package view.
* show views -> error log