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

Thursday, March 29, 2012

what does JVM do?


  • Learn about JVM internals - what does the JVM do?

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


  • Java Programming Tutorial 2: Java Virtual Machine (JVM) : How it works

http://www.youtube.com/watch?v=aa7Y07Wv1-M



  • JVM parameters in Java

1)    JVM Options that begin with -X are non-standard (thy are not guaranteed to be supported on all JVM implementations), and are subject to change without notice in subsequent releases of the JDK.

2)    JVM Options or parameters which are specified with -XX are not stable and are not recommended for casual use.

Good knowledge of JVM options specially related to GC tuning is important for time critical application e.g. high volume low latency electronic trading platform where every micro seconds matter

1)    Boolean JVM options can be  turned on with -XX:+ and can be turned off with -XX:-.

2)    Numeric JVM Options can be set with -XX:=. Numbers can include 'm' or 'M' for megabytes, 'k' or 'K' for kilobytes, and 'g' or 'G' for gigabytes (for example, 32k is the same as 32768).

3)    String JVM options can be set by using -XX:=, and usually used to specify a file, a path, or a list of commands.




1) JVM memory options related to java heap size
Following three JVM options are used to specify initial and max heap size and thread stack size while running Java programs.

 -Xms        set initial Java heap size
 -Xmx        set maximum Java heap size
 -Xss>         set java thread stack size
 
 http://javarevisited.blogspot.com/2011/11/hotspot-jvm-options-java-examples.html

How are stack and heap organized?

Stack & Heap : Java Programming 16
http://www.youtube.com/watch?v=VQ4eZw6eVtQ&feature=related

Lecture 14 | Programming Methodology (Stanford)
http://www.youtube.com/watch?v=W8nNdNZ40EQ

how does garbage collector work? what algorithm does it use?


  • CS 61B Lecture 38: Garbage Collection

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


  • Java Programming - Garbage Collection - Video 15

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


  • Lesson3 Garbage Collection

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


  • Garbage Collection Algorithms


Historically, the heap was managed explicitly by the programming
by using allocate and release function calls in a library (such as malloc/free in C, and new/delete in
C++).  Explicit memory management has been a significant source of software bugs, and programmer
pain (for example, using memory after it has been freed, freeing it twice, or forgetting to free it at all).

With automatic memory management, a programmer can request space from
the heap (eg. by instantiating a new object with a statement like “new MyObject()” in C# and Java),
and the run-time system does the job of allocating the necessary memory and releasing it to be reused when it’s no longer needed.  Automatic memory management is easier to use and less errorprone than explicit memory management, but is also usually considered to be less efficient and less
flexible.

Automatic memory management is usually implemented by the runtime system using a family of
algorithms called “garbage collection”.  Lisp was the first widespread programming language to
adopt garbage collection in the early 60s

The basic problem of garbage collection is to identify the memory which is no-longer needed by the
application, and to make it available for other allocations

Mark-sweep
The earliest and most basic garbage collection algorithm is mark-sweep garbage collection
Mark-sweep is a “stop-theworld” collector, which means that at some point when the program requests memory and none is
available, the program is stopped and a full garbage collection is performed to free up space. In marksweep, each object has a “mark-bit” which is used during the collection process to track whether the
object has been visited.

Semi-space
Semi-space garbage collection is a copying algorithm, which means that reachable
objects are relocated from one address to another during a collection.
Available memory is divided into two equal-size regions called “from-space” and “to-space”.
When there is insufficient space in to-space to fulfill an allocation, a collection is performed.

Other variations
Compacting garbage collectors typically use an algorithm like mark-sweep, but also re-arrange the
objects to coalesce free-space to avoid fragmentation.

Generational garbage collectors are designed under the assumption that objects which are created
recently are more likely to be garbage than objects which have been alive for a long time

Incremental garbage collectors attempt to minimize the pause time incurred due to a collection, at the
expense of more overhead overall relative to stop-the-world collectors.  This typically involves doing
a little bit of the GC work at every allocation

Most high-performance modern industrial GCs (including the one in Microsoft’s Common Language
Runtime) are generational mark-sweep compacting collectors, with an optional concurrent mode for
low-latency applications.

http://www.cs.washington.edu/education/courses/csep521/07wi/prj/rick.pdf




  • Summary on Garbage collection in Java

1) Java Heap is divided into three generation for sake of garbage collection. These are young generation, tenured or old generation and Perm area.
2) New objects are created into young generation and subsequently moved to old generation.
3) String pool is created in Perm area of Heap, garbage collection can occur in perm space but depends upon JVM to JVM.
4) Minor garbage collection is used to move object from Eden space to Survivor 1 and Survivor 2 space and Major collection is used to move object from young to tenured generation.
5) Whenever Major garbage collection occurs application threads stops during that period which will reduce application’s performance and throughput.
6) There are few performance improvement has been applied in garbage collection in java 6 and we usually use JRE 1.6.20 for running our application.
7) JVM command line options –Xmx and -Xms is used to setup starting and max size for Java Heap. Ideal ratio of this parameter is either 1:1 or 1:1.5 based upon my experience for example you can have either both –Xmx and –Xms as 1GB or –Xms 1.2 GB and 1.8 GB.
8) There is no manual way of doing garbage collection in Java

http://javarevisited.blogspot.com/2011/04/garbage-collection-in-java.html#ixzz29y2yGnJQ

Tuesday, March 27, 2012

network quiz exam solutions

Jackson State University Department of Computer Science
CSC 435 Computer Networks Spring 2012
http://www.jsums.edu/cms/tues/html/CSC435-Spring2012.html

ECE 3076 Computer Communications
http://www.csc.gatech.edu/~copeland/3076/quizzes/index.html

TCP/IP Protocol Suite,
http://highered.mcgraw-hill.com/sites/0072967722/student_view0/chapter_1_quiz.html

Newton's method

In numerical analysis, Newton's method (also known as the Newton–Raphson method), named after Isaac Newton and Joseph Raphson, is a method for finding successively better approximations to the roots (or zeroes) of a real-valued function


Applications

Minimization and maximization problems

Newton's method can be used to find a minimum or maximum of a function. The derivative is zero at a minimum or maximum, so minima and maxima can be found by applying Newton's method to the derivative


Examples
Consider the problem of finding the square root of a number. There are many methods of computing square roots, and Newton's method is one.
For example, if one wishes to find the square root of 612, this is equivalent to finding the solution to

http://en.wikipedia.org/wiki/Newton's_method

Newton's Method: Example
http://www.youtube.com/watch?v=0H7L1m4_qvs


Bisection methods, Newton/Raphson and comparison
Lec 6 | MIT 6.00 Introduction to Computer Science and Programming, Fall 2008
http://www.youtube.com/watch?v=hVHqs38fPe8

Newton-Raphson Method: Example
http://www.youtube.com/watch?v=lFYzdOemDj8&feature=relmfu

Newton's Method 1
http://www.youtube.com/watch?v=_MQi3WntZqQ&feature=related

4-5 Newton's Method Example I
http://www.youtube.com/watch?v=cGTc70yDG6I&feature=related

4-5 Newton's Method Example II
http://www.youtube.com/watch?v=iht6utERkZo&feature=related


Newton's Method
http://www.youtube.com/watch?v=E24zUEKqgwQ&feature=related


Newton's Method Example Excel
http://www.youtube.com/watch?v=5ZRjUdjlVoU

Newton's method in C++
http://www.youtube.com/watch?v=dfg9rVl_Tgc&feature=related


Newton's method in java
http://www.youtube.com/watch?v=BLFkHOeaVMY

binary search

  • Binary Search
Binary search relies on a divide and conquer strategy to find a value within an already-sorted collection
http://algorithms.openmymind.net/search/binarysearch.html



  • Binary search
A binary search algorithm (or binary chop) is a technique for finding a particular value in a linear array, by ruling out half of the data at each step, widely but not exclusively used in computer science.
A binary search finds the median, makes a comparison to determine whether the desired value comes before or after it, and then searches the remaining half in the same manner.
A binary search is an example of a divide and conquer algorithm (more specifically a decrease and conquer algorithm) and a dichotomic search (more at Search algorithm).
http://www.codecodex.com/wiki/Binary_search

  • Binary Search

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


  • Binary Search (recursive version)

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



  • Binary search (iterative version)

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

merge sort


  • Algorithms Lesson 3: Merge Sort

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


  • merge sort with game cards

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



  • Merge Sort Tutorial

http://www.youtube.com/watch?v=ayN8nBiqg5I&feature=related
similar to quick sory
divide and conquer strategy




  • Merge sort

Merge sort (also commonly spelled mergesort) is an O(n log n) comparison-based sorting algorithm
Merge sort is a divide and conquer algorithm

Conceptually, a merge sort works as follows
Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted).
Repeatedly Merge sublists to produce new sublists until there is only 1 sublist remaining. This will be the sorted list.

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

Saturday, March 24, 2012

Yerellik Düzeyi (Locality)

Görev isletiminin, belirli bir adres bölgesinde ne kadar süreyle kaldığı, görevin yerellik düzeyi (locality) ile açıklanır

what's trashing?

İsletim sisteminin eksik sayfa uyarılarının gerektirdiği islemlerle yoğun bir biçimde uğrasmaya baslamasına,trashing denir.

A process that is spending more time paging than executing is said to be thrashing.
http://www.cs.uic.edu/~jbell/CourseNotes/OperatingSystems/9_VirtualMemory.html

what's working set?

Working Set (WS), bir görevin, belirli bir zaman aralığı içinde, eksik sayfa uyarısı üretmeden çalısabileceği en küçük sayfa takımıdır.

what's belady anomaly?

The Belady's anomaly accurs in case of the FIFO page replacement policy in the OS.
When this FIFO is used and the number of page frames are increased in number, then the frames that are required by the program varies in a large range(due to large no of pages) as a result of this the number of page faults increases with the number of frames.

In computer storage, Belady's anomaly states that it is possible to have more page faults when increasing the number of page frames while using FIFO method of frame management. Laszlo Belady demonstrated this in 1969. Previously, it was believed that an increase in the number of page frames would always provide the same number or fewer page faults.

http://www.foddalo.com/viewtopic.php?f=18&t=277

Belady Anormalliği
Bazen bir göreve ayrılan bos sayfa sayısı artırılsa bile eksik sayfa uyarısı artabilir. Buna Belady anormalliği denir.
Çünkü, görevlere ayrılan sayfa sayısı artırılırsa, sistemde görev sayısının çok olduğu durumlarda, bellekte bos sayfa bulmak zorlasacaktır.
Görevlere aynı anda atanabilecek sayfa sayısı, genelde eksik sayfa uyarısı sayısı taban alınarak isletim sistemince belirlenir.

http://web.cs.hacettepe.edu.tr/~abc/teaching/bil324/slides/BIL324_01_6.pdf

sinav sorulari-3







http://w3.gazi.edu.tr/web/akcayol/files/JavaOrnekVize.pdf

sinav sorulari-2












http://w3.gazi.edu.tr/web/akcayol/files/JavaOrnekVize.pdf

sinav sorulari-1

Örnek 1.2.1 : 1'den 100'e kadar olan sayıların toplamını veren algoritma.
1. Toplam T, sayılar da i diye çağırılsın.
2. Başlangıçta T'nin değeri 0 ve i'nin değeri 1 olsun.
3. i'nin değerini T'ye ekle.
4. i'nin değerini 1 arttır.
5. Eğer i'nin değeri 100'den büyük değil ise 3. adıma git.
6. T'nin değerini yaz.


Aynı algoritmayı aşağıdaki gibi yazabiliriz.
1. T=0 ve i=0
2. i'nin değerini T'ye ekle.
3. i'yi 1 arttır.
4. i<101 ise 2.adıma git.
5. T'nin değerini yaz.


Örnek 1.2.3 : İki tamsayının çarpma işlemini sadece toplama işlemi kullanarak gerçekleyin.
Girdi : iki tamsayı
Çıktı : sayıların çarpımı
1. a ve b sayılarını oku
2. c =0
3. b>0 olduğu sürece tekrarla
.3.1. c=c + a
3.2. b = b-1
4. c değerini yaz ve dur


Örnek 1.2.4 : Bir tamsayının faktoriyelini hesaplayınız.
Girdi : Bir tamsayı
Çıktı : sayının faktoriyel
İlgili formul: Faktoriyel(n)=1*2*...*n
1. n değerini oku
2. F=1
3. n >1 olduğu sürece tekrarla
.3.1. F=F*n
3.2. n= n-1
4. F değerini yaz


Örnek 1.2.5 : İki tamsayının bölme işlemini sadece çıkarma işlemi kullanarak gerçekleyin. Bölüm ve kalanın ne olduğu bulunacak.
1. a ve b değerlerini oku
2. m=0
3. a>=b olduğu sürece tekrarla
3.1 a=a-b
3.2 m = m + 1
4. kalan a ve bölüm m 'yi yaz



Kaynak:
http://www.izafet.com/c-ve-c/93459-c-dili-kullanarak-bilgisayar-programlama.html#ixzz1q2jZw7WZ


Bilgisayar belle inde bulunan n x n boyutlar ndaki bir A matrisinin
transpozesini (devri ini) al p (B=AT), bunu form üzerinde matris format nda
yazd ran bir program yaz n z.

For i=1 To n
For j=1 To n
B(i,j)=A(j,i)
Next i
Next j
For i=1 To n
For j=1 To n
Print B(i,j),
Next i
Print
Next j


“notlar.txt” isimli dosyada 1. s n f ö rencilerinin Bilgisayar Programlama
dersine ait numara, ad-soyad ve 1.vize not bilgileri bulunmaktad r. Bu dosyay
kullanarak, bu ders için minimum, maksimum ve ortalama notu hesaplay p,
Picture1 nesnesine yazd ran program olu
turunuz

N=100 ‘Ö renci say s
ReDim V1(N)
For i=1 To N
Input #1, no, ad, V1(i)
Toplam=Toplam+V1(i)
Next i
Close #1
Ort=Toplam/N


Max=V1(1)
Min=V1(1)
For i=1 to N
If V1(i)>Max Then Max=V1(i)
If V1(i)
main()
{
int i,sayi,ek=100,eb=-100,ta=0, cifta=0;
double tek=0.0;
for(i=0; i<5; i++)
{
scanf("%d",&sayi);
if (sayi>eb) eb=sayi;
if (sayi
void dca(int en,int boy, int *cevre, int *alan)
{
*cevre=2*en+2*boy;
*alan=en*boy;
}
int main()
{
int en,boy,C,A;
printf ("Dikdörtgene ait en ve boyu girin :");
scanf("%d %d",&en,&boy);
dca(en,boy,&C,&A);
printf("Dikdörtgenin çevresi=%3d \n Alanı=%3d",C,A);
return 0;
}






13. Ogrenci isimli sınıfta, parametre olarak dışarıdan String ve boolean türünde değişken alan sadece bir
constructor tanımlanmıştır. Bu sınıftan bir nesne yapmak istiyoruz. Aşağıdaki seçeneklerden hangisi
doğrudur? [5 puan]
a. Ogrenci = new Ogrenci();
b. Ogr = Ogrenci(“java”, “true”);
c. Ogrenci ogr = new Ogrenci(“tobb”, false);
d. Ogrenci ogr = new Ogrenci(“true”);
e. Ogrenci ogr = Ogrenci(“tobb”, true);



http://w3.gazi.edu.tr/web/akcayol/files/JavaOrnekVize.pdf


Is memory leak possible in Java?

In any programming language, application-level memory management problems revolve around the deallocation of memory.
These problems fall into two categories:
premature deallocation (corrupted pointers) and incomplete deallocation (memory leaks).


In the case of incomplete deallocation, there are two subcases:
coding bugs and design bugs.

Coding bugs are language dependent.
In the case of C, this would involve free()ing less than was malloc()ed,
while in C++ this might involve using delete in lieu of delete[].


Design bugs, on the other hand, do not depend on the language;
instead, they involve simple programmer negligence.

In languages like C/C++, all memory management is handled by the programmer, so all of these problems can arise

the Java language and runtime together entirely eliminate the problems of corrupted pointers and code-level memory leaks.Here's how:

1-In Java, memory is allocated only to objects. There is no explicit allocation of memory, there is only the creation of new objects. (Java even treats array types as objects.)

2-The Java runtime employs a garbage collector that reclaims the memory occupied by an object once it determines that object is no longer accessible.
This automatic process makes it safe to throw away unneeded object references because the garbage collector does not collect the object if it is still needed elsewhere.
Therefore, in Java the act of letting go of unneeded references never runs the risk of deallocating memory prematurely.

3-In Java, it's easy to let go of an entire "tree" of objects by setting the reference to the tree's root to null; the garbage collector will then reclaim all the objects (unless some of the objects are needed elsewhere).
This is a lot easier than coding each of the objects' destructors to let go of its own dependencies (which is a coding-level problem with C++).


what about memory leaks caused by poor program design?
unnecessary object references originating in long-lived parts of the system prevent the garbage collector from reclaiming objects that are in fact no longer needed.
Another design flaw occurs "in the small," at the level of a faulty algorithm; the use of Collections objects in such cases will typically magnify the error.

As the technology improves, a suitably implemented JVM could help reduce the effects of such designed-in memory leaks by using the garbage collector to track object usage over time.

In conclusion: Design problems can be mitigated by letting go of object references in one's own classes as soon as one can

References:
http://www.javaworld.com/javaworld/javaqa/1999-08/04-qa-leaks.html?page=2
http://olex.openlogic.com/wazi/2009/how-to-fix-memory-leaks-in-java/



  • Actually there is not to worry about the memory leak in Java.It is handled by Garbage Collector in Java.


But sometimes if there is java.lang.OutOfMemoryError Exception , memory leak is certainly strong suspect.
IF any application eats more & more system memory and never seems to return memory back to the system untill large amount ot physical memory allocation to that application then this is the sign of memory leak.

Also there is a common problem when we register a class as an event listener without bothering to unregister when the class is no longer needed.

We can prevent memory leaks by watching for some common problems
Collection classes, such as hashtables and vectors, are common places to find the cause of a memory leak
This is particularly true if the class has been declared static and exists for the life of the application. and many times member variables of a class that point to other classes simply need to be set to null at the appropriate time.

Reference:
http://www.erpgreat.com/java/memory-leak-in-java.htm
http://stackoverflow.com/questions/6470651/creating-a-memory-leak-with-java



  • Java Memory Leak Detection with JProfiler

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


  • Java Performance - Eclipse.mp4

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



  • Intertech - Complete Java Performance Tuning Training - Part 1

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


  • Plumbr - a tool for preventing and solving Java memory leaks

http://www.youtube.com/watch?v=3p-rwnJlGMY




  • What is Memory Leak in java? 


memory leak will occur if you put too many objects on the heap, I think that most of the time it will happen when you have some kind of a data structure and you keep on filling it while not removing unneeded objects.

For example, let say I'm keeping a Hash that contains all the phones that are currently in my factory.
If I forget to remove phones that left the factory towards customers - A memory leak exists in my program, since the hash will keep on growing. This is also the place to mention that some data structures (such as hash and arraylist) are doubling their sizes when they reach some predefined factor and so I can even run out of memory before I even use the entire potential of it holding my phones...

more common example would be if you hold connections to your server and forget to close them and remove them from your connection pool

http://www.linkedin.com/groups/What-is-Memory-Leak-in-70526.S.208104654?view=&gid=70526&type=member&item=208104654&trk=eml-anet_dig-b_nd-pst_ttle-cn




  • Creating a memory leak with Java


a good way to create a true memory leak (objects inaccessible by running code but still stored in memory) in pure Java:
1-The application creates a long-running thread (or use a thread pool to leak even faster).
why application containers (like Tomcat) can leak memory like sieve if you frequently redeploy applications that happen to use ThreadLocals in any way.
(Since the application container uses Threads as described, and each time you redeploy the application a new ClassLoader is used.)

http://stackoverflow.com/questions/6470651/creating-a-memory-leak-with-java

Is http stateful or stateless?

HTTP as a protocol is stateless. In general, though, a stateless protocol can be made to act as if it were stateful, assuming you've got help from the client
This happens by arranging for the server to send the state to the client, and for the client to send it back again next time
There are three ways this happens in HTTP.
One is cookies, in which case the state is sent and returned in HTTP headers
The second is URL rewriting, in which case the state is sent as part of the response and returned as part of the request URI
The third is hidden form fields, in which the state is sent to the client as part of the response, and returned to the server as part of a form's data
(which can be in the request URI or the POST body, depending on the form's method).

Reference:
http://www.velocityreviews.com/forums/t149832-is-http-stateful-or-stateless.html

Introduction to HTTP Preview
http://www.youtube.com/watch?v=xpBpGC08f4Q

Lesson: Hypertext Transport Protocol Overview (HTTP) - Part 1
http://www.youtube.com/watch?v=iySa4zBYScE

Friday, March 23, 2012

most used tcp ports

http 80
smtp 25
ftp 21

pop3 110
https 443

What Is a MAC Address?

A Media Access Control address (MAC address) is a unique identifier assigned to network interfaces for communications on the physical network segment
The MAC address is a unique value associated with a network adapter.
MAC addresses are also known as hardware addresses or physical addresses.
They uniquely identify an adapter on a LAN

What is a subnet mask?

  • What is a subnet mask?

A subnet mask is used to divide an IP address into two parts. One part identifies the host (computer), the other part identifies the network to which it belongs.
Subnetting an IP network allows a single large network to be broken down into what appear (logically) to be several smaller ones.

Applying a subnet mask to an IP address separates network address from host address
The network bits are represented by the 1's in the mask, and the host bits are represented by 0's.
Performing a bitwise logical AND operation on the IP address with the subnet mask produces the network address.

IP: 1101 1000 . 0000 0011 . 1000 0000 . 0000 1100 (216.003.128.012)
Mask: 1111 1111 . 1111 1111 . 1111 1111 . 0000 0000 (255.255.255.000)
---------------------------------------------
1101 1000 . 0000 0011 . 1000 0000 . 0000 0000 (216.003.128.000)


Let's assume that a host has a network address of 216.3.128.0 (as shown in the example above).
Let's say that we're going to divide the network into 2 and dedicate the first half to itself, and the other half to its customers.

216 . 3 . 128 . (0000 0000) (1st half assigned to the web host)
216 . 3 . 128 . (1000 0000) (2nd half assigned to the customers)


The web host will have the subnet mask of 216.3.128.128 (/25). Now, we'll further divide the 2nd half into eight block of 16 IP addresses.

216 . 3 . 128 . (1000 0000) Customer 1 -- Gets 16 IPs (14 usable)
216 . 3 . 128 . (1001 0000) Customer 2 -- Gets 16 IPs (14 usable)
216 . 3 . 128 . (1010 0000) Customer 3 -- Gets 16 IPs (14 usable)
216 . 3 . 128 . (1011 0000) Customer 4 -- Gets 16 IPs (14 usable)
216 . 3 . 128 . (1100 0000) Customer 5 -- Gets 16 IPs (14 usable)
216 . 3 . 128 . (1101 0000) Customer 6 -- Gets 16 IPs (14 usable)
216 . 3 . 128 . (1110 0000) Customer 7 -- Gets 16 IPs (14 usable)
216 . 3 . 128 . (1111 0000) Customer 8 -- Gets 16 IPs (14 usable)
-----------------------------
255 . 255 . 255 . (1111 0000) (Subnet mask of 255.255.255.240)


http://www.iplocation.net/tools/netmask.php
http://uk.answers.yahoo.com/question/index?qid=20090308095625AALSBe3







  • Subnetting Part 1 IP Basics (Rob Bentz)



-IPV4
-IP address is 32 bits
-IP has 4 octets
-8 bits=1 octet
-IP includes network id and host id information
-network id and host id are specified by subnet mask
-Computers uses boolean AND operation to determine host and network id
-32-bit IP address is converted to 32-bit subnet mask with boolean AND operation
-this conversion with boolean AND operation reveals network id and masks the host id

CIRD tells us how many bits of ip address of subnet mask is on,in other words numerically 1

172.16.1.1/16(CIDR) "/16" means first 16 bits of subnet mask is on
255.255.0.0



  • Subnetting Part 2 The New Mask (Rob Bentz)




  • Subnetting Part 3 Subnets (Rob Bentz)




  • Subnetting Cisco CCNA -Part 1 The Magic Number


How does a router figure out how to route an incoming ip address of a pc with a subnet mask to a network?





  • Subnetting Cisco CCNA -Part 3 The Magic Number




  • Subnetting in 6 easy steps - part 1




  • Subnetting Made Easy Part 2




  • IP Addressing and Subnetting Part 3




  • How to calculate a TCPIP IPv4 subnet mask




  • How to Subnet - HD Tutorial






  • My project needs 6 subnets, but each department has different numbers of host. I have to reserve extra hosts for future growth.

I’m stuck at this part… So what are the IP’s, subnet mask, & network address?
http://webdrift.net/



  • The maximum number of hosts and subnets in a particular subnetwork is designated by a subnet mask.

A subnet mask divides an IP address into the network part and the host part by a number of ones and zeros

So we translate a subnet mask into binary form, or we can use a CIDR mask, and count the number of ones and zeros
(number-of-zeros = 32 - number-of-ones).

The network part of an address is designated by ones in the subnet mask
it means that we can change bits in this part and every time we'll get a different subnet, so the number of combinations in this part is the number of subnets

2 square number-of-ones = number-of-subnets
http://subnet-calculator.samuraj-cz.com/



  • The remaining bits after the subnet are used for addressing hosts within the subnet. In the above example the subnet mask consists of 26 bits, leaving 6 bits for the host identifier. This allows for 64 combinations (26), however the all zeros value and all ones value are reserved for the network ID and broadcast address respectively, leaving 62 addresses.

In general the number of available hosts on a subnet is 2n−2, where n is the number of bits used for the host portion of the address.


  • Rule 1

If the host bits in a given IP address are all set to '0', this is the network or subnet address.
If the host bits in a given IP address are all set to '1', this is the broadcast address (all hosts in the subnet/network are destination).

Rule 2
The formula used to calculate the number of available subnets given the specific length of network mask.

Rule 3
The formula used to calculate the number of available hosts per subnet or network given the specific network mask.

http://ciscoiseasy.blogspot.com/2010/11/lesson-29-ipv4-subnetting-rules.html





  • Subnetting Questions with Detailed Answers:


1. You work for a large communications corporation named GlobeComm which has been assigned a Class A network address. Currently, the company has 1,000 subnets in offices around the world. You want to add 100 new subnets over the next three years, and you want to allow for the largest possible number of host addresses per subnet.
http://academic.keystone.edu/cisco/documents/subnetting/SubnettingQuestionsAndAnswers.htm


Your router has the following IP address on Ethernet0: 172.16.2.1/23. Which of the following can be valid host IDs on the LAN interface attached to the router?

172.16.1.100
172.16.1.198
172.16.2.255
172.16.3.0

http://www.indiabix.com/networking/subnetting/
Solving Subnetting Questions for the Cisco CCNA - 1
What is the subnet? Easy Solution
Subnet a Network in Packet Tracer - Part1
Configure Devices in Packet Tracer - Part2
Configure Static Routes in Packet Tracer - Part3


  • Subnet Calculator is used to divide an IP network into subnetworks by calculating network address, subnet mask, broadcast address and host IP address range 
Subnet Calculator (IPv4 Only)
IP Subnet Calculator
Subnet Calculator
Subnet Calculator
Subnet Calculator
Subnet Calculator
IP Subnet Calculator
Subnet Calculator
IP Subnet Calculator
Subnetting Mastery - What is Subnetting? - Part 1 of 7

  • What are the benefits of subnetting?
Subnetting helps reduce network traffic and the size of the routing tables. It’s also a way to add security to network traffic by isolating it from the rest of the network

http://www.enterprisenetworkingplanet.com/netsysm/10-killer-interview-questions-for-network-professionals.html