Tuesday, January 31, 2012

Concurrency Utilities in JDK 1.5 (Tiger)

http://www.cs.umd.edu/class/spring2006/cmsc433/lectures/util-concurrent.pdf

a slide summarizing concurrency changes in java 1.5

w classes and enhancements

Executors, Thread Pools, and Futures
• Concurrent collections: Queues, Blocking
Queues, ConcurrentHashMap
• Locks and Conditions
• Synchronizers: Semaphores, Barriers, etc.
• Atomic Variables
Low-level compare-and-set operation
• Other enhancements
Nanosecond-granularity timing


------------------
class WebServer {
Executor pool =
Executors.newFixedThreadPool(7);
public static void main(String[] args) {
ServerSocket socket = new ServerSocket(80);
while (true) {
final Socket connection = socket.accept();
Runnable r = new Runnable() {
public void run() {
handleRequest(connection);
}
};
pool.execute(r);
}
}


compare different java Framework

http://raibledesigns.com/rd/page/publications

Tapestry 5 was... Wow. It was the effect it did to me and the other tester.
Its simplicity is amazing : its a joy to create new components (simple
POJOs with some conventions and annotation), test them and reuse
them along your application. The separation between HTML and logic is
rather good, the reload facility a must have (Wicket also have this), the
injection framework is amazing.

Tapestry
was a success for the project, but had two critical failings: 1. Backwards
compatibility 2. Documentation and project resources


Apache Tapestry 5 is even more productive than before. There's a good set of books, and a large community. Tapestry is productive. No need to stop and start your application. I like its template approach. It is not a component-based framework, so it is more close to Spring MVC and Play!
Tapestry - takes yet another approach for web development. It lets you sprinkle tapestry tags in your plain HTML, which provide the necessary logic/data. This is the second best I liked personally because I can work on HTML directly without resorting to JSPs, etc.

adapter design pattern

http://sourcemaking.com/design_patterns/adapter/java/1


Intent

  • Convert the interface of a class into another interface clients expect.
  • Adapter lets classes work together, that could not otherwise because of incompatible interfaces.

factory pattern

http://www.oodesign.com/factory-pattern.html

  • creates objects without exposing the instantiation logic to the client.
  • refers to the newly created object through a common interface


What is Virtual Memory

http://computer.howstuffworks.com/question684.htm

Virtual memory is a common part of most operating systems on desktop computers. It has become so common because it provides a big benefit for users at a very low cost.

Most computers today have something like 64 or 128 megabytes of RAM (random-access memory) available for use by the CPU (central processing unit). Often, that amount of RAM is not enough to run all of the programs that most users expect to run at once. For example, if you load the Windows operating system, an e-mail program, a Web browser and word processor into RAM simultaneously, 64 megabytes is not enough to hold it all. If there were no such thing as virtual memory, your computer would have to say, "Sorry, you cannot load any more applications. Please close an application to load a new one." With virtual memory, the computer can look for areas of RAM that have not been used recently and copy them onto thehard disk. This frees up space in RAM to load the new application. Because it does this automatically, you don't even know it is happening, and it makes your computer feel like is has unlimited RAM space even though it has only 32 megabytes installed. Because hard-disk space is so much cheaper than RAM chips, virtual memory also provides a nice economic benefit.

The area of the hard disk that stores the RAM image is called a page file. It holds pages of RAM on the hard disk, and the operating system moves data back and forth between the page file and RAM. (On a Windows machine, page files have a .SWP extension.)

Of course, the read/write speed of a hard drive is much slower than RAM, and the technology of a hard drive is not geared toward accessing small pieces of data at a time. If your system has to rely too heavily on virtual memory, you will notice a significant performance drop. The key is to have enough RAM to handle everything you tend to work on simultaneously. Then, the only time you "feel" the slowness of virtual memory is in the slight pause that occurs when you change tasks. When you have enough RAM for your needs, virtual memory works beautifully. When you don't, the operating system has to constantly swap information back and forth between RAM and the hard disk. This is called thrashing, and it can make your computer feel incredibly slow.

Database management interview questions

http://www.techinterviews.com/database-management-interview-questions

1. What is a Cartesian product? What causes it?

Expected answer:
A Cartesian product is the result of an unrestricted join of two or more tables. The result set of a three table Cartesian product will have x * y * z number of rows where x, y, z correspond to the number of rows in each table involved in the join. It is causes by specifying a table in the FROM clause without joining it to another table.

2. What is an advantage to using a stored procedure as opposed to passing an SQL query from an application.

Expected answer:
A stored procedure is pre-loaded in memory for faster execution. It allows the DBMS control of permissions for security purposes. It also eliminates the need to recompile components when minor changes occur to the database.

3. What is the difference of a LEFT JOIN and an INNER JOIN statement?

Expected answer:
A LEFT JOIN will take ALL values from the first declared table and matching values from the second declared table based on the column the join has been declared on. An INNER JOIN will take only matching values from both tables

4. When a query is sent to the database and an index is not being used, what type of execution is taking place?

Expected answer:
A table scan.

5. What are the pros and cons of using triggers?

Expected answer:
A trigger is one or more statements of SQL that are being executed in event of data modification in a table to which the trigger belongs.

Triggers enhance the security, efficiency, and standardization of databases.
Triggers can be beneficial when used:
– to check or modify values before they are actually updated or inserted in the database. This is useful if you need to transform data from the way the user sees it to some internal database format.
– to run other non-database operations coded in user-defined functions
– to update data in other tables. This is useful for maintaining relationships between data or in keeping audit trail information.
– to check against other data in the table or in other tables. This is useful to ensure data integrity when referential integrity constraints aren’t appropriate, or when table check constraints limit checking to the current table only.

6. What are the pros and cons of using stored procedures. When would you use them?

7. What are the pros and cons of using cursors? When would you use them?


database question for beginners

http://www.go4expert.com/forums/showthread.php?t=322

1. Explain the difference between a database administrator and a data administrator.

Database Administrator :- A person (or group of people) responsible for the maintenance and performance of a database and responsible for the planning, implementation, configuration, and administration of relational database management systems.

Data Administrator :- The individual or organization responsible for the specification, acquisition, and maintenance of data management software and the design, validation, and security of files or databases. The DA is in charge of the data dictionary and data model.

2. Explain the difference between an explicit and an implicit lock.

Explicit Lock :- Lock is explicitly requested for a record or table.
Implicit Lock :- Lock is implied but is not acquired

3. What is lock granularity?

There are many locks available for the database system to have like
Intent Shared, Shared, Intent exclusive, exclusive and Shared Intent exclusive.
Locking granularity refers to the size and hence the number of locks used to ensure the consistency of a database during multiple concurrent updates.

4. In general, how should the boundaries of a transaction be defined?

A transaction ensures that one or more operations execute as an atomic unit of work. If one of the operations within a transaction fails, then all of them are rolled-back so that the application is returned to its prior state. The boundaries that define a group of operations done within a single transaction.

5. Explain the meaning of the expression ACID transaction.

ACID means Atomic, Consistency, Isolation, Durability, so when any transaction happen it should be Atomic that is it should either be complete or fully incomplete. There should not be anything like Semi complete. The Database State should remain consistent after the completion of the transaction. If there are more than one Transaction then the transaction should be scheduled in such a fashion that they remain in Isolation of one another.Durability means that Once a transaction commits, its effects will persist even if there are system failures.

6. Explain the necessity of defining processing rights and responsibilities. How are such responsibilities enforced?

One of the reason to define rights is the security in the database system. If any user is allowed to define the data or alter the data then the database would just be of no use and so processing rights and responsibilities are clearly defined in any database system. The resposibilities are enforced using the table space provided by the database system.

7. Describe the advantages and disadvantages of DBMS-provided and application-provided security.

DBMS provided security :- Any database system requires you to login and then process the data depending on the rights given by the DBA to the user who has logged in. The advatage of such a system is securing the data and providing the user and the DBA the secured platform. Any user who logs in cannot do whatever he want but his role can be defined very easily. There is no major disadvantage about the DBMS provided security apart from overhead of storing the rights and priviledges about the users.

Application-provided security :- It is much similar to the DBMS provided security but the only difference is that its the duty of the programmer creating the application to provide all the seurities so that the data is not mishandled.

8. Explain how a database could be recovered via reprocessing. Why is this generally not feasible?

If we reprocess the transaction then the database can be made to come to a state where the database is consistent and so reprocessing the log can recover the database. Reprocessing is not very feasible for a very simple reason that its very costly from time point of view and requires lots of rework and many transaction are even rollback giving more and more rework.

9. Define rollback and roll forward.

Rollback :- Undoing the changes made by a transaction before it commits or to cancel any changes to a database made during the current transaction
RollForward :- Re-doing the changes made by a transaction after it commits or to overwrite the chnaged calue again to ensure consistency

10. Why is it important to write to the log before changing the database values?

The most important objective to write the log before the database is changed is if there is any need to rollback or rollforward any transaction then if the log are not present then the rollback rollforward cannot be done accurately.

Restful Web Services

http://www.ibm.com/developerworks/webservices/library/ws-restful/

  • Use HTTP methods explicitly.
  • Be stateless.
  • Expose directory structure-like URIs.
  • Transfer XML, JavaScript Object Notation (JSON), or both.

Conclusion

REST is not always the right choice. It has caught on as a way to design Web services with less dependence on proprietary middleware (for example, an application server) than the SOAP- and WSDL-based kind. And in a sense, REST is a return to the Web the way it was before the age of the big application server, through its emphasis on the early Internet standards, URI and HTTP. As you've examined in the so-called principles of RESTful interface design, XML over HTTP is a powerful interface that allows internal applications, such as Asynchronous JavaScript + XML (Ajax)-based custom user interfaces, to easily connect, address, and consume resources. In fact, the great fit between Ajax and REST has increased the amount of attention REST is getting these days.

Exposing a system's resources through a RESTful API is a flexible way to provide different kinds of applications with data formatted in a standard way. It helps to meet integration requirements that are critical to building systems where data can be easily combined (mashups) and to extend or build on a set of base, RESTful services into something much bigger. This article touches on just the basics here but hopefully in a way that has enticed you to continue exploring the subject.


http://www.xfront.com/REST-Web-Services.html




Discover the secrets of the Java Serialization API

http://java.sun.com/developer/technicalArticles/Programming/serialization/

Rule #1: The object to be persisted must implement the Serializable interface or inherit that implementation from its object hierarchy.

Rule #2: The object to be persisted must mark all nonserializable fields transient

persist the object. That is done with the java.io.ObjectOutputStream class. That class is a filter stream--it is wrapped around a lower-level byte stream (called anode stream) to handle the serialization protocol for us. Node streams can be used to write to file systems or even across sockets. That means we could easily transfer a flattened object across a network wire and have it be rebuilt on the other side!

180 fos = new FileOutputStream(filename);
190 out = new ObjectOutputStream(fos);
200 out.writeObject(time);

190 fis = new FileInputStream(filename);
200 in = new ObjectInputStream(fis);
210 time = (PersistentTime)in.readObject();

ObjectOutputStream.reset()

java.io.InvalidClassException

serialVersionUID

Saturday, January 28, 2012

Double-checked locking

http://en.wikipedia.org/wiki/Double-checked_locking

see why double-checked locking does not work, and what is the solution
volatile

volatile in java

the volatile keyword will be more useful. When multiple threads using the same variable, each thread will have its own copy of the local cache for that variable. So, when it's updating the value, it is actually updated in the local cache not in the main variable memory. The other thread which is using the same variable doesn't know anything about the values changed by the another thread. To avoid this problem, if you declare a variable as volatile, then it will not be stored in the local cache. Whenever thread are updating the values, it is updated to the main memory. So, other threads can access the updated value.

Friday, January 27, 2012

multi-threading


Thread.sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.

the sleep period can be terminated by interrupts,

Note that constructors cannot be synchronized — using the synchronized keyword with a constructor is a syntax error.

Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods. (An important exception: final fields, which cannot be modified after the object is constructed, can be safely read through non-synchronized methods, once the object is constructed) This strategy is effective, but can present problems with liveness,

Every object has an intrinsic lock associated with it. By convention, a thread that needs exclusive and consistent access to an object's fields has to acquire the object's intrinsic lock before accessing them, and then release the intrinsic lock when it's done with them. A thread is said to own the intrinsic lock between the time it has acquired the lock and released the lock. As long as a thread owns an intrinsic lock, no other thread can acquire the same lock. The other thread will block when it attempts to acquire the lock.


read this page carefully if there is no time to read everything

Locks In Synchronized Methods

When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.

You might wonder what happens when a static synchronized method is invoked, since a static method is associated with a class, not an object. In this case, the thread acquires the intrinsic lock for the Class object associated with the class. Thus access to class's static fields is controlled by a lock that's distinct from the lock for any instance of the class.

Synchronized Statements

Another way to create synchronized code is with synchronized statements. Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock:

public void addName(String name) {     synchronized(this) {         lastName = name;         nameCount++;     }     nameList.add(name); }


But a thread can acquire a lock that it already owns. Allowing a thread to acquire the same lock more than once enables reentrant synchronization.

Using volatile variables reduces the risk of memory consistency errors, because any write to avolatile variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads. What's more, it also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.
1. java 1.5 multithread concept
2. compare 1.4 vs 1.5
3. produce consumer
4. double checked locking
5.write lazy load, multithread safe, a singlton class
6. implement multiple threading pool (queue data structure, plus produce consumer)

Thursday, January 26, 2012

XML Schema

http://www.w3schools.com/schema/schema_howto.asp

An XML Schema describes the structure of an XML document.

Monday, January 23, 2012

difference between process and thread

http://stackoverflow.com/questions/200469/what-is-the-difference-between-a-process-and-a-thread

Process
Each process provides the resources needed to execute a program. A process has a virtual address space, executable code, open handles to system objects, a security context, a unique process identifier, environment variables, a priority class, minimum and maximum working set sizes, and at least one thread of execution. Each process is started with a single thread, often called the primary thread, but can create additional threads from any of its threads.

Thread
A thread is the entity within a process that can be scheduled for execution. All threads of a process share its virtual address space and system resources. In addition, each thread maintains exception handlers, a scheduling priority, thread local storage, a unique thread identifier, and a set of structures the system will use to save the thread context until it is scheduled. The thread context includes the thread's set of machine registers, the kernel stack, a thread environment block, and a user stack in the address space of the thread's process. Threads can also have their own security context, which can be used for impersonating clients.



--

A process is a collection of code, memory, data and other resources. A thread is a sequence of code that is executed within the scope of the process. You can (usually) have multiple threads executing concurrently within the same process.

--

The major difference between threads and processes is:

  1. Threads share the address space of the process that created it; processes have their own address space.
  2. Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.
  3. Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.
  4. Threads have almost no overhead; processes have considerable overhead.
  5. New threads are easily created; new processes require duplication of the parent process.
  6. Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes.
  7. Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the process; changes to the parent process does not affect child processes.

Java Multithreading examples

http://www.tutorialspoint.com/java/java_multithreading.htm

I need to define another term related to threads: process: A process consists of the memory space allocated by the operating system that can contain one or more threads. A thread cannot exist on its own; it must be a part of a process. A process remains running until all of the non-daemon threads are done executing.

Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum.


Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.

Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).


  • New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.

  • Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.

  • Waiting: Sometimes a thread transitions to the waiting state while the thread waits for another thread to perform a task.A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.

  • Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.

  • Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates.