frameworks, facades …"simplifiers"?

I have seen a lot of new api (or library, or framework) created to “simplify” something, to shield developers from the “tedious, error-prone details” i.e. complexity. These façades or wrappers often make the common tasks easy but could make the uncommon tasks harder. 
I feel the technical complexities often won't disappear out of thin air. If you have 
– demanding performance requirements (often requires some engineering and tuning)
– complex, unusual business requirements
– fast-changing requirements (which often requires higher flexibility than supported by the simplifiers)
– large distributed team 
… you have to, one way or another, deal with the details beneath the carpet or behind the facade. The raw material is more flexible.
I have heard many veterans comment that swing is very flexible or C is very flexible.
Here are some endorsed/sanctioned “simplifiers”: 
eg: garbage collector
eg: drag-n-drop programming
eg: high-level concurrency constructs
eg: dotnet wrappers over win32 constructs
eg: any tool to make a remote component feel like a local one
Advertisements

#1 of what I enjoy most – body-building

(Avichal asked me …)

#1 of what I enjoy most – body-building. There are various elements that make it challenging, engaging, sustainable

* some value-add for the tech community

* relevant to immediate IV -and- value-add-for-employer, which translates to stable and hopefully rising income…
Example – high performance c++ on linux

* unlocking additional job markets
Example – c++, c#, swing, socket
Example – FX domain knowledge
Example – quant stuff

* Real insight gained only by in-depth study, overcoming a non-trivial entry barrier, and building a lead over competitors
Example – quant trading strategy
Example – threading, STL,
Example – insights into c#
Example – stat risk content, even though not really relevant to my interviews.

* strategic value to my competitive position
counter-example: secDB

WPF binding system queries VM upon PropertyChanged event

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx pointed out …

The INotifyPropertyChanged interface contains an event pseudo-field called PropertyChanged.

Whenever a property on a ViewModel object (or a Model object) has a new value, it can (should?) raise the PropertyChanged event to notify the WPF binding system. Upon receiving that notification, the binding system queries the property, and the bound property on some UI element receives the new value. I believe this is how new data hits the screen.

I believe the callbacks run on the UI thread, just like swing.

In order for WPF to know which property on the ViewModel object has changed, the PropertyChangedEventArgs class exposes a PropertyName property of type String. You must be careful to pass the correct property name into that event argument; otherwise, WPF will end up querying the wrong property for a new value.

For PropertyChanged to work, i think we have to use xaml binding with a prop name. In contrast, the alternative — defining ItemSource in codebehind probably doesn’t work. 

layout in wpf vs swing, a few pointers

Layout is one of the most important tasks of a GUI coder (as well as the artist). I get layout questions in my GUI job interviews. Despite all the advancement, veterans would probably agree layout is non-trivial. Both WPF and swing have tons of features on layout.

Swing layout is sometimes challenging/painful, esp. with window resizing. There are various advanced layout managers created to address the pains – gridbag etc.

http://killertilapia.blogspot.sg/2012/11/making-sense-of-wpf-layouts.html has some good pointers on wpf with references of swing –

* By default, WPF apps have a base Grid layout. Get rid of it and use “Dock Panel” as your base.  Dock Panels are the same as swing Border layout. The idea is to place the menu on top (DockPanel.Dock=”Top”), status bar bottom (DockPanel.Dock=”Bottom”) and put a Grid at the center. Now you have a well-behaved desktop app that reacts well to window re-sizes. 
* The Grid control is like Swing’s GridBagLayout only easier to use.
* Positioning — Use the AM (Alignment/Margin) to position elements in a container.
* Spacing — Use the margin + padding for spacing. If 2 buttons are side by side, don’t put a blank label in-between them to create space.
** In contrast, swing uses glue — http://docs.oracle.com/javase/tutorial/uiswing/layout/box.html#filler

http://wpftutorial.net/LayoutProperties.html has good pointers too —

– height/width — All controls provide a Height and Width but don’t fixed sizing.
** Set the Width and Height of elements to Auto whenever possible.
** For precise control, use the MinHeight, MaxHeight, MinWidth and MaxWidth properties to define a acceptable range.

2 frontiers between swing/OS

Between the swing layer and OS layer, there are 2 interactions “channels”. In other words, swing relies on 2 services provided by
the “hotel service desk” that’s the OS.

A: upward -> screen update, targetting a particular screen object
B: downward -> keyboard/mouse events when user interacts with a screen object

In both domains, data/events are bound to individual screen/visual objects. Eech screen object maps to one (or more) swing object + one (or more) native object “protected” by the OS. Remember OS is the wrapper layer on top of hardware, and all access to hardware must go through the OS.

You encounter low-level details when digging into either of the 2 domains
A: painting, java 2D, UI delegates
B: event pumping, low-level vs semantic events.

Multicast delegate in c# (+AWT), briefly

cf swing AWTEventMulticaster …
———
All c# delegate types are multicast. The word “multicast” is /superfluous/redundant/, just like Reentrant in ReentrantLock. You can similarly say silly things like “Secure SSL”, or “Reliable TCP”.

According to http://msdn.microsoft.com/en-us/library/system.multicastdelegate.aspx, a MulticastDelegate has a linked list of delegates, known as an invocation list. When a multicast delegate is invoked, the delegates in the invocation list are called _synchronously_ in the order in which they appear.

http://blogs.msdn.com/b/brada/archive/2004/02/05/68415.aspx says ” We abandoned the distinction between Delegate and MulticastDelegate towards the end of V1.” Even though MulticastDelegate type extend Delegate type, system will not even allow you to derive from Delegate directly. Instead, all delegates extend MulticastDelegate.

a greek’s value converges during expiration #my take

Let’s be clear what I mean — for a given greek (say, delta) of European options, regardless of which underlier, what strike or expiration month, the value of that greek tends to move towards predictable levels as we approach expiration.

Well before expiration, a greek is like a real-value variable which could take on any numerical value within a range. However, during the last days, BS formula predicts that a greek’s value (say delta) always gravitates towards some well-defined convergence points.

delta — either 1.0 or 0 (negative for puts). However, if underlier spot price fluctuates around my strike level (IF you remain very close to ATM), then I’m switching sides between ITM and OTM, so my delta would swing wildly between the 2 convergence 1.0 and 0.

gamma — either infinity or zero. ATM (IF you remain very close to ATM) would go to positive infinity gamma (for long positions); deep ITM/OTM go to zero gamma. However in the last moments there’s no point talking about infinity or zero gamma. If in the last minute spot is still changing around your strike level, then you basically close your eyes and wait to see if you finish ITM or OTM. Even if you finish ITM, the payoff would be a small [1] percentage of strike, and probably a small percentage of premium.

[1] unless you have a Binary option. If you finish ITM with a binary option, you effective win a million dollar bet.

theta — either infinity or zero. Similar to gamma, ATM would go to negative infinity theta; deep ITM/OTM go to zero theta.

option valuation — either $0 or stock price.

jcomponent / listener / event, another analysis

http://docs.oracle.com/javase/tutorial/uiswing/events/eventsandcomponents.html shows which (type of) listener can attach to which

(type of) jcomponent. It leaves out the 3rd vital element — the (type of) event. The relationship of the 3 entities is central to

Swing.

An AWTEvent is an object containing data about some “happening”. It also “contians” a source jcomponent via getSource(). Another

important content is the type of event — mouse move, resizing, checkbox click…via getID(). An event usually comes from a

jcomponent — both user actions and code actions generate events.

When generated, the event doesn't “know” the listeners — similar to how a MOM sender generates an “unaddressed” message. Instead,

the “source” jcomponent keeps the (list of) listeners.

I sometimes prefer to discuss in terms of event-queue task (qtask) rather than events. A qtask is an event + a single listener

object. Now I feel this is educational but imprecise.

Recall a listener object is an initially stateless functor object + optional objects passed in to ctor + optional objects in the

enclosing class or enclosing method. The last group are more tricky.

Here's my hypothesis. When an event occurs,

Event object constructed

Event object euqueued

EDT picks up the event and invokes Component.processEvent(theEvent)

Inside processEvent(), each listener is invoked sequentially.

http://tech.stolsvik.com/2009/03/awt-swing-event-pumping-and-targeting.html described some of the details in a

MouseEvent.mouseClicked() example.

3 types of high-level external events – swing

An entire swing app is event driven – either 1) user events, 2) “mkt data” events, or (rarely) scheduled timer events. Without these events, entire swing app is idle.

Therefore, event handling logic permeates swing apps.

Actually “Mkt data” event is a misnomer since it can be any external data from MOM, from database response, from loading a file, from RMI response, from a web service response…

These 3 types of external events are not AWTEvents, but “happenings”. They can generate internal events, typically AWTEvents. For example, if a user event hits a JButton, the event handler in the button could fire an AWT event on a TableModel. The TableModel event handler can then modify table data and fire another event to update the screen.

Swing has a notion of low-level events vs semantic events. My 3 types are semantic.

swing propChangeListener: pass info between event generator/callback Methods

background — callback/event-handling/listener is one of the more interesting or tricky part of swing development.

Callback site can use EventObject.getSource() to find the generator Object (for a semantic event), cast to a specific type, then access its specific methods or fields. This requires prior knowledge of the exact data type of the event-generator object. That leads to tight-coupling.

A more generic solution is the PropertyChangeListener.java. This and related classes are part of java.beans package, not limited to swing. PCL is a flexible and practical solution in a wide variety of contexts beyond swing.

PropertyChangeEvent.java holds (in addition to source) propertyKeyName, oldValue and newValue fields.
Any Listener class can implement the PropertyChangeListener.java interface and support a single callback method — propertyChange(PropertyChangeEvent). When the callback runs, at run-time it has access to all 4 constituents of the PropertyChangeEvent instance.

## participants in a swing event ecosystem

Some interviewer once asked me to comment on the multi-threading issues in swing. I said that’s easier to me than the chaos and entanglement passing objects between code modules. Half of that confusion relates to events.
Just to give you a taste. A lot of event listeners are inner classes so a callback method therein has handles on
* all (even private) fields of the enclosing class
* final fields of the objects pass to the listener ctor, which are implicitly saved as hidden fields of the listener INSTANCE,
* fields of the event source object (typically a jcomponent)
* fields of the event object — PropertyChangeEvent for example

—————–
In a typical [1] swing event data flow, there are 3+1 roles
– jcomponents
– listeners — some can be jcomponents
– event objects
– event tasks
[1] in real life, the set-up is often complicated by thread, inner classes etc, so it’s important to look at simple yet realistic examples.
Now, many of these roles are simple only conceptually — actual object-graph is a bit complicated.
Jcomponent is the most Concrete thing among these mysterious creatures. Jcomponents can be an event source, and can optionally implement an listener interface such as ActionListener.java.
Event tasks, as described in another blog post, exists inside the JVM only, and not in java api. Each task points-to exactly one listener instance and one event object.
The listener role is tricky. In my experience, half the listeners are jcomponents, and half are non-jcomponents.
How about Action instance? I feel it is a glue-class for listener and jcomponent. See http://bigblog.tanbin.com/2009/10/abstractaction-brief-intro.html

each task instance in EventQueue has ptr to 1 listener

EventObject.java doesn’t contain a “handle” [2] on the listener INSTANCE, but look at an event-queue-task (“qtask”) in the Swing EventQueue.

EDT runs all callback methods (such as actionPerformed) sequentially [1]. So if a jtable and a jtree both listen to an event, EDT must execute the 2 callbacks sequentially.

Imagine 2 qtask INSTANCES are in EventQueue. It’s instructional to imagine a qtask having 3 handles
– on that one listener object, sometimes a jcomponent. See http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
– on the event object, which provides a handle
– on the source object, perhaps a button or table cell

Note in our simple example one source object (button) generates one event (click) at a time. Given the source maintains 2 pointers to 2 listeners, that one event object must be “delivered to” 2 listeners — 1:2 mapping.

Now the English word “deliver-to” is nice but rather vague or (worse) misleading and can permanent damage some learner’s brain. Listener is unlike some jms client process capable of processing event. Instead, Listener is typically
– a stateful object (perhaps a jcomponent) holding a handle on some RESOURCE — DB, bunch of jcomponents..
– exposing a callback like actionPerformed()

So delivery-to means “EDT executing that non-static callback method on the listener instance, passing in the event object”. This is a crucial and non-trivial data-flow worth a hard look and analysis
* Business logic is in … the method source code;
* Data is passed via …. the event object and the event source
* Resources needed to handle the message are in ….. the listener object’s non-static fields

[1] even though a callback method may dispatch the task to a worker thread or back to EDT again – by invokeLater() i.e. packing up the task into a qtask and “enqueue” to the end of the event queue.

[2] basically a reference or pointer, but it’s good to use a generic term here.

A busy live mkt-data GUI table – realistic

1000 records are batched into each chunk and posted to event queue. Every chuck needs to be displayed on a “main” table. Killer is the re-sort/re-filter, which must happen on EDT. As a result, EDT is overwhelmed — when you re-size or move the app, it responds, but is sluggish and leaves an ugly trail.

My suggestions –
* Break up into smaller tables, so sorting is faster.
* Break up into smaller datasets. In fact most users are only interested in a subset of the live data.
* If sort (filter) is the killer….
… adopt a a sort-free JTable that efficiently accesses pre-sorted underlying data. Underlying data can be swapped in/out efficiently, and sorted on a “mirror-site” using another thread, possibly a swing worker. Take inspiration from the 2 GC survivor spaces and use 2 identical data structures. One live, the other used as a sort worktable. Swap (by pointer) and fire table event. However this increase memory consumption.

We also need to completely disable user-triggered sorts. Use a dialog box to educate users that changing sorting policy is non-trivial, and they should configure and install the new sorting policy and be prepared to wait a while to see its effect.

In general, you can only get any 2 of
E) cell editing
R) real time view of fast changing mkt data
C) full rather than subset of data streams

In mkt data streaming,  R alone is often enough — read-only view. Some users needs R+C. Some needs E+R

wpf/swing – invite EDT to query the model and update screen

In Swing, You can never change the screen directly — You always “invite” the EDT (or the UI thread in wpf)  to asynchronously query the model and update the screen.

I guess this is a golden rule in wpf and swing, at least for the mainstream visual components with a model/view.

If my custom method synchronously updates a visual component, then this method must always be on the EDT.

In WPF, How about listBox1.Items.Add(..)? I guess this is editing the Model or ViewModel, not the View. I guess screen is updated upon invitation.

(Asked Neeraj…)

##design patterns in my own code

— Ranked by real value and power —
producer/consumer – swing, thread pool, MOM, and almost anything synchronous
MVC
observer/listener/callback
template method
proxy – dynamic or static
visitor
factory
builder
Dependency injection
command — stateful timer task
strategy
singleton — the strict ones are less useful.
decorator
DTO
DAO
adapter ie wrapper

— other patterns I like —
RAII
pimpl
bridge

— patterns I don’t apply in my own code —
facade
iterators
service locator
chain of responsibilityflyweight
memento
state

row sorter – swing fundamentals #my take

A row sorter instance holds
1) an all-important “row index” mapping, somewhat similar to the “col index” translator in TableColumnModel,
2) the list of sort keys

The row sorter updates the mapping whenever underlying content changes or sort key list changes. Javadoc says “RowSorter’s primary role is to provide a mapping between two coordinate systems: that of the view (for example a JTable) and that of the underlying data source, typically a model.

One sorter has multiple sort keys.
One sorter covers all the columns — all potential sort columns

public List getSortKeys() – returns the current sort key list
public setSortKeys()

RowSorter need to reference a TableModel. JTable also have a reference to the model. RowSorter should not install a listener on the model. Instead the view class will get model events, and then call into the RowSorter. For example, if a row is updated in a TableModel, JTable gets notified via the EDT event queue then invokes sorter.rowsUpdated(), which is a void method. The rowsUpdated() internally refreshes row sorter’s internal mapping. I believe after this method returns JTable would query row sorter to re-display the rows in the new order.

Because the view makes extensive use of the convertRowIndexToModel() and convertRowIndexToView(), these methods need to be fast.

When you click a header, mouse click handler calls into the sorter’s instance method toggleSortOrder() to
1) change sort key list,
2) then update internal mapping

tunnel^bubble routed events, first look

Routed events have a bit of theory behind it. Routing theory perhaps?

One of the (top 3?) essential jobs of xaml is linking up the GUI event handlers. These event handlers are essential and found in every GUI toolkit. WPF event handlers are often implemented as instance methods in the xaml class. The xaml xml can specify a handler method by unqualified method name like a bare-word.

A bit of history on the “event” concept. In swing and other GUI, an event instance is a single occurrence of a … say a button click (or mouse-over or a special key combination). In dotnet, an event is conceptually a (usually non-static) field holding a functor. In GUI, such an event often points to an instance method of the xaml class behind the xaml. So I feel in a dotnet gui an event in a xaml screen is like “a specific type of user action”, like a click on ButtonA. WPF uses a supercharged kind of event, built on top of the CLR event. We are talking about routed event.

To understand routed event, we better bear in mind that a xaml defines a screen, built with a tree of visuals in a containment hierarchy. Such a hierarchy is also essential in Swing.

When a user action happens, the WPF “Hollywood” typically raises 2 routed events — 1) a tunneling version then 2) a bubbling version. Tunneling events are named Preview_*, and designed to fire before the bubbling event. [[illustrated wpf]] shows a simple example. Upon a click, first the tunnel event hits outer container, then the inner image, and then a second event, the bubble event, hits the inner image then the outer container. Both the inner and outer visual object define event handlers for the click, adding up to 4 event handler methods in the code behind. Therefore we we see 4 log messages.

This is all standard behavior of “Hollywood”. It provides flexibility that you can opt out. You can disable any of the 4 event handlers, and an earlier tunneling event handler can stop the propagation of the tunneling event (ditto bubble), but often you want to give outermost container the first chance to react, before the children. “This gives the container the power to see an event before its children“, as someone pointed out on http://stackoverflow.com/questions/1107922/wpf-routed-events-tunneling-and-bubbling. Here’s my sound byte –

    In the preview (tunneling) phase, container gets the preview before the children

gemfire notification event types — 2+1

2 basic event types — RegionEvent and EntryEvent, are changes to a region or a data entry. Both extend CacheEvent interface.

1) The EntryEvent object contains information about an event affecting a data entry, including the key, the value before this event, and the value afterwards. Similar to a swing PropertyChange —  http://bigblog.tanbin.com/2012/03/how-to-pass-info-between-event.html

2) RegionEvent object provides information about operations that affect the whole region

3) CqEvent ie continuousQueryEvent — see other posts.
Warning — All cache events are synchronous. To make them asynchronous, you can hand them off to another thread for the callback. RoleEvent, TransactionEvent, BridgeEvent, GatewayEvent are less common.

bond price vs interest-rate swings, again

http://faculty.weatherhead.case.edu/ritchken/documents/Chap_9.pdf says

“As interest rates increase, bond prices[1] decline while the returns [2] from reinvested coupon receipts increase.”

The effect of 1 and 2 are for different reasons.

[1] bond sellers are *forced* to discount their bonds more deeply. Inflation (as indicated by prevailing interest rates — libor) immediately and automatically increases the discount advertisement known as “yield”. When a seller discounts more deeply, advertised price automatically declines. If a seller doesn’t deepen the discount, no one wants to buy his bond.

[2] is due to higher interest rate when you reinvest the money in higher-interest securities including a regular CD.

tableColumn, tableColumnModel, TableModel

(Outdated. See other posts on TCM.)
Actual Table data (like numbers and string values) are stored in the table model Instance, and should not be redundantly stored in another object such as JTable instance, TCM instance or TC instance. http://www.chka.de/swing/table/TableColumnModel.html points out —

A TableColumnModel Instance holds a bunch of TableColumn Instances, ordered like they are shown in a JTable — #1 job of TCM. You can verify this observation from method “TableColumn getColumn(int)” . The method getColumns(void) actually returns an Enumeration of TC instances.

The 2nd job of a TCM Instance is the listener list. These listeners listen to column-move (and similar) events, NOT table data change events.

(A TCM instance doesn’t hold actual table data.)

In a TC (TableColumn) instance, the most important information is the model index, i.e. which column in the TM is behind this TC instance. A TC Instance holds data fields controlling the appearance of a column. You can think of a TC Instance as a table_column_view object.

(Allow me to repeat — There’s no actual table data in a TC instance.)

anctionListener Instance may(not) be a jcomponent (stateful

A) I have seen many examples where we subclass a jcomponent and implement ActionListener. See http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

B) There are also numerous (simple) examples where you create an anonymous stateless subtype of ActionListener, but do not subclass jcomponent. See http://stackoverflow.com/questions/1346978/java-using-an-actionlistener-to-call-a-function-in-another-class-on-an-object-f

I think it’s a common misconception to assume a listener is typically a jcomponent or a listener is usually separate from any jcomponent, but those are wrong thoughts.

swing action listener callback and wait/notify

Anthony,

Last month I asked “Exactly which thread calls the callback method in a Swing action listener when I click on a mouse?” I think Answer is, the EDT or “AWT event queue thread” in debugger thread listing.

This thread is started when the app starts and it waits in Object.wait() — confirmed. When you click on a button in the swing JFrame, the callback method runs in this thread. System doesn’t create a new thread to run the callback method. I think that would be too expensive since creating a new thread is not cheap. There are other fundamental reasons to run all event callbacks on EDT — see other posts in my blog.

For JMS onMessage() callback, I guess it might be similar — a single dedicated, long-running thread, not 5 new threads for 5 new messages. The volume of incoming messages is way too high if we create a new thread each time.

Next question is, what is this dedicated thread doing when there’s a long quiet period? I think it has to do a wait(), just like Swing.

Your input is welcome.

Bin

WPF EventArgs = EventObject in Swing — a message DTO

In every GUI toolkit there’s a class hierarchy of of event “value objects”. Such an object is passed into event handlers or callbacks as a function argument. In Swing it is known simply an “event” object. I feel this meaning of “event” is traditional, natural and intuitive — a data transfer object carrying a message about an occurrence.

WPF refers to such a DTO object as “EventArgs”, and user “Event” for something else. WPF turned the English word “Event” on its head and gave it a twist. The new meaning is “invitation”. When a WPF view model (or model) object fires an event, it sends out an invitation to a (or a inv-list of) registered listener, inviting them to “query me for my current state”. The listener is typically a data-bound visual component in the view

Therefore in the WPF context there are 2 slightly different meanings to the English word “event” —
– “An event pseudo field” — a list of listeners. If 2 visuals bind to a single model object, then list of 2 listeners.
– “firing event” — a single invitation sent to the listeners. You can rapid-fire 500 events in a minute[1] using the same event-pseudo-field. Each invitation will hit all the listeners.

[1] Incidentally, Such rapid-firing rate is not uncommon, because firing is often programmatic and driven by a collection.

Another analysis of a vanilla swing event listener

See also http://bigblog.tanbin.com/2011/02/deeper-look-at-swing-event-handlers.html

Case study — http://download.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

Be crystal clear about
* registration time — could happen hours before
* produce-time
* consume-time

How many threads?
– EDT is the consumer thread
– producer thread
– registration thread? less relevant. can be any thread.

Data shared among these threads at these different TIMES?
+ (singleton) jcomponent object
+ (singleton) action listener object
+ event-queue-task objects.

Before registration time, action listener is instantiated. At registration time, address of the listener object is saved in jcomponent object — like a subscriber mailing list (or spam list:)

At produce-time, system instantiates event-queue-task object (different from EventObject), injecting the jcomponent (as event source) + Listener object addresses therein, then enqueues the task object to the EDT event-queue. If 5 listeners registered, then 5 distinct task objects enqueued.

At consume-time (shortly but possibly much later [1]), EDT picks up the task object and finds the listener object, and calls listener.actionPerformed() passing in EventObjectt. As a non-static method, this CALL’s host object is the listener object but it executes on EDT. At consume-time, all instance fields of the source object (typically a jcomponent), instance fields of the listener (and, if a nested class within a jcomponent, private fields of the enclosing jcomponent) are accessible.

Listener OBJECT is often of an inner class –> Complicating. You need to be very clear that registration time and listener creation time are rather less relevant since they could be well before the event. Enclosing class’s fields all become accessible to actionPerformed().

If inner class is local, then local variables of the enclosing METHOD are also accessible, if FINAL. This last FINAL scenario is more tricky. The local vars are created at registration time but (because FINAL) remain accessible at consume-time.

[1] that’s why async always needs buffer — see http://bigblog.tanbin.com/2011/05/asynchronous-always-requires-buffer-and.html

when would table model data change show up (TableModel/EDT fusing)

Q: If on a non-EDT thread, such as a market data thread, I modify the table model beneath a “showing” (“realized”) jtable, say change text from “A” to “B”, but don’t repaint or fire table change event, when will my new text show up on screen?

A: never. I tested with a custom table model. The new text shows up only after I repaint or fire table event.

A: you must send an invitation to the EDT to re-query the table model and then repaint the visual, otherwise the visual will not update. Look at INotifyPropertyChanged in wpf.

A (from a veteran): For custom table model, we need to fire events, either cell change event or table data change event.
A (from a veteran, echoed on http://stackoverflow.com/questions/3179136/jtable-how-to-refresh-table-model-after-insert-delete-or-update-the-data): in some cases like default table model setValueAt()/addRow(), the event is fired automatically. I’d say the more common and standard procedure is to always fire events manually

Q: Will firing event involve repaint()?
A: not according to my debug test

Q: will firing the event trigger paint()?
A: yes according to my debug test. EDT runs paint().

Q2: is it safe for non-EDT thread to make state change on the table model object?
A: not sure. The only way to propagate the state change to the screen is via native screen object.
There are perhaps 4 (or more) objects involved:
– JTable instance (view-controller?)
– Model instance
– ?UI delegate object
– native screen object

We are modifying the model object, not the “real” object (whatever it is), so screen won’t update. UI delegate or native screen object are probably not directly accessible.

http://docs.oracle.com/javase/6/docs/api/javax/swing/package-summary.html#threading says “This restriction also applies to models attached to Swing components. For example, if a TableModel is attached to a JTable, the TableModel should only be modified on the event dispatching thread. If you modify the model on a separate thread you run the risk of exceptions and possible display corruption.” This seems to suggest that TableModel objects are modified by even handlers due to user actions or due to timers …

Q: when user edits a table cell, does the table model object change via an event callback or automatically without any event callback?
A: via Event callback, on EDT. My debug test show stopCellEditing(..) is invoked by Hollywood. This indirectly calls editingStopped(…), which calls setValueAt(..)

swing callback objects^methods, briefly

Note most if not all swing event handlers are objects, not mere method. (It’s common and harmless to use nested classes for the objects.) These objects are often stateless, but i feel you can carefully add state to them.

Since the EDT is the only thread running callback methods, these methods can spawn new (worker) threads to take on heavy jobs.

How many times will these callbacks run in an hour? How many threads do you want to spawn?

bond duration – learning notes

I like the official definition in http://en.wikipedia.org/wiki/Bond_duration#Definition. Each payout has a payout-date and therefore a ‘distance’ from valuation-date. (Example: 47 months from now). Weighted average of all these “distances” is the Mac Duration.

* eg: zeros aka STRIPS — one payout-date only. If distance is 4.5 years then Mac Duration is the same. Zeros have the longest duration[1]
* eg: low coupon bond maturing in 4.5 years — Weighted average means Mac duration is dominated by the principal repayment’s distance of 4.5 years. Duration is slightly shorter than that that last distance.
* eg: high coupon bond with that same maturity of 4.5. Duration is much shorter than the last distance.

[1] among bonds of the same maturity date.

“distance” is a more visual word than the “time-to-maturity” or “term-to-maturity” technical jargon. I also like the TTL or time-to-live phrase.

Now, if we receive $50 coupons five times and then $1000, we get total $1250 [2]. Q: what’s a reasonable “average-payout-date” of this $1250? Answer is the Duration.

[2] actual formula uses present value of each payout.

Now let’s see why the zero is most volatile, i.e. “this bond’s current price swings wildly with interest rate”

Key assumption: yield is roughly correlated to benchmark interest rates (such as the overnight FedFund rate), an indication of market sentiment.

For a high-yielder, larger portions (half?) of the total PresentValue come early and suffer minimal discount (discount factor close to 100%) . Remember DF and yield are subject to semi-annual compound. STRIPS have no early payouts, so the final payout must be discounted deeply due to compounding. Impact of yield change is deep.

Remember yield of 7% is always semi-annually compounded to derive DiscountFactor. See posts on DF and yield.

## swing – sources of events (brief list)

Swing supports semantic events and low-level events — http://tech.stolsvik.com/2009/03/awt-swing-event-pumping-and-targeting.html. Most of the “visible” events that litter our source code are semantic, so that’s the focus of most app-developer. However authors often include low-level events when “swing event” is mentioned in literature.

We mostly care about events on the EDT. Nothing stops a swing app from using any number of events on some independent thread unrelated to the EDT, but anything that affects the display must use EDT, unless the method is marked “thread-safe”. Here are some common sources of events.

– UI events — from mouse and keyboard. It’s possible to write many small swing apps with no other events than UI events.
– MOM events — A swing app often has MOM listeners that can fire events that affect the UI.
– timer events — Always en-queue to EDT. Often affects UI.
– property change events — example? See Action.java
– UI model change events — model is always, always attached to a UI component, so the change usually affects some UI. Additionally, a change can affect other UI components. Example? Say a table model should update jtable + some row-counter + background color to indicate new data in the jtable.k
** TableModel changes can occur due to user actions — P449 [[Java cookbook]]

Observer pattern brief notes

event object? Ignore for now. First focus on the 2 basic players

Subject and Observer HAS-A pointer to each other. (tight coupling@@ NO. Thanks to interfaces)

– Subject HAS-A reference to each observer [1] in order to send them updates.
– Observer HAS-A rcontrol linked to his subject(s) in order to subscribe/unsubscribe. Usually a field in the observer.

It seems to me that they don’t normally receive these pointers by argument-passing like

– Subject doesn’t HAS-A such pointer but receives a list of observers in notifyObserver() method. However, this way, subscription has no meaning.
– Observer doesn’t HAS-A such pointer but receives it as argument when calling subscribe().

[1] Static collection or a collection as a field in the subject object.

[[ Head First Design Patterns ]] is good. Helps me internalize
– registration
– data passing during notification

–Usage@@ I think most (if not every) events, listeners, subscribers, publishers … take some hints from the Observer pattern.
* swing — /Intimate/ knowledge helps you chip away at swing. Events and listeners are fundamental to swing.
* java beans
* servlet — This pattern is also relevant for servlet listeners.
* threads — Observer pattern helps inter-thread communications and data sharing
* JMS, MDB @@ Confident. No need to verify

— keywords:
subject/observer
pub/sub — the observer subscribes to news published from the Subject object
listener aka observer
registration aka subscribing