Async query (Sybase + others)

Q: What do we mean by Asynchronous query or Asynchronous DB connection?

A: Best answer, based on http://search.cpan.org/~mewp/sybperl-2.18/CTlib/CTlib.pm:
The Sybase API knows about 1) synchronous (ie blocking, the default), 2) deferred IO (polling) and 3) async IO (call-back) modes. In the synchronous mode database requests block(see below) until a response is available. In deferred IO mode database requests return immediately (with a return code of CS_PENDING), and you check for completion with the ct_poll() call. In async IO mode the API uses a completion callback to notify the application of pending data for async operations.

—– blocking ^ polling in Sybase and other databases, based on http://orafaq.com/maillist/oracle-l/2000/07/19/2071.htm:

Asynchronous connection to a database means that multiple commands can be passed to the database server and processed simultaneously. For example, there is no need to wait for the query to return before sending another command to the database server.

Instead of waiting for a “Finished” message to be sent back from the database server, the calling application sends a query status message to the database server at set times asking “Are you done yet?” (polling) When the database server says “Yes”, the result packets start coming back.

Client can send 2 signals to server
* a periodic status check — “my query is completed and ready for download?”
* a cancel

—– polling ^ call-back, based on http://search.cpan.org/~mewp/sybperl-2.18/CTlib/CTlib.pm:

To enable fully async mode, you need to have your completion callback Perl-subroutine registered, and you need to also enable async notifications, as well as setting up a timeout for requests.

Your completion callback perl-subroutine is either invoked when ct_poll() is notified of a request completion, or by the OpenClient API directly in full async mode.

Advertisements

Collection.java ^ Collections.java methods

Collections.java static methods are just like Math.java static methods.

Collection.java interface methods are more “widely” used, as they must be implemented by all Collection subtypes. Maps are NOT subtypes.

* size() is a Collection interface method. Now you know ArrayList isn’t using the word “length”, as this name wouldn’t fit Sets.
– – > “length” is used for arrays as in my_array.length == 7621
* add(Object) can’t be used for Maps
* The overloaded toArray() can’t be used for Maps

INCLUDE <jsp:include> <c:import>

The 2 common alternatives are INCLUDE and .

, defined in jstl-core, is less common.

To memorize the key difference among the 3 alternatives, #1 thing to remember is

” is in the middle ground”

reads content from arbitrary URL (vs which is restricted to the jvm)
* Insert into page
* Store in variable

sql iview4fin job

Q: benefits of relational model
q: benefits of views
q: materialized views?
q: how do u go about tuning a slow sql
q: tuning tools?
q: clustered index
q: types of indexes
q: how do u do reports?
q: outer join?
q: sybase identity column
q: what columns2index
q: what do the normalization rules mean, conceptually?

NIO q&&a

Prerequisite: blocking. See other posts

Q: Typically, how many active clients can an NIO server support?
A: thousands for a single-thread NIO server

Q: How about traditional IO?
A: typically hundreds

Q: can we have a single-thread server in traditional IO? P221
A: no. when data is unavailable on the socket, the server thread would “block” and stop doing anything at all. Since there are no other threads to do anything either, the entire server freezes up in waiting, ignoring any events or signals or inputs.

Q: basic NIO server uses a single thread or multiple threads?
A: p 233

Q: in traditional IO, what’s the threading, session, socket … allocation?
A: each client is linked to a server socket, a thread.

Q: why traditional io supports limited number of clients?
A: threads can’t multiply infinitely. (No real limit on sockets.). P227 shows 2nd reason

Q: problem of thread pool?
A: thousands of active clients would require same size (heavy!) of thread pool!

Q: in one sentence, explain a major complexity in NIO programming. P232

hibernate n:m mapping

“name=” always means a property of THIS class
 
“table=” is necessary only for many-to-many [1] => link table required
 
[1] not the other 3 types. P632 [[ java enterprise ]]
 
Suppose the persistent object is Student.java. For a given property,
“class=” is optional if the property is declared a type (like Department) with a hbm (like Department.hbm.xml)
“class=” is required if the property is a java.util.Set => no type declared for the elements in the collection. Applicable to set-mapping.

What q[bind]means to a java socket

Both types — ServerSocket and Socket — are bound to a [1] local address:port and never a remote one. “Bind” always implies “local”.

[1] one and only 1 local address:port.

Look at the ServerSocket.bind() and Socket.bind() API.

It may help to think of a server jvm and a client jvm.

It’s possible for a socket object (in JVM) to be unbound.

crisp iview q

high volume
high availability
load-balanced
jms, hibernate, multi-threading
no ejb
WAP and web

Q: how do u make a jsp threadsafe? isThreadSafe?
A: isThreadSafe is never needed

why is single-thread-servlet deprecated?

hashtable ^ hashmap

SAX ^ DOM parsers

referential integrity

how many types of joins have you used

life cycle of a servlet

servlet listeners and filters

redirect^forward

adaptor, decorator, command patterns

multi-threaded java is everywhere

Q: In what areas must you deal with multi-threading? ranking in terms of importance
* swing is multi-threaded@@ I think so since GUI is inherently multi-threaded
* To exploit multi-processor. eg: Mansion’s T2 — 1 processor, 8 core, 32 native kernel threads
* Every java IO system

# eor
* applets are often multi-threaded@@
* Hibernate@@ I think so because each database transaction (a unit-of-work) maps to a session and a thread. See other posts
* XP: NextGen is multi-threaded
* Every servlet/JSP is by default multi-threaded
* Most database-backed java applications are multi-threaded. Every DB-connection is often used by a single thread. A db-transaction is associated with a connnection.
* I think most online transaction systems are multi-threaded, but how about before java?

Personal observations on the above scenarios:
#1 common characteristic: each thread is basically a call stack
But these threads don’t always share a lot of data
Not much deadlock worry

getRequestDispatcher() in 2 classes

 
A: There is very little difference between the ServletContext and ServletRequest versions of this method, the RequestDispatcher you get operates in exactly the same way. However, the ServletRequest method also allows you to use a path argument that is relative to the “current” resource, starting with “./Example.jsp” or “../Example.jsp”. The ServletContext getRequestDispatcher method should only be used for paths relative to the application root, starting with “/Example.jsp”.

java abstract classes +! concrete method@@

Often u make it an interface but there are a few justifications

Q: I think an interface must be public ??
A: non-public interface can be nested inside a class.

* all fields in interfaces must be public static final
* all methods in interface must be public
* #1 justification: Say you plan to add concrete methods to your abstract class. You make it abstract now (instead of interface) to forbid subtypes extending something else. Consider the nightmare — U make it an interface, a subtype extends something else, and now u want it to extend your abstract class instead …. the required change could be huge and painful.

thread-safe JSP

Q: You know “session attributes” and “application attributes” aren’t thread-safe ie 2 threads can access the same data at the same [1] time. So what do you do?

%%A: synchronize each and every single method accessing them. Do that in every servlet. See P200, 197 [[ head first servlet ]]

%%A: Now i think it’s easier to use a database. Even a careless servlet becomes safe. Databases are concurrent, even before servlets were invented.

[1] in exactly the same clock cycle if using 2 of the 32 processor threads like in Mansion’s T2000 servers

soft ref ^ weak ref, according to UBS interviewer

Both features below are meaningful only in the GC context.

Let’s say there’s a target object t1 that our soft ref or weak ref points to.

– our soft ref behaves exactly the same as a regular ref until an outofmemory exception is to be thrown. At this moment, GC wakes up, scans the heap and encounters t1. If regular-reference-count is zero, and our soft ref is the only ref, then t1 goes.

Without outofmemory condition, our soft ref behaves like a regular ref, and counts in reference-count. (Personally, i don’t feel very sure, but i trust him.)

– a weak ref never counts during reference-count. Therefore, when t1 reference-count drops to zero, t1 goes, even with all the weak references clinging on to it.

throw-away PreparedStatement +! param

%% Answer: Unimportant question. If you must know the technical answer, it's usable but not recommended
 
–based on http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html :

The main feature of a PreparedStatement object is that, unlike a Statement object, it is given an SQL statement when it is created. The advantage to this is that in most cases, this SQL statement is sent to the DBMS right away, where it is compiled(in *DBMS*). As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement SQL statement without having to compile it first.

Although PreparedStatement objects can be used for SQL statements with no parameters, you probably use them most often for SQL statements that take parameters.

sonic iview q

%%q: we thought it’s easy to migrate spring mvc (without EJB) to Weblogic web container

Q: compare spring-hibernate against struts-jsp

Q: describe queuing in zed

q: is your wapmail stateless? Is state maintained on server or client?
A: query string to carry state

q: what do u do with abandoned tasks?

[07] In java, volatile means ..

In this post we avoid when-to-use-volatile. When we say “long” we mean “long, and double, the 64bit types”.

* volatile is a field modifier
* visibility — fields marked “volatile” are never cached in a thread’s register
* Local variables (ie stack variables local to a method) are different from fields. Local variables are never shared with other threads so never need volatile modifiers

**** volatile long/double:
– is permitted by compiler
– volatile has an important atomicity effect on long/double fields
–> According to 3rd edition of the Java Language specification, declaring a long field to be volatile ensures that reads or writes to it occur atomically.
–> “Unless they are declared volatile, implementations of Java are allowed to treat assignments to long and double variables as two assignments to two variables that hold 32 bits each rather than one assignment to single variable that holds 64 bits.” — http://www.mindspring.com/~mgrand/double-checked_locking_implementation.html

**** In a nutshell, volatile helps visibility and also helps (for 64bit load/store) atomicity.
1) volatile helps visibility for all primitive fields including long and double.
1.1) longer story for reference types. There’s another blog post on this.
2) volatile’s help on atomicity is limited to 64bit field’s load and store
2.1) load/store on smaller data types are always atomic whether volatile or not. Guaranteed by the Java Memory Model.
2.2) For ANY data type, Composite read/write operations (like *=, ++ ) on volatile fields can compile but are non-atomic. A float volatile field is similar to a field of type VFloat:

final class VFloat { //from http://g.oswego.edu/dl/cpj/jmm.html and P97 [[concurrent programming in java]]
private float value;
final synchronized void set(float f) { value = f; }
final synchronized float get() { return value; }
}

One of the most frequent/important consequences of 2.2 is

Q: how to avoid another thread modifying/reading such a float variable half way through my increment?” (or another composite operation)
A: volatile can’t help. Synchronize please.

“consistent”== consistentWithReality

consistency means
* consistent with business reality
* P 39 [[ concurrent programming in java ]] object-consistency = “all fields and all fields of other objects on which they depend, possess legal, meaningful values”
* P 40: “An object is consistent if all fields obey their
invariants.”
* As in ACID, Consistent = consistent with reality . Inconcurrency can produce weird and unpredictable /state/
* our object should never “be seen in an embarrassing moment”. Our object is designed to expose its /state/ while interacting with clients

In multi-threading, Consistency covers race conditions, visibility, reorder, atomicity.

The essential protection against inconsistency is confinement including mutex. It’s like queuing up to enter a phone booth. Also known as mutex lock (including “synchronized”).

which methods to make static — FTTP perspective

Key differences between static ^ instance methods

* static methods can only access static fields and static methods of this class, but many important “members” are non-static
* “public static” methods serve as “services” to clients (and deserve public service awards). Example: Arrays.*, Collections.*, Math.*
* static methods can run before the constructor ==> Many common operations in a class must be static — main(), getInstance()
* abstract method can’t be static. See other posts for the complicated reasons.
* overriding^hiding
* “synchronized” has different meanings

2 ways to create threads

(one of the most common interview questions)
 
1) … extends Thread or a subclass
override run(), to provide the job for your thread
no other compulsory methods to implement
 
 
2) myTask implements Runnable // and becomes a “task” object. Thread^task 2-object design is the idea behind Runnable.
implement run() — the only method in Runnable
but interrupt() is not inherited from Thread.java
 
    Thread thr = new Thread(new myTask()); // “insert” the task object
    thr.start();
 

perl shift/unshift/push/pop quick intro

pop/push are more intuitive verbs. They treat an array or a list like “(0,5,2)” as a stack (eg: call stack) and operate on the RIGHT end of the stack, where the index is highest.

* In one phrase, pop/push operates on the newest element; shift/unshift on the oldest.
* In one phrase, pop/push operates on the rightmost; shift/unshift on the leftmost element.
* In one phrase, pop/push operates on the highest index, while shift/unshift on the lowest, which is zero. The highest index is both $#my_array == scalar (@my_array) -1

hibernate cache-chain = money changers

Any one of these caches ALONE can eliminate a large percentage of database disk-reads, esp. for a read-mostly database.

Analogy: a chain of money changers A, B, C…. When a customer asks A about a forex rate, A can ask B (A->B->C), or use his “last-received” data ie A’s cache.

Caching at each stage of request-processing:
A = browser cache and client site proxy, the proxy server you configure in browser
B = server-side proxy — squid, proven by –> wikipedia <–
C = page-cache — smarty, JSP (?)
D = ORM “cached objects”, at several stages — hibernate http://www.devx.com/dbzone/Article/29685/1954?pf=true . I think this is also Jing Song’s suggestion.
E = raw query output cache — weblogic
F = DB-side caches, a few stages — P446 [[ mysql stored procedure ]]

open-call in FTTP loader singleton

To prevent deadlock, we took care to adopt open-call in our synchronized singleton constructor.

Basically, our long constructor (any long constructor) tend to make calls to other objects. Eventually, one of the calls that another programmer add may invoke a method that invoke a synchronized method. Now step back and count how many locks are involved.

Some may question this is over-cautious — the class doesn’t have any other static synchronized method. But Future?

Open-call is defensive design.

hibernate self-quiz

[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 ]]

* in a element, what does the “name” attribute mean to the system? [m]
* In a element, is the “column” attribute mandatory? [m]
* what hib perf features have you used?
* how do you avoid loading up an entire database accidentally?
* on which familiar hibernate object is the Transaction api defined? [m]
* what’s the relationship between hibernate.properties ^ hibernate.cfg.xml ? [m]
* Is SELECT optional? why? P 649
* what if no WHERE? P 649
* since client objects only uses getters and setters, can we use a hashmap to hold the persistence fields?

JGC runs finalize() despite "protected"

Object class has an overridable instance method

protected void finalize()

Q: will “protected” hinder GC who will invoke finalize()?
A: “protected” was chosen for overriding/inheritance consideration only. Access modifiers do not affect GC daemon.

Q: why should GC be above the law (ie access modifiers)?
A: A possible GC behaviour — GC probably need to look into every line of bytecode to make out a reference graph. A private method suspended by yield()/wait()/after-notify() might hold a vital reference???

Encapsulation only controls object-to-object communication and collaboration

most specific signature wins#Onion,covariant,subsume

(My most advanced java OO post to date)

Q: LoginAction.java execute(HttpRequest req, HttpResponse res, ActionMapping m, supertypeOfActionForm f) allowed?
A: allowed but after lots of research still not sure if this is overriding or overloading.

http://ocw.mit.edu/NR/rdonlyres/Electrical-Engineering-and-Computer-Science/6-170Fall-2005/915D0C58-87BE-46B4-893A-42CFCA08A717/0/lec14.pdf

    2. Each method in subtype that corresponds to one in the supertype:
    requires less (has a weaker precondition)
    • there are no more “requires” clauses, and each one is no more strict than the one in the supertype method.
    • 2.1) the argument types may be supertypes of the ones in the supertype. This is called contravariance, and it feels somewhat backward, because the arguments to the subtype method are supertypes of the arguments to the supertype method. However, it makes sense, because any arguments passed to the supertype method are sure to be legal arguments to the subtype method.

    guarantees more (has a stronger postcondition)
    • there are no more exceptions %% a kind of guarantee
    • the result type may be a subtype of that of the supertype. This is called covariance: the return type of the subtype method is a subtype of the return type of the supertype method.

    Example: If A is a subtype of B, then the following would be a legal overriding: %% overloading
    Bicycle B.f(Bicycle arg); %% abstract -> compile error
    RacingBicycle A.f(Vehicle arg);
    Method B.f takes a Bicycle as its argument, but A.f can accept any Vehicle (which includes all Bicycles). Method B.f returns a Bicycle as its result, but A.f returns a RacingBicycle (which is itself a Bicycle).

In this example, subtype A satisfies IS-A, even though we question overloading vs overriding. A.f() supports the expected service. I verified this set-up in NextGen. Compiled OK. However, P 44 and P6 [[ java precisely ]] introduced the concept of subsumption and “most specific signature”. Based on my understanding, the baseclass execute() is more specific => takes precedence at compile-time method binding

The Onion rules of runtime binding apply when the overriding and overriden signatures are equally specific ie the declared argument types are 100% identical.

http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)#Java has a concise statement — “Parameter types have to be exactly the same (invariant) for method overriding, otherwise the method is overloaded with a parallel definition instead.

Notice the title says “most specific signature” instead of “signatureS”? There’s always a single “most specific signature”, possibly implemented by multiple ancestors/descendants on the inheritance tree. Look at hashCode(), equals() and toString().

(java) abstract AND …. method #unfillable dental cavity

I think java “abstract” keyword evolved from c++ pure virtual…

abstract AND synchronized @@ no idea. I think [[ java precisely ]] covers this.

abstract AND private @@ No. http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#11244

abstract AND final @@ no. can’t be implemented

— abstract AND static @@ —
No. “It is a compile-time error for a static method to be declared abstract.” http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#11246 It all boils down to runtime^compile-time binding. First, you need to really understand that static calls are resolved at compile time — based on the declared type.

In general, given any static method s() in any baseclass B redefined in any subclass C, then C.s() can never step in to help B.s(). This holds whether B.s() is abstract or concrete.

Therefore, an abstract static method is an unfillable dental /cavity/, an /unrecoverable liability/. Such a construct makes no sense.

choose index vs FTS(full table scan)

http://www.isug.com/Sybase_FAQ/ASE/section1.5.html#1.5.3 has a good story. Here’s my version of the story, perhaps less accurate.

limited RAM => can’t keep all data blocks in cache. frequent swap-out/page-out => index may point to Page 5 first, and 986 pages later, Page 5 again => same disk data-block retrieved twice => index solution may require more disk-reads than a FTS.

The simplified story above helps us focus on a small, bite-sized topic. When you feel ready, read the longer version below.

Besides, Remember index itself need to be retrieved from disk.
How to choose between index and FTS? [[ oracle sql tuning ]] and [[mysql stored procedure ]] both mention somewhere around 10% [1] as a threshold to switch to FTS.
[1] [[ oracle sql tuning ]] p 233 gives different thresholds for row-sequenced tables. Same chapters also mention the influence of parallel query.

additional space requirement of quicksort

In-place sorting like quicksort has low space requirement. O(log N) space complexity is considered low. I think it’s probably the minimum for comparison-sorts.
Iterative is an alternative to recursive. Iterative lets first call complete before starting 2nd call — no call stack. Recursive is characterized by a deep call stack (of depth log N). Think onion. Think LIFO.
For any resursive sort, you usually need O(s) space where s = stack-depth. Since most (?) well-known divide-and-conquer sorts involve log N divisions and log N nested calls, space complexity is presumably O(log N)?
Now what’s the constant factor in O(log N)? At least the number of local variables defined in the subroutine. Each call on the stack maintains that number of local variables.
“additional” means besides space for the N elements.

parts of hibernate set mapping

The set-mapping xml specifies a few things on the O and R sides. (Let’s not worry about one-many or many-many stuff for now. Focus.)
 
On the O side:
* class,
* field name
* java data type -> java.util.Set
 
 
On the R side:
* table — the “subordinate” table.
* key column
* other columns — of the table. Usually you want to retrieve all the columns to populate the objects, so no need.

pretend2b d controller – [[headfirst servlet]]

The Most vague concept is the intangible Model. (New discovery: P 741, 745 [[ servlet ]] has a simple, clear example )

One excellent starting point is a real, tangible, mapping file.

Another starting point (P733 [[ servlet ]]) is “pretend to be the contoller” and trace its steps. You will notice that mostly the controller deals with
* request obj and stuff put in there such as user inputs
* response obj containing query output
* views
* query input, query output, to be sent to the view

After these things become familiar, maybe u can then lj the interactions with the elusive Model. Maybe there’s no model. Maybe it’s just a term used by … some people. Maybe it’s well defined in GUI.

timesquare-recruiter iview

Q: LinkedList ^ ArrayList

Q: what properties of an anonymous innerclass are accessible from outside

Q: why use multiple or custom class loaders?
A:

Q: delegate pattern?
A:

Q: why we need both hashCode() and equals()?
A ( now i think): hashCode() returns a int (instead of a boolean), which is used in more ways than comparing equality. Specifically, it can be used for HashMap.

Q: How does a hashmap grow in reaction to growing content? What parameters controll how it grows?
A: something like load factor

what’s a finalizer

Q: what’s unreachable by GC
A: (I now think) a /2-pronged/ approach {ref-counting, path-from-root }. Eevery object can be monitored for reference-count. Even if ref-count >=1, it may be unreachable from root-objects.

how does the GC detect an island

what’s a mutex

what’s a race condition? how do u deal with it?

spirevision perl iview q

q: require ^ use

q: DBI statements to run a select query

q: bless?

q: how to access the 3 in $a = [1,2 [3,4]]

q: a subroutine to multiply 2 numbers, complete with error checking
biggest challenge is validating input as numbers. How about $should_be_num + 0 == $should_be_num

in-line view ^ ANSI view: SELECT from SELECT

select * from (select * …. )
NOT a sub-query. supported in oracle and mysql5
Now an ANSI standard view is very similar. Basically a saved query to be used as a fake table, a select-query to be used in FROM, ie select from select.
The starting point to learn inline view is a standard ANSI view.

I would say Oracle supports 2+1 types of views
* ANSI standard view
* materialized view — see earlier posts
* inline view — no name. query not saved with a name

CurrencyHoliday DB table

To my surprise, there’s actually a CurrencyHoliday table in the FX trading system. Traders/dealers are alerted to holidays that impact their trade’s settlement.

FX Forward traders get a calendar automatically adjusted based on this table, to show the value dates of T/N, S/N, 1m, 2m etc

The related TblCurrencyPair table holds standard lot size and settlement convension (like T+1 for CAD)

DB view quiz

q: table rows are usually unique, in a standard design, but many derived views are not. Example please?
A: if you select just 1 column.

q: why views can’t be indexed like tables?
A: no physical storage of the data

q: name an obvious headache of using “distinct” in a view definition? Name a solution.
I think sybase 15 allows it.

IS-A => subtype methods be "compatible" with supertype

In an earlier post we reasoned that a concrete method from an interface must be public. We can now extend it to all method-overriding and all method-implementation. The rules of method overriding are well-documented on the Net. I think all the rules exist due to the IS-A principle.
 
IS-A => “repeated” methods in subtypes must support the expected services of the supertype
 
If we can use a supertype remote-control to invoke method1(), then we can use a subtype, too. All the subtypes’ method1() implementations are “compatible” with the supertype’s method1(). Compatibility is defined by the 4 or 5 method-overriding rules.

domestic ccy, base ccy… jargons

Key is to view first symbol NOT as a currency but as an asset. Perhaps the best example — “XAG/CC1” means 1 ounce of silver quoted in your local currency CC1.

Asset currency” — Silver is the asset being quoted.
“Commodity currency” — ditto
“Base currency” — (Base-metal) is like the silver prices quoted on exchanges.
“Unit currency” — exactly 1.0 unit of this currency is quoted in the “contract”. This is the currency that’s not changing in the equation like
1 USD = 1.234 SGD, becoming
1 USD = 1.235 SGD

An author said “first currency is like stock in equity market”.
 
Tony pointed out the graph of CC1CC2 shows the strength of CC1 i.e. one unit of CC1 as a commodity. When CC1CC2 drops we intuitively see CC1 as weakening.

–Above are names of the first symbol; Below are names of the 2nd symbol–

“Domestic currency” — means the currency you PAY to own the silver “asset“. See warning below.
“Quote currency” — means our silver is quoted-in this currency.
“Term currency” — means the exchange rate is quoted-in Terms of this currency
“Premium currency” — means the FX option premium is quoted-in this currency

Starting from a USD inventory,
– When you buy EURUSD, you buy euro, at pip price of 1.4444
– When you sell EURUSD, you sell euro, at price of 1.4444
– When you buy USDJPY, you SELL yen (and buy USD) at 99.99

=== warning Foreign currency is like the Silver. You quote prices in xx.xxx amount of local currency. This terminology is common in literature, but I find it confusing. Inside the United States, USDJPY is traded with JPY as domestic currency!

=== first currency (i.e. base currency) is like the “silver” that you buy or sell.
pip (percentage in point) is expressed-in quote-currency. If USD/SGD is moving from 1.1234 + 1 pip to 1.1235, then that 1 pip means 1 tiny “piece” of SGD.

“Base currency” means? The currency that’s not changing in the equation like
1 USD = 1.1234 SGD, becoming
1 USD = 1.1235 SGD

If you see “2.23 DEM/GBP” price, think of it as
2.23 DEM=GBP or
2.23 DEM/GBP =1   i.e.
2.23 = GBP/DEM 

(subClassObj(superClassObj))-> onion

Best 1-word glue to tie up constructor chain-reaction, object inheritance, overriding, dynamic binding…. is onion

To drive home the concept, think of any java object as an onion. If C extends B extending A extending Object, then an C obj wraps a B obj, enclosing an A obj, containing an Object obj. There’s always an Object.java instance at the core, inside the innermost onion layer.

In the constructor call stack, C() calls B(), which calls A(), which calls Object(). The callstack looks exactly like an onion. First statement in ANY constructor is always an (implicit or explicit) call to super(). No exception.

Dynamic binding explained by Mr. Onion — If an ancestor method m() is overriden (must be non-static) by every descendant, then a call to m() binds (only at runtime, never compile-time) to the outermost onion layer, ie the most specific implementation of m(). This is regardless of what you put before “. m()” — type_a_var.m() or type_b_var.m() all binds to the m() implementation in C.java. See p 45 [[ Java precisely ]]

subclass obj always contains a superclass obj

(A letter I wrote but did not send. ) Hi Elisha,
You once told me something interesting about subclass instantiation.

Suppose concrete Class C extends concrete Class B.
Suppose B has instance variable bi and static variable bs
Suppose B has non-static method bn() and static method bm()

When we call new C(), JVM allocates a chunk of memory for the new object. What you said that surprised me is — right inside that chunk of memory, there’s a complete B object.

We know C() automatically calls B(), which allocates a chunk of memory for the new B object.

Q: is the B chunk inside the C chunk?
A: yes for C++, the derived object as the same address as the base object – post on AOB.
A: yes. I just found a DIAGRAM on http://courses.csail.mit.edu/6.170/old-www/2000-Spring/handouts/lect11/lect11.pdf

Note an Object instance is inside every java object.

php attacking java’s heartland

see other posts —
[[ %%thoughts on corporate adoption:php^java ]]

I think PHP is still lacking key enterprise features found in java (and to some extent .NET)

* the level of commitment by large vendors like BEA, Oracle, IBM,
* track record as a battle-tested strong player in large, complex projects. I can only think of wikipedia.

* OO –> see [[ php oo matching java ]]
* EAI support for a huge array of legacy enterprise systems — mainframe, ERP …
* SOA, Web Services@@ rudimentary in php
* greater transaction support, including XA.
* large non-HTTP systems like NextGen
* enterprise-scale ORM
* swing
* MQ support@@ rudimentary in php.
* OO design patterns@@ very little in PHP
* clustering
* rule engines like jrules
* declarative role-based security on a per-method level
* socket and network applications
* sophisticated unit test frameworks@@ could be developed for PHP
* portable. i think this could be one of java’s most fundamental strengths over C++.

IS-A principle => interface methods are ALL public

An earlier post asked Q: Must concrete methods be public if born in an interface?
%% A: I think so. why?

short answer: a subtype must appear a good member of the “family”, supporting all expected services. A non-public method would not support the expected service.

We call each method a “service” because the client will use it and depend on it.

long answer:

Suppose a caller method M1 calling a method M2, perhaps a factory method.
Suppose M2 returns a Company which is an interface.
Suppose M1 puts the object into a variable “company” of type Company, and calls company.payTax().

Suppose the object is actually a Shop, a subtype of Company.

Since Company.java is an Interface, java syntax dictates Company (or its ancestors) declaring payTax() as public.

Q: can Shop.java define payTax() as private?
A: no. M1, the client, would fail when calling payTax(). In fact, Shop.java would probably fail to compile if payTax() is protected, default or anything but public.
A: You break the IS-A principle — Shop no longer IS-A Company.
A: a public callable payTax() method is part of the IS-A.
A: a public callable payTax() method is part of being a Company
A: a public callable payTax() method is part of the expected services of the Company family.
A: Every subtype of Company, be it a sub-interface, abstract class or concrete class, must expose a public callable payTax(), otherwise clients will die.

A more real example: Runnable.run() is, thanks to the interface, public ==> concrete run() method is always public. Suppose you instantiate an object R implementing Runnable but with a private run(). Suppose a 3rd-party client receives this object as a Runnable type and faithfully invokes its run(). Bang! The client has to disqualify this object as a genuine Runable.

validator-rules.xml

some of the built-in-validators: required maxLength email date creditCard

* Now I think validator-rules.xml should be named built-in-validator.xml
* validator-rules.xml is a standard file you seldom need to modify.
* It configures the built-in-validators.

* root xml has a bunch of children like
* Each built-in-validator is also known as built-in-valiation-routine. Each built-in-validation-routine in the validator-rules.xml file has its own definition that is declared with a “validator” tag, which is used to assign a logical name to the routine, using the name attribute, and to specify the class and method for the routine. The routine’s logical name is used by other routines in this file as well as by validation definitions in the validation.xml file to refer to the routine.

ajax self-quiz

Some if not all answers are found in your book.

Q: describe an ajax application proxy. Created in what language? Why needed? Connects which 2 parties that can’t talk directly?

q: describe a simple xmlHttpRequest data flow starting from a onClick, going through an onreadyStateChange special-js function, with some page fragment updated. (more common than hidden frame, but not more complex)
 

j4stored procedures #sybase

Update — In a 2018 MS interview answer this same question:

Q: stored procedure vs regular query
%%A: input validation esp. for insert/update
%%A: stored proc can reduce 5,000,000 rows to 2,000 before sending them out over the wire. Contrast a join query (in a proc) vs join-emulation in application
%%A: regular query can’t create temp tables easily
%%A: data-related business logic can go into the database.
%%A: Say my proc uses first query result in a 2nd query. Clumsy with inline queries.
AA: server-side transformation can benefit from cache hits inside the (DB) server.

There are many advantages to using stored procedures (unfortunately in Sybase they do not handle the text/image types):

    • 1) Modularity (%% #1 object-oriented design principle: isolate changes => reduce impact, reduce regression test, unit test && dependency injection %%) – during application development, the application designer can concentrate on the front-end and the DB designer can concentrate on the ASE.
    • 1b) If query changes often, we hate to recompile and redeploy entire app every time — high risk. Consider extracting the inline queries into a command file, but proc is better.
    • 1c) proc can be unit-tested.
    • 1d) Independent version control.
    • 2) Security (%% consider views %%) – you can revoke access to the base tables and only allow users to access and manipulate the data via the stored procedures. Ensures all writes go through validation.
    • 4) Minimise blocks and deadlocks – it is a lot easier to handle a deadlock if the entire transaction is performed in one database request, also locks will be held for a shorter time, improving concurrency and potentially reducing the number of deadlocks. Further, it is easier to ensure that all tables are accessed in a consistent order (%% 1 of 4 deadlock conditions %%) if code is stored centrally rather than dispersed among a number of apps.
    • 4b) %% In zed I used to do mass delete and mass update, which held the lock forever. Cursor is more “nice” (unix jargon), locking and releasing a subset of rows (or just 1) at a time. Less contention and less deadlocking. %%
    • 3) Performance – stored procedures are parsed and a query plan is compiled. This information is stored in the system tables and it only has to be done once.
    • 3b) Network – if you have users who are on a WAN (slow connection) having stored procedures will improve throughput because less bytes (%% ? %%) need to flow down the wire from the client to ASE.

choosing ASA

0.3 What applications is ASA good for?

1) A major area for ASA databases is with applications that need to distribute the database with the application as a general storage area for internal components, but the database is not a major part of the deliverable.

2) ASA has excellent ODBC support, which makes it very attractive to tools oriented towards ODBC.


0.4 When would I choose ASA over ASE?

    • Ease of administration,e.g., self-tuning optimizer, db file is an OS file (not partition).
    • Lower footprint – runs on “smaller” machines.
    • Lower cost, ASA is definitely cheaper than ASE on the same platform.

materialized view

I think there are only 2 important types of views — traditional view ^ materialized view

materialized view = a db-server-side cache. Compare with mysql query cache [[ mysql stored procedures ]]

Compared to a standard view, A materialized view takes a different approach in which the query result is cached as a concrete (rather than virtual) table that is infrequently (rather than on-each-query) updated from the original base tables. This enables much more efficient access, at the cost of some data being potentially out-of-date. Whenever the underlying tables of a materialized view are updated, Oracle marks the materialized view as stale.

When a SQL query is issued, the query rewrite facility within Oracle will determine whether a suitable materialized view is available. If it is, Oracle will transparently rewrite the query to use the materialized view instead. This results in significantly improved performance since the query accesses the small set of rows in the materialized view rather than all the rows in the tables referenced by the query.

materialized view is most frequently used in data warehouse applications. Data warehousing applications also do not typically require access to real-time data.

MySQL does not provide Materialised Views by itself. But it is easy to build Materialised Views yourself.

MS SQL server has something similiar to materialized view — “indexed view”

java: static method inherited even if hidden

–I guess not inherited:
a static method m1 is tied to the super class. I think A subclass can only define another m1 to hide it.

Refer to the other post on “superclass instance inside subclass instance”. Static members are not INSIDE the onion and not inherited.

— Now I believe yes inherited:
P 22 [[ java precisely ]] says “inherits all methods … but not the constructors”
p 45 has a real example to prove that the superclass static method is still accessible even if shadowed (hidden) by a subclass static method (of the same signature, of course)