An ExecutorService that can schedule commands to run after a given delay, or to execute periodically.

Below is a Java program to schedule a service which periodically beeps every 10seconds for one hour.

import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;

class BeeperControl {
private final static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

public static void main(String[] args){
beepForAnHour();
}

public static void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() {
System.out.println(“beep”);
}
};
final ScheduledFuture beeperHandle = scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);

scheduler.schedule(new Runnable() {
public void run() {
beeperHandle.cancel(true);
}
}, 60 * 60, SECONDS);
}
}

Java Decompiler

Posted: February 13, 2012 in Uncategorized

http://java.decompiler.free.fr/?q=jdeclipse

Click the above link.

It’s a easy to use eclipse Plugin Java Decompiler.

Life Cycle of a Trade/End-to-End

Posted: January 11, 2012 in Financials

1. Client Onboarding:
- Sign ISDA Master agreement and CSA Credit support annex.
- Collect Clients data and store in reference data.
- KYC, SPN is created.
- Collateral agreements and margins are agreed.
- Credit Rating checks are performed.
2. Trade Execution: Occurs when traders buy or sell a financial product. This may/may not involve a exchange.
3. Trade Capture/Support: The trades are input into a relevant risk management system.
4. Profile & Loss/Risk Reporting: How much money we made or lost. Realized and Unrealized profit/loss are calculated.
5. Confirmation: The details of trade are sent to clients for confirmation. It may electronic email/phone confirmations.
6. Settlement: Involes pre/actual/post settlement activities.
7. Accounting: GLRS general ledger reconcilation process is the process of reconciliating the month end ledger balances to the sub-ledger and source transaction system.

Handlers for Uncaught Exceptions
The run method of a thread cannot throw any checked exceptions, but it can be terminated by an unchecked exception. In that case, the thread dies.
However, there is no catch clause to which the exception can be propagated. Instead, just before the thread dies, the exception is passed to a handler for uncaught exceptions.

The handler must belong to a class that implements the Thread.UncaughtExceptionHandler interface.
That interface has a single method, void uncaughtException(Thread t, Throwable e)

As of JDK 5.0, you can install a handler into any thread with the setUncaughtExceptionHandler method().
You can also install a default handler for all threads with the static method setDefaultUncaughtExceptionHandler()of the Thread class.
A replacement handler might use the logging API to send reports of uncaught exceptions into a log file.

If you don’t install a default handler, the default handler is null. However, if you don’t install a handler for an individual thread, the handler is the thread’s ThreadGroup object.
The ThreadGroup class implements the Thread.UncaughtExceptionHandler interface.

Its uncaughtException method takes the following action:
1. If the thread group has a parent, then the uncaughtException method of the parent group is
called.
2. Otherwise, if the Thread.getDefaultExceptionHandler method returns a non-null handler, it is
called.

Search “Pradeep” in all the files in all sub directories from the current directory.

find . | xargs grep -s ‘Pradeep’

Search “Pradeep” in all *.txt files in all sub directories from the current directory.

Find . –name “*.txt” | xargs grep ‘Pradeep’

What is Quartz Scheduler?

Posted: November 21, 2011 in Best Practices, Technicals

What is Quartz?

Enterprise Job Scheduler

Quartz is a full-featured, open source job scheduling service that can be integrated with, or used alongside virtually any Java EE or Java SE application – from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components that may execute virtually anything you may program them to do. The Quartz Scheduler includes many enterprise-class features, such as JTA transactions and clustering.

Quartz is freely usable, licensed under the Apache 2.0 license.

http://www.quartz-scheduler.org/

SAX Parser vs DOM Parser

Posted: November 19, 2011 in Technicals, XML
SAX DOM
Both SAX and DOM are used to parse the XML document. Both has advantages and disadvantages and can be used in our programming depending on the situation.
Parses node by node Stores the entire XML document into memory before processing
Doesn’t store the XML in memory Occupies more memory
We cant insert or delete a node We can insert or delete nodes
Top to bottom traversing Traverse in any direction.
SAX is an event based parser DOM is a tree model parser
SAX is a Simple API for XML Document Object Model (DOM) API
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
doesn’t preserve comments preserves comments
SAX generally runs a little faster than DOM SAX generally runs a little faster than DOM
If we need to find a node and doesn’t need to insert or delete we can go with SAX itself otherwise DOM provided we have more memory.

Java Thread Safe Collections

Posted: November 13, 2011 in Java, Technicals

Thread Safe Collections
================
Blocking Queue
- LinkedBlockingQueue
- ArrayBlocking queue
- DelayedBlockingQueue
- PriorityBlockingQueue

ConcurrentHashMap
ConcurrentLinkedQueue
CopyOnWriteArrayList
CopyOnWriteArraySet

Because Vector and Hastable were declared as obsolete ever since JDK1.2; and ArrayList and HashMap were introduced, though they are not threadsafe; they can be externally synchronized by using synchronization wrapper

List synchArrayList = Collections.synchronizedList(new ArrayList());
Map synchHashMap = Collections.synchronizedMap(new HashMap());

However, if you want to iterate over the collection, you need to use a synchronized block:
synchronized (synchHashMap)
{
Iterator iter = synchHashMap.keySet().iterator();
while (iter.hasNext()) . . .;
}

In JDK 1.0 introduced ‘stop’ and ‘suspend’ methods. But it was deprecated in JDK 1.2.
Reasons
——
Stop: Immediately terminates the thread that calls and relinquishes the locks on all the objects that i holds. This can leave the objects in inconsistent state.
Ex: Suppose in banking applications; if the transfer thread is stopped in middle of the transfer, after the withdrawal or before the deposit; what will happen to the money? The bank is seriously damaged.
When one thread wants to stop another thread, there is no way of knowing when the later thread is safe to stop.

Suspend: Immediately blocks the thread until another thread calls the resume.
Unlike stop, suspend won’t damage objects. However, if you suspend a thread that owns a lock, then the lock is unavailable until the thread is resumed. If the thread that calls the suspend method tries to acquire the same lock, then the program deadlocks: The suspended thread waits to be resumed, and
the suspending thread waits for the lock.

Read/Write Locks
The java.util.concurrent.locks package defines two lock classes, the ReentrantLock that we already discussed and the ReentrantReadWriteLock class. The latter is useful when there are many threads that read from a data structure and fewer threads that modify it. In that situation, it makes sense to allow shared access for the readers. Of course, a writer must still have exclusive access.

Here are the steps that are necessary to use read/write locks:

1. Construct a ReentrantReadWriteLock object:
private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
2. Extract read and write locks:
private Lock readLock = rwl.readLock();
private Lock writeLock = rwl.writeLock();
3. Use the read lock in all accessors:
public double getTotalBalance()
{
readLock.lock();
try { . . . }
finally { readLock.unlock(); }
}
4. Use the write lock in all mutators:
public void transfer(. . .)
{
writeLock.lock();
try { . . . }
finally { writeLock.unlock(); }
}