Friday, March 30, 2012

stateful vs stateless EJB

Stateless Session Beans (SLSB) are not tied to one client and there is no guarantee for one client to get the same instance with each method invocation (some containers may create and destroy beans with each method invocation session, this is an implementation-specific decision, but instances are typically pooled - and I don't mention clustered environments). In other words, although stateless beans may have instance variables, these fields are not specific to one client, so don't rely on them between remote calls.

In contrast, Stateful Session Beans (SFSB) are dedicated to one client for their entire life, there is no swapping or pooling of instances (it may be evicted from memory after passivation to save resources but that's another story) and maintain conversational state. This means that the instance variables of the bean can keep data relative to the client between method invocations. And this makes possible to have interdependent method calls (changes made by one method affect subsequent method calls). Multi-step processes (a registration process, a shopping cart, a booking process...) are typical use cases for SFSB

http://stackoverflow.com/questions/2351220/stateless-and-stateful-enterprise-java-beans

Explain RMI Architecture?

Explain RMI Architecture?
Application Layer: The client and server program
Stub & Skeleton Layer: Intercepts method calls made by the client/redirects these calls to a remote RMI service.
Remote Reference Layer: Understands how to interpret and manage references made from clients to the remote service objects.
Transport layer: Based on TCP/IP connections between machines in a network. It provides basic connectivity, as well as some firewall penetration strategies.

http://www.javabeat.net/articles/113-rmi-interview-questions-1.html

marshalling vs serialization


  • Marshaling

Marshaling is process of encoding object to put them on the wire (network)
Unmarshaling is the process of decoding from the wire and placing object in the address space
RMI uses serialization (deserialization) to perform marshaling (Unmarshaling)


  • Serialization

Serialization allows objects to be converted to a sequence of bytes
The sequence of bytes can be stored in a file, database, sent to a remote machine
The sequence of bytes can be used to recreate the original object


In particular, marshaling is about getting parameters from here to there, while serialization is about copying structured data to or from a primitive form such as a byte stream. In this sense, serialization is one means to perform marshaling, usually implementing pass-by-value semantics


  • Deserializing

Recreating the object from the above generated bytes

http://www.eli.sdsu.edu/courses/spring98/cs696/notes/marsh/marsh.html

CPU Scheduling Algorithms


  • Operating Systems (CS/CPE 408) : CPU Scheduling


  • Non-Preemptive Vs Preemptive Scheduling


Non-Preemptive: Non-preemptive algorithms are designed so that once a process enters the running state(is allowed a process), it is not removed from the processor until it has completed its service time ( or it explicitly yields the processor). 

context_switch() is called only when the process terminates or blocks. 


Preemptive: Preemptive algorithms are driven by the notion of prioritized computation. The process with the highest priority should always be the one currently using the processor. If a process is currently using the processor and a new process with a higher priority enters, the ready list, the process on the processor should be removed and returned to the ready list until it is once again the highest-priority process in the system. 

context_switch() is called even when the process is running usually done via a timer interrupt



  • First In First Out (FIFO)

This is a Non-Premptive scheduling algorithm. FIFO strategy assigns priority to processes in the order in which they request the processor.The process that requests the CPU first is allocated the CPU first.When a process comes in, add its PCB to the tail of ready queue. When running process terminates, dequeue the process (PCB) at head of ready queue and run it.
Consider the example with P1=24, P2=3, P3=3

  Gantt Chart for FCFS :  0 - 24 P1 , 25 - 27 P2 , 28 - 30 P3

  Turnaround time for P1 = 24
  Turnaround time for P1 = 24 + 3
  Turnaround time for P1 = 24 + 3 + 3

  Average Turnaround time = (24*3 + 3*2 + 3*1) / 3

  In general we have (n*a + (n-1)*b + ....) / n

  If we want to minimize this, a should be the smallest, followed by b and
  so on.
Comments: While the FIFO algorithm is easy to implement, it ignores the service time request and all other criteria that may influence the performance with respect to turnaround or waiting time.

Problem: One Process can monopolize CPU

Solution: Limit the amount of time a process can run without a context switch. This time is called a time slice.




  • Round Robin

Round Robin calls for the distribution of the processing time equitably among all processes requesting the processor.Run process for one time slice, then move to back of queue. Each process gets equal share of the CPU. Most systems use some variant of this.

Problem: Round robin assumes that all processes are equally important; each receives an equal portion of the CPU. This sometimes produces bad results. Consider three processes that start at the same time and each requires three time slices to finish


  • Priority Based Scheduling

Run highest-priority processes first, use round-robin among processes of equal priority. Re-insert process in run queue behind all processes of greater or equal priority.

Problem: Priority scheduling may cause low-priority processes to starve




  • Shortest Job First

Maintain the Ready queue in order of increasing job lengths. When a job comes in, insert it in the ready queue based on its length. When current process is done, pick the one at the head of the queue and run it.

Problem: SJF minimizes the average wait time because it services small processes before it services large ones. While it minimizes average wiat time, it may penalize processes with high service time requests.



  • Multi-Level Feedback Queue

Several queues arranged in some priority order.

Each queue could have a different scheduling discipline/ time quantum.

Lower quanta for higher priorities generally.

Defined by:

# of queues
scheduling algo for each queue
when to upgrade a priority
when to demote



http://www1bpt.bridgeport.edu/sed/projects/cs503/Spring_2001/kode/os/scheduling.htm




  • CPU Scheduling Algorithms

http://www.youtube.com/watch?v=QpuFq3-fdhw&feature=related


  • CPU Scheduling

http://www.youtube.com/watch?v=5p3bAC-AX84&feature=related

Operator Precedence And Associativity


  • Operator Precedence And Associativity

http://www.youtube.com/watch?v=n_eDAzzgzkA



Two characteristics of operators determine how they will group with operands:
precedence Precedence is the priority for grouping different types of operators with their operands.
associativity Associativity is the left-to-right or right-to-left order for grouping operands to operators that have the same precedence.

For example, in the following statements, the value of 5 is assigned to both a and b because of the right-to-left associativity of the = operator. The value of c is assigned to b first, and then the value of b is assigned to a.

b = 9;
c = 5;
a = b = c;

the * and / operations are performed before the + because of precedence. Further, b is multiplied by c before it is divided by d because of associativity.

a + b * c / d

http://northstar-www.dartmouth.edu/doc/ibmcxx/en_US/doc/language/concepts/cuexppre.htm




  • Operator Precedence in Java

For example, multiplication and division have a higher precedence than addition and subtraction. Precedence rules can be overridden by explicit parentheses

Precedence Order. When two operators share an operand the operator with the higher precedence goes first. For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3 since multiplication has a higher precedence than addition.

Associativity. When two operators with the same precendence the expression is evaluated according to its associativity
For example x = y = z = 17 is treated as x = (y = (z = 17)), leaving all three variables with the value 17, since the = operator has right-to-left associativty
 72 / 2 / 3 is treated as (72 / 2) / 3 since the / operator has left-to-right associativity.

What is the result of the following code fragment? Explain.

System.out.println("1 + 2 = " + 1 + 2);
 1 + 2 = 12 and 1 + 2 = 3, respectively. If either (or both) of the operands of the + operator is a string, the other is automatically cast to a string. String concatenation and addition have the same precedence. Since they are left-associative, the operators are evaluated left-to-right.

System.out.println("1 + 2 = " + (1 + 2));
  The parentheses in the second statement ensures that the second + operator performs addition instead of string concatenation
 
 
What does the following code fragment print?
System.out.println(1 + 2 + "abc");
System.out.println("abc" + 1 + 2);
Answer: 3abc and abc12, respectively. The + operator is left associative, whether it is string concatenation or arithmetic plus.

http://introcs.cs.princeton.edu/java/11precedence/



  • Operator Precedence and Associativity

Operator precedence is why the expression 5 + 3 * 2 is calculated as 5 + (3 * 2), giving 11, and not as (5 + 3) * 2, giving 16.
We say that the multiplication operator (*) has higher "precedence" or "priority" than the addition operator (+), so the multiplication must be performed first.

Operator associativity is why the expression 8 - 3 - 2 is calculated as (8 - 3) - 2, giving 3, and and not as 8 - (3 - 2), giving 7.
We say that the subtraction operator (-) is "left associative", so the left subtraction must be performed first. When we can't decide by operator precedence alone in which order to calculate an expression, we must use associativity.


Since the operators + and - have the same precedence, and are left-associative, the following expressions are all equivalent:
x + 3 - y + 5
(x + 3) - y + 5
((x + 3) - y) + 5
((x + 3) - y + 5)

Since the operators =, += and -= have the same precedence, and are right-associative, the following expressions are all equivalent:
x = y += z -= 4
x = y += (z -= 4)
x = (y += (z -= 4))
(x = y += (z -= 4))


http://docs.roxen.com/pike/7.0/tutorial/expressions/operator_tables.xml





  • Operator associativity

In programming languages and mathematical notation, the associativity (or fixity) of an operator is a property that determines how operators of the same precedence are grouped in the absence of parentheses.

The choice of which operations to apply the operand to, is determined by the "associativity" of the operators. Operators may be left-associative (meaning the operations are grouped from the left), right-associative (meaning the operations are grouped from the right) or non-associative (meaning there is no defined grouping).

Consider the expression a ~ b ~ c.
If the operator ~ has left associativity, this expression would be interpreted as (a ~ b) ~ c and evaluated left-to-right
If the operator has right associativity, the expression would be interpreted as a ~ (b ~ c) and evaluated right-to-lef

Many programming language manuals provide a table of operator precedence and associativity

Associativity is only needed when the operators in an expression have the same precedence.
Usually + and - have the same precedence.

Consider the expression 7 - 4 + 2.
The result could be  (7 - 4) + 2 = 5
result corresponds to the case when + and - are left-associative

or 7 - (4 + 2) = 1.
+ and - are right-associative.


Usually the addition, subtraction, multiplication, and division operators are left-associative, while the exponentiation, assignment and conditional operators are right-associative.

To prevent cases where operands would be associated with two operators, or no operator at all, operators with the same precedence must have the same associativity.

A detailed example
Consider the expression 5^4^3^2. A parser reading the tokens from left to right would apply the associativity rule to a branch, because of the right-associativity of ^, in the following way:

Term 5 is read.
Nonterminal ^ is read. Node: "5^".
Term 4 is read. Node: "5^4".
Nonterminal ^ is read, triggering the right-associativity rule. Associativity decides node: "5^(4^".
Term 3 is read. Node: "5^(4^3".
Nonterminal ^ is read, triggering the re-application of the right-associativity rule. Node "5^(4^(3^".
Term 2 is read. Node "5^(4^(3^2".
No tokens to read. Apply associativity to produce parse tree "5^(4^(3^2))".

A left-associative evaluation would have resulted in the parse tree ((5^4)^3)^2


http://en.wikipedia.org/wiki/Operator_associativity

Lexical Analysis


  • Lexical Analysis

http://www.youtube.com/watch?v=B-nkdR4H530
http://www.youtube.com/watch?v=_1o9z4XIyx4




  • Lexical analysis

In computer science, lexical analysis is the process of converting a sequence of characters into a sequence of tokens
A program or function which performs lexical analysis is called a lexical analyzer, lexer, or scanner.
A lexer often exists as a single function which is called by a parser or another function.

http://en.wikipedia.org/wiki/Lexical_analysis



  • compiler phases





  • Lexical Analysis


A scanner groups input characters into tokens. For example, if the input is

x = x*(b+1);
then the scanner generates the following sequence of tokens
id(x)
=
id(x)
*
(
id(b)
+
num(1)
)
;

A typical scanner:

recognizes the keywords of the language (these are the reserved words that have a special meaning in the language, such as the word class in Java);
recognizes special characters, such as ( and ), or groups of special characters, such as := and ==;
recognizes identifiers, integers, reals, decimals, strings, etc;
ignores whitespaces (tabs and blanks) and comments;
recognizes and processes special directives (such as the #include "file" directive in C) and macros.


http://lambda.uta.edu/cse5317/notes/node6.html




How does Dijkstra's shortest path algorithm work?

http://www.youtube.com/watch?v=UG7VmPWkJmA&feature=related
http://www.youtube.com/watch?v=psg2-6-CEXg&feature=related

How does Huffman Code work?


  • How does Huffman Code work?

http://www.youtube.com/watch?v=0PahtaFK640




  • Huffman coding

In computer science and information theory, Huffman coding is an entropy encoding algorithm used for lossless data compression.
http://en.wikipedia.org/wiki/Huffman_coding



  • How does Compression Work?

There are two main types of compression methods - lossless compression and lossy compression. Huffman Tree compression is a method by which the original data can be reconstructed perfectly from the compressed data, and hence it belongs to the lossless compression family.

http://www.sfu.ca/~vwchu/howcompression.html



  • Text Compression with Huffman Coding
https://www.youtube.com/watch?v=ZdooBTdW5bM



  • A simple example of Huffman coding on a string


you need to have a basic understanding of binary tree data structure and the priority queue data structure

Let’s say we have the string “beep boop beer!” which in his actual form, occupies 1 byte of memory for each character. That means that in total, it occupies 15*8 = 120 bits of memory.

(Theoretically, in this application we’ll output to the console a string of 40 char elements of 0 and 1 representing the encoded version of the string in bits. For this to occupy 40 bits we need to convert that string directly into bits using logical bit operations which we’ll not discuss now.)

In order to obtain the code for each element depending on it’s frequency we’ll need to build a binary tree such that each leaf of the tree will contain a symbol (a character from the string). The tree will be build from the leafs to the root, meaning that the elements of least frequency will be farther from the root than the elements that are more frequent. You’ll see soon why we chose to do this.

To build the tree this way we’ll use a priority queue with a slight modification, that the element with the least priority is the most important. Meaning that the elements that are the least frequent will be the first ones we get from the queue

Firstly we calculate the frequency of each character :

we’ll create binary tree nodes for each character and we’ll introduce them in the priority queue with the frequency as priority :



http://en.nerdaholyc.com/huffman-coding-on-a-string/

Infix to Prefix Notation Conversion

http://www.youtube.com/watch?v=fUxnb5eTRS0
http://www.youtube.com/watch?v=qmGS2M6uV8g

Explain EJB , EJB Types and RMI


  • EJB 3 Introduction

http://www.youtube.com/watch?v=W-Tq93LUdMM&feature=results_video&playnext=1&list=PLCAD48825EA5D4B49

stateless means you can call stateless session bean without having previous data

statefull means each user has its own session bean so you can keep track of what's going on

If the session bean is stateless one stateless session bean can be used by many users as it does not have previous information regarding the session.

in case of stateful session bean each user can use its own session bean.



  • Enterprise Java Beans - Introduction

http://www.youtube.com/watch?v=3YwSY8joz20&feature=fvwrel

RMI is designed to invoke remote methods in remote JVMs.However effect is same as if calling a function which is local to our machine

why do we need stub and skeleton?

if we pass arguments to the same jvm by RMI we pass the arguments by reference

Does it make a sense to send memory references to another heap as above mentioned?


stub serializes objects and skeleton deserializes the objecst instead of sending one memory heap to other machine



  • Enterprise JavaBeans 


Enterprise JavaBeans (EJB) is a managed, server-side component architecture for modular construction of enterprise applications

Types of Enterprise Beans


Session Beans that can be either "Stateful", "Stateless" or "Singleton" and can be accessed via either a Local (same JVM)
or Remote (different JVM) interface or
directly without an interface, in which case local semantics apply.
All session beans support asynchronous execution for all views (local/remote/no-interface).

Message Driven Beans (also known as MDBs or Message Beans).
MDBs also support asynchronous execution, but via a messaging paradigm.

Session beans

Stateful Session Beans
Stateful Session Beans are business objects having state: that is, they keep track of which calling client they are dealing with throughout a session and thus access to the bean instance is strictly limited to only one client at a time.
Examples
    Checking out in a web store might be handled by a stateful session bean that would use its state to keep track of where the customer is in the checkout process, possibly holding locks on the items the customer is purchasing
   
Stateless Session Beans
Stateless Session Beans are business objects that do not have state associated with them. However, access to a single bean instance is still limited to only one client at a time and thus concurrent access to the bean is prohibited.
In case concurrent access to a single bean is attempted anyway the container simply routes each request to a different instance.This makes a stateless session bean automatically thread-safe  
Instance variables can be used during a single method call from a client to the bean, but the contents of those instance variables are not guaranteed to be preserved across different client method calls.
Instances of Stateless Session beans are typically pooled.
If a second client accesses a specific bean right after a method call on it made by a first client has finished, it might get the same instance.
The lack of overhead to maintain a conversation with the calling client makes them less resource-intensive than stateful beans
Examples
Sending an e-mail to customer support might be handled by a stateless bean, since this is a one-off operation and not part of a multi-step process.
Fetching multiple independent pieces of data for a website, like a list of products and the history of the current user might be handled by asynchronous methods of a session bean as well (these calls are asynchronous because they can execute in parallel that way, which potentially increases performance)

Singleton Session Beans
Singleton Session Beans are business objects having a global shared state within a JVM.
Concurrent access to the one and only bean instance can be controlled by the container (Container-managed concurrency, CMC) or by the bean itself (Bean-managed concurrency, BMC
Examples
    Loading a global daily price list that will be the same for every user might be done with a singleton session bean, since this will prevent the application having to do the same query to a database over and over again.


Message driven beans
Message Driven Beans are business objects whose execution is triggered by messages instead of by method calls.
The Message Driven Bean is used among others to provide a high level ease-of-use abstraction for the lower level JMS (Java Message Service) specification
Examples
    Sending a configuration update to multiple nodes might be done by sending a JMS message to a 'message topic' and could be handled by a Message Driven Bean listening to this topic (the message paradigm is used here, since the sender does not need to have knowledge about the amount of consumers or their location or even their exact type)
   

Entity beans (deprecated)
Previous versions of EJB also used a type of bean known as an Entity Bean.
These were distributed objects having persistent state
Beans in which their container managed the persistent state were said to be using Container-Managed Persistence (CMP), whereas beans that managed their own state were said to be using Bean-Managed Persistence (BMP)
In EJB 3.0, Entity Beans were replaced by the Java Persistence API, which was completely separated to its own specification to allow the EJB specification to focus only on the "core session bean and message-driven bean component models and their client API"

http://en.wikipedia.org/wiki/Enterprise_JavaBeans

difference between call-by-value and call-by-reference

  • Call by Reference vs. Call by Value
http://www.youtube.com/watch?v=loDpVao0Jik&feature=related

  • Java Parameter passing: call by reference and value.
http://www.youtube.com/watch?v=6IBlJNdzP9c

  • String in java is a reference data type as are all non-primitive data types
All Strings in java are objects
Strings in java are immutable thus there are many methods to manipulate strings
String contents can't be changed but replaced with methods in java


  • An Immutable Class
http://www.youtube.com/watch?v=FRjlMs5Xa3A
Immutable class can't be changed


  • 6. Confusion over passing by value, and passing by reference

This can be a frustrating problem to diagnose, because when you look at the code, you might be sure that its passing by reference, but find that its actually being passed by value. Java uses both, so you need to understand when you're passing by value, and when you're passing by reference.

When you pass a primitive data type, such as a char, int, float, or double, to a function then you are passing by value. That means that a copy of the data type is duplicated, and passed to the function. If the function chooses to modify that value, it will be modifying the copy only. Once the function finishes, and control is returned to the returning function, the "real" variable will be untouched, and no changes will have been saved. If you need to modify a primitive data type, make it a return value for a function, or wrap it inside an object.

When you pass a Java object, such as an array, a vector, or a string, to a function then you are passing by reference. Yes - a String is actually an object, not a primitive data type.  So that means that if you pass an object to a function, you are passing a reference to it, not a duplicate. Any changes you make to the object's member variables will be permanent - which can be either good or bad, depending on whether this was what you intended.

On a side note, since String contains no methods to modify its contents, you might as well be passing by value.

http://www.javacoffeebreak.com/articles/toptenerrors.html

How does RMI work in java?

Java RMI
http://www.youtube.com/watch?v=qyqqisPV5Qs&feature=related


Part 1 of 3: Simple Java RMI Tutorial
http://www.youtube.com/watch?v=ILeAeFZOkMI&feature=channel

Introduction To Java RMI - Tutorial
http://www.youtube.com/watch?v=3fq4AdaiGFA