首页 > 代码库 > JI_4

JI_4

(1) OOP and Design Patterns

(1.1) Please explain difference among class, interface and abstract class. When you would use it rather than other?

Feature

Interface

Abstract class

Multiple inheritance

A class may implement multiple interfaces.

A class may inherit only one abstract class.

Default implementation

An interface cannot provide any code, just the signature.

An abstract class can provide complete, default code and/or just the details that have to be overridden.

Access Modifiers

The only permissible access modifier is public, which is also the default one.

An abstract class can contain access modifiers for the methods and properties.

Core vs. Peripheral

Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a Movable interface.

An abstract class defines the core identity of a class and therefore it is used for objects of the same type.

Homogeneity

If various implementations only share method signatures then it is better to use Interfaces.

If various implementations are of the same kind and use common behavior or status then abstract class is better to use.

Speed

Previously used to require more time to find the actual method implementation while going through the table or interfaces of a class.

Previously used to be faster. The today’s dynamic compilation eliminates the difference.

Adding functionality (Versioning)

If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.

If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.

Fields and Constants

Only public static final field can be defined. Fields are public, static, and final by default.

An abstract class can have any fields with any modifiers.

Static methods

Static methods are not allowed. Static methods cannot be overridden because they are resolved at compile time. Official proposal for Java 7 was dropped for unforeseen complications.

Static methods are allowed.

Abstractness

The keyword “abstract” is default for all methods. Method body is not allowed.

The class must be declared with the keyword “abstract”. Abstract methods with no body must use the keyword “abstract”.

 

Nested interface = interface inside another interface or class. Example: defining the callback interface as nested.

(1.2) Please explain the overloaded, overridden methods? Constructors can be overloaded, overridden?

Overloading: picking a method signature at compile time based on the number and type of the arguments. Return type is not part of the signature and so it can’t be used to distinguish between the overloaded methods, not even in Java 7 or ever J

Overriding: picking a method implementation at run time based on the actual type of the target object. As of Java 5, the overriding implementation in subclass may return a subclass of the type returned by the overridden implementation in the super class (covariant return type).

Constructors can be overloaded.

Constructors cannot be overridden because they are not inherited. Each subclass constructor has to chain either to another constructor within the subclass or to a constructor in the superclass. No argument constructors and default constructors chain automatically to the no argument constructor of the parent.

(1.3) What is a marker interface? What is purpose? Some examples.

Marker interface is an interface with no methods. It is used to mark, that instances of the marked class support “some functionality”. The marker interface can be checked using “instanceof”.

Recently, marker interfaces are often being replaced by annotations.

Examples:

Cloneable: Discouraged. Does not contain the method clone(). Just marks that instances may be cloned. Implementers of clone() should call super.clone(). If class is not marked Cloneable, Object.clone() will throw CloneNotSupportedException.

Serializable: ObjectOutputStream, ObjectInputStream. NotSerializableException.

(1.4) Please pick any design pattern and describe it. Could you mention some usage of patterns in JDK?

Creational Patterns

Abstract Factory

  • javax.xml.parsers.DocumentBuilderFactory#newInstance()
  • javax.xml.transform.TransformerFactory#newInstance()
  • javax.xml.xpath.XPathFactory#newInstance()

Builder

  • java.lang.StringBuilder#append() (unsynchronized)
  • java.lang.StringBuffer#append() (synchronized)
  • java.nio.ByteBuffer#put() (also on CharBuffer, ShortBuffer, IntBuffer, LongBuffer, FloatBuffer and DoubleBuffer)
  • javax.swing.GroupLayout.Group#addComponent()
  • All implementations of java.lang.Appendable

Factory method

  • java.util.Calendar#getInstance()
  • java.util.ResourceBundle#getBundle()
  • java.text.NumberFormat#getInstance()
  • java.nio.charset.Charset#forName()
  • java.net.URLStreamHandlerFactory#createURLStreamHandler(String) (Returns singleton object per protocol)

Prototype

  • java.lang.Object#clone() (the class has to implement java.lang.Cloneable)

Singleton

  • java.lang.Runtime#getRuntime()
  • java.awt.Desktop#getDesktop()

Structural Patterns

Adapter

  • java.util.Arrays#asList()
  • java.io.InputStreamReader(InputStream) (returns a Reader)
  • java.io.OutputStreamWriter(OutputStream) (returns a Writer)
  • javax.xml.bind.annotation.adapters.XmlAdapter#marshal() and #unmarshal()

Bridge

  • None comes to mind yet. A fictive example would be new LinkedHashMap(LinkedHashSet<K>, List<V>) which returns an unmodifiable linked map which doesn‘t clone the items, but uses them. The java.util.Collections#newSetFromMap() and singletonXXX() methods however comes close.

Composite

  • java.awt.Container#add(Component) (practically all over Swing thus)
  • javax.faces.component.UIComponent#getChildren() (practically all over JSF UI thus)

Decorator

  • All subclasses of java.io.InputStream, OutputStream, Reader and Writer have a constructor taking an instance of same type.
  • java.util.Collections, the checkedXXX(), synchronizedXXX() and unmodifiableXXX() methods.
  • javax.servlet.http.HttpServletRequestWrapper and HttpServletResponseWrapper

Facade

  • javax.faces.context.FacesContext, it internally uses among others the abstract/interface types LifeCycle, ViewHandler, NavigationHandler and many more without that the enduser has to worry about it (which are however overrideable by injection).
  • javax.faces.context.ExternalContext, which internally uses ServletContext, HttpSession, HttpServletRequest, HttpServletResponse, etc.

Flyweight

  • java.lang.Integer#valueOf(int) (also on Boolean, Byte, Character, Short and Long)

Proxy

  • java.lang.reflect.Proxy
  • java.rmi.*, the whole API actually.

Behavioral Patterns

Chain of responsibility

  • java.util.logging.Logger#log()
  • javax.servlet.Filter#doFilter()

Command

  • All implementations of java.lang.Runnable
  • All implementations of javax.swing.Action

Interpreter

  • java.util.Pattern
  • java.text.Normalizer
  • All subclasses of java.text.Format
  • All subclasses of javax.el.ELResolver

Iterator

  • All implementations of java.util.Iterator (thus among others also java.util.Scanner!).
  • All implementations of java.util.Enumeration

Mediator

  • java.util.Timer (all scheduleXXX() methods)
  • java.util.concurrent.Executor#execute()
  • java.util.concurrent.ExecutorService (the invokeXXX() and submit() methods)
  • java.util.concurrent.ScheduledExecutorService (all scheduleXXX() methods)
  • java.lang.reflect.Method#invoke()

Memento

  • java.util.Date (the setter methods do that, Date is internally represented by a long value)
  • All implementations of java.io.Serializable
  • All implementations of javax.faces.component.StateHolder

Observer (or Publish/Subscribe)

  • java.util.Observer/java.util.Observable (rarely used in real world though)
  • All implementations of java.util.EventListener (practically all over Swing thus)
  • javax.servlet.http.HttpSessionBindingListener
  • javax.servlet.http.HttpSessionAttributeListener
  • javax.faces.event.PhaseListener

State

  • javax.faces.lifecycle.LifeCycle#execute() (controlled by FacesServlet, the behaviour is dependent on current phase (state) of JSF lifecycle)

Strategy

  • java.util.Comparator#compare(), executed by among others Collections#sort().
  • javax.servlet.http.HttpServlet, the service() and all doXXX() methods take HttpServletRequest and HttpServletResponse and the implementor has to process them (and not to get hold of them as instance variables!).
  • javax.servlet.Filter#doFilter()

Template method

  • All non-abstract methods of java.io.InputStream, java.io.OutputStream, java.io.Reader and java.io.Writer.
  • All non-abstract methods of java.util.AbstractList, java.util.AbstractSet and java.util.AbstractMap.
  • javax.servlet.http.HttpServlet, all the doXXX() methods by default sends a HTTP 405 "Method Not Allowed" error to the response. You‘re free to implement none or any of them.

Visitor

  • javax.lang.model.element.AnnotationValue and AnnotationValueVisitor
  • javax.lang.model.element.Element and ElementVisitor
  • javax.lang.model.type.TypeMirror and TypeVisitor

(1.5) What is the multiple inheritance? Have you heard the term Diamond problem? Is it possible to have multiple inheritance in Java? Could you propose some solution how to achieve it? How you would achieve class is of more types?

  • Interfaces: Java allows multiple inheritance for interfaces.
  • Composition: Composition can be used in place of inheritance. Method calls are then delegated to contained objects.

(1.6) What is the difference between deep and shallow copy?

  • Shallow copy: for example Object#clone() which is protected and requires java.lang.Cloneable
  • Deep copy: for example java.io.Serializable (implements deep copy and gracefully handles cyclic dependencies)

(1.7) What is the concept of access modifiers? How many access modifiers do we have in Java?

Class level

  • public – accessible from any package
  • (default / package private) – only accessible within the same package (private is not allowed)

Member level

Modifier

Class

Package

Subclass

World

public

Y

Y

Y

Y

protected

Y

Y

Y

N

(default / package private)

Y

Y

N

N

private

Y

N

N

N

 

(1.8) What are inner class and anonymous class? Can an anonymous class implement an interface?

  • static nested class = behaves much like an outer class (access modifiers apply, no direct access to its containing class), but is declared inside an outer class
  • non-static nested class (aka inner class) = its instance is always related to the instance of its containing class; has direct access to all members of the containing class; must not declare static members
  • anonymous class = special kind of inner class with no associated name

Every class in Java must implement and/or extend some other class (java.lang.Object by default). This applies for anonymous classes as well and the syntax for implementing and extending is identical.

(1.9) Please describe the basics of dependency injection mechanism? Can you mention some pros & cons? Do you know some frameworks implementing this? Have you used any?

Inversion of Control (Hollywood principle) = the framework calls the application code, not the other way round

Dependency Injection = The framework calls the application code and sets dependencies.

Pros:

  • reduction of boilerplate code responsible for setting up dependencies
  • configuration flexibility – changes can be done without the need of recompiling
  • facilitates writing of testable code

Cons:

  • dependency injection container is needed, and you need to configure it

Frameworks: Spring, Google Guice, Pico Container, CDI

(2) Java Core and Libraries

(2.1) What is passing by value and passing by reference, and what is the situation in Java/C?

Java is by definition pass-by-value, references to non-primitive types are passed by value.

Primitive data types: byte, short, int, long, float, double, boolean, char.

(2.2) What is serialization? What I need to do to serialize an object? How I can remove some instance property from serialization? How the transient field could be reconstructed during the de-serialization phase? Do you know some frameworks used for serialization?

  • implement java.io.Serializable
  • use OutputObjectStream#writeObject()

The keyword “transient” excludes given member variable from serialization.

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException{

 

    in.defaultReadObject();

 

    // reconstruct transient variables

 

}

 

Serialization frameworks:

  • XStream (xml and json)
  • Jackson (json)
  • SnakeYAML (yaml)
  • Kryo (binary)

(2.3) If you override the equals() method what other methods would you also need to consider and why? Why is important to override the equals() method?

You must override hashCode() in every class that overrides equals(), because equal objects must have equal hash codes.

The default implementations satisfy the contract but are often not very efficient.

  • Object#equals() = true iff identity.
  • Object#hashCode() = usually objects address converted to integer

(2.4) What do you know about Collections framework? Why do we have eg. more implementation of List interface. Provide some examples and pros/cons.

Efficiency depends on the way the collection implementation is used (fast read / slow write etc).

(2.5) What is the difference between final, finally and finalize? What do you understand by the java final keyword?

final

  • mark a variable “unchangeable” (it can be assigned at most once)
  • make a method not “overrideable”
  • make a class not “inheritable”

finally – try/catch/finally

finalize – called on an object when it is garbage collected. Nobody knows when and if it will be called.

(2.6) What is reflection API? Pros/Cons? What is the purpose?

Pros

  • Plugins
  • Class browsers, IDEs
  • Debuggers and test tools

Cons

  • Performance overhead (cannot make use of optimization)
  • Security restrictions (security manager must be present)
  • Exposure of internals (access to private members, breaks abstraction)

(2.7) Checked and Unchecked exception? What is the difference? What do you prefer in your app?

Checked exceptions

  • Recoverable conditions.
  • Inherited from java.lang.Exception.
  • We want to force the user of our API to handle the exceptional situation.
  • IOException, SQLException, DataAccessException, ClassNotFoundException, InvocationTargetException
  • They seem to be over-used in Java API. They were eliminated in C#.

Unchecked exceptions

  • Un-recoverable conditions.
  • Inherited from java.lang.RuntimeException.
  • The user of the API does not have to handle it, but they can.
  • NullPointerException, ArrayIndexOutOfBound, IllegalArgumentException, IllegalStateException, IndexOutOfBoundsException.

(2.8) What is the difference between an error and an exception?

Errors are abnormal conditions, which should not be caught.

AnnotationFormatError, AssertionError, LinkageError, VirtualMachineError, StackOverflowError.

(2.9) What is a mutable object and immutable object? Why is it important to distinguish them?

It is not possible to change state of an immutable object.

Effective Java: “Classes should be immutable unless there‘s a very good reason to make them mutable....If a class cannot be made immutable, limit its mutability as much as possible.”

How to implement:

  • ensure the class cannot be overridden - make the class final, or use static factories and keep constructors private
  • make fields private and final
  • force callers to construct an object completely in a single step, instead of using a no-argument constructor combined with subsequent calls to setXXX methods (that is, avoid the Java Beans convention)
  • do not provide any methods which can change the state of the object in any way
  • if the class has any mutable object fields, then they must be defensively copied when passed between the class and its caller

(2.10) What are generics in java and what is the benefit of using them?

Customize a "generic" method or class to whatever type you‘re working with.

Advantages:

  • Stronger type checks at compile time.
  • Elimination of casts.
  • Enabling programmers to implement generic algorithms.

(2.11) What is an annotation? Do you know any Java built-in annotations?

Annotations are a form of syntactic metadata that can be added to the source code.

Classes, methods, variables, parameters and packages may be annotated.

Checking for annotations is done via reflection API.

Built-in annotations:

  • @Override
  • @Deprecated
  • @SuppressWarnings

Usage:

  • Documentation, e.g. XDoclet
  • Compilation
  • IDE
  • Testing framework, e.g. JUnit
  • IoC container e.g. as Spring
  • Serialization, e.g. XML
  • Aspect-oriented programming (AOP), e.g. Spring AOP
  • Application servers, e.g. EJB container, Web Service
  • Object-relational mapping (ORM), e.g. Hibernate, JPA

(2.12) What is the StackOverflowError? What could be the root cause of this error?

StackOverflowError is an error and thus should not be handled.

StackOverflowError is mostly caused by infinite recursion (invalid or missing termination condition).

(2.13) Which methods can you call on every instance in Java?

  • equals
  • hashCode
  • wait
  • notify, notifyAll
  • toString
  • getClass
  • PROTECTED: clone and finalize

(2.14) What are enums? Describe them. Can be inherited? Is it allowed to define a constructor for an enum?

An enum type is a special data type that enables for a variable to be a set of predefined constants.

Enums cannot inherit from each other, because each enum type already implements from java.lang.Enum and there’s no multiple inheritance in Java.

Enums can implement interfaces though.

Enums can contain constructors, methods and fields.

The individual constants are like instances of the enum class.

(2.15) Is it possible to change the content of a String instance? Can you mention some other classes for manipulating Strings?

String is immutable (and also final). Why?

  • StringPool would not be possible – anybody could change any string.
  • Security reasons – String is input parameter to many standard functions – could be exploited.
  • Inherently thread safe.
  • String can cache the hashCode.

StringBuffer (synchronized), StringBuilder (is not synchronized). Clear by calling setLength(0).

(3) Advanced Java/J2EE

(3.1) What is the reflection API? Pros/Cons? What is its purpose?

(This is a duplicate question – same as (2.6))

(3.2) What is a servlet? What is the life cycle of a servlet?

A Servlet is an interface in Java EE (javax.servlet) that conforms to the Java Servlet API, a protocol by which a Java class may respond to HTTP requests.

Servlet# service(ServletRequest req, ServletResponse res)
Servlet# init(ServletConfig config)
Servlet# destroy()

HttpServlet# doGet(HttpServletRequest req,HttpServletResponse resp)
HttpServlet# doPost(HttpServletRequest req, HttpServletResponse resp)

 

(3.3) What is a classloader and what are itsresponsibilities? What is a classloader hierarchy?

Java is a dynamically compiled language. Unlike C++, thelinking process is performed by the JVM at runtime. Classes are loaded into theJVM on an ‘as needed‘ basis. Static initializers are run when the class isbeing loaded.

 

Each classloader in the hierarchy first queries its parent. Onlywhen the parent is not able to load  theclass, the classloader tries itself.

(3.4) What is JMS, what are the two basic models?

Java Messaging Service, part of Java EE.

Two basic models:

  • Point-to-point (queues, senders/producers, receivers/consumers)
  • Publish / subscribe (topics, publisher,subscriber)

(3.5) What is point-to-point messaging?

In point-to-point messaging system, messages are routed toan individual consumer which maintains a queue of "incoming"messages. This messaging type is built on the concept of message queues,senders, and receivers. Each message is addressed to a specific queue, and thereceiving clients extract messages from the queues established to hold theirmessages. While any number of producers can send messages to the queue, eachmessage is guaranteed to be delivered, and consumed by one consumer. Queuesretain all messages sent to them until the messages are consumed or until themessages expire. If no consumers are registered to consume the messages, thequeue holds them until a consumer registers to consume them.

(3.6) What is a managed bean?

EJB = POJO that is treated as managed component by the JavaEE container.

  • Session Beans – "Stateful","Stateless" or "Singleton"
  • Message Driven Beans

(3.7) What is a web service? Could you explain terms SOAP,WSDL.

Web Service is a software system designed to supportinteroperable machine-to-machine interaction over a network. It has aninterface described in a machine-processable format (specifically WSDL). Othersystems interact with the Web service in a manner prescribed by its descriptionusing SOAP messages, typically conveyed using HTTP with an XML serialization inconjunction with other Web-related standards.

  • Java EE
  • Apache Axis
  • Spring Web Services

SOAP = Simple Object Access Protocol = protocol for WebServices.

(3.8) What are two basic approaches of how to design webservice?

REST

  • If you have limited bandwidth
  • If your operations are stateless
  • If your clients require caching.

SOAP

  • If you require asynchronous processing
  • If you need formal contract/Interfaces
  • In your service operations are statefull

(3.9) What is a two-phase commit?

2PC is a distributed algorithm that coordinates all theprocesses that participate in a distributed atomic transaction on whether tocommit or roll back the transaction.

Commit request phase (= voting phase)

  • The coordinator sends a query to commit messageto all cohorts and waits until it has received a reply from all cohorts.
  • The cohorts execute the transaction up to thepoint where they will be asked to commit. They each write an entry to theirundo log and an entry to their redo log.
  • Each cohort replies with an agreement message(cohort votes Yes to commit), if the cohort‘s actions succeeded, or an abortmessage (cohort votes No, not to commit), if the cohort experiences a failurethat will make it impossible to commit.

Commit phase (success)

  • If the coordinator received an agreement messagefrom all cohorts during the commit-request phase:
  • The coordinator sends a commit message to allthe cohorts.
  • Each cohort completes the operation, andreleases all the locks and resources held during the transaction.
  • Each cohort sends an acknowledgment to thecoordinator.
  • The coordinator completes the transaction whenall acknowledgments have been received.

Commit phase (failure)

  • If any cohort votes No during the commit-requestphase (or the coordinator‘s timeout expires):
  • The coordinator sends a rollback message to allthe cohorts.
  • Each cohort undoes the transaction using theundo log, and releases the resources and locks held during the transaction.
  • Each cohort sends an acknowledgement to thecoordinator.
  • The coordinator undoes the transaction when allacknowledgements have been received.

(3.10) What is JDBC? What is ORM. Do you know anyimplementations? What is lazy-loading/fetching?

JDBC (Java Database Connectivity) is part of JDK since JDK1.1. Packages java.sql.* and javax.sql.*.

JDBC is oriented towards relational databases.

A JDBC-to-ODBC bridge enables connections to anyODBC-accessible data source in the JVM host environment.

Usage

  • Class.forName( "com.somejdbcvendor.TheirJdbcDriver");
  • DriverManager.registerDriver(Driver driver)
  • DriverManager.getConnection(<connectstring>)
  • Statement stmt = conn.createStatement();
  • stmt.executeUpdate( "INSERT INTO MyTable(name ) VALUES ( ‘my name‘ ) " );

Four types of drivers

  • Type 1 that calls native code of the locallyavailable ODBC driver.
  • Type 2 that calls database vendor native libraryon a client side. This code then talks to database over network.
  • Type 3, the pure-java driver that talks with theserver-side middleware that then talks to database.
  • Type 4, the pure-java driver that uses databasenative protocol.

Object Relational Mapping (ORM)

  • Three levels of caching: entity level (lazyloading); first level cache (persistence context); second level cache (EHCache)

(4) Multithreading and Synchronization

(4.1) How can you create new threads in Java? What is thethread lifecycle in Java? Is there difference between J2SE and J2EE world?

Create new thread:

  • implement java.lang.Runnable (preferred way),extend java.lang.Thread
  • high level concurrency – java.util.concurrent(since Java 5.0)

(4.2) How JVM performs thread synchronization? Explain termsMonitor, critical section, deadlock, volatile.

Keyword “synchronized”

  • Static method can be synchronized – the monitoris the class.
  • Constructors cannot use the synchronizedkeyword.
  • Synchronized blocks are reentrant (by the samethread).

Atomic access

  • Reads and writes are atomic for referencevariables and for most primitive variables (all types except long and double).
  • Reads and writes are atomic for all variablesdeclared volatile (including long and double variables).

wait(), notify(), notifyAll()

  • The thread must have acquired a lock beforeinvoking wait(), notify() or notifyAll().
  • Otherwise, IllegalMonitorStateException.

Immutable object are inherently thread safe.

join() on multiple threads

for (Thread thread : threads) {

 thread.join();

}

 

(4.3) What‘s the difference between the methods sleep() andwait()?

  • A wait can be "woken up" by another threadcalling notify on the monitor which is being waited on whereas a sleep cannot.
  • wait (and notify) must happen in a blocksynchronized on the monitor object whereas sleep does not. sleep does notrelease the acquired lock.
  • wait is called on Object itself (i.e. you waiton an object‘s monitor) whereas you call sleep (static) on Thread.
  • You should always wait whilst spinning on somecondition.

(4.4) What does java.util.concurrent package provide?

High level concurrency package introduced with Java SE 5.

java.util.concurrent.locks

Interface

Implementation

Lock

  • lock()
  • lockInterruptibly()
  • newCondition()
  • tryLock()
  • tryLock(long time, TimeUnit unit)
  • unlock()

ReentrantLock

ReentrantReadWriteLock.ReadLock

ReentrantReadWriteLock.WriteLock

ReadWriteLock

  • readLock()
  • writeLock()

ReentrantReadWriteLock

 

 

Executor, ThreadPool

Concurrent collections

  • BlockingQueue
  • ConcurrentHashMap

Atomic variables

  • Like volatile, for example:
  • AtomicBoolean, AtomicInteger, AtomicReference …
  • Operations: get, set, lazySet, weakCompareAndSet,compareAndSet

 (4.5) How do yousynchronize a collection?

We can use synchronized wrappers. The following factorymethods return thread-safe objects:

  • Collections.synchronizedCollection(Collection<T>c) 
  • Collections.synchronizedList(List<T>list) 
  • Collections.synchronizedMap(Map<K,V>m) 
  • Collections.synchronizedSet(Set<T> s) 
  • Collections.synchronizedSortedMap(SortedMap<K,V>m) 
  • Collections.synchronizedSortedSet(SortedSet<T>s) 

(4.6) Can a thread deadlock itself?

By definition, there should be at least two threads for adeadlock. However the following two lines product a thread-hang that almostlooks like a thread deadlocking itself:

lock.readLock().lock();
lock.writeLock().lock();

(5) Databases

(5.1) Can you explain what transactions are? How are theyused and why? What ACID stands for? Can you describe isolation levels?

ACID – core properties of a DBMS

  • Atomicity = Transaction is "all or nothing”.
  • Consistency = DB is always in valid stateaccording to constraints, cascades, triggers.
  • Isolation = Concurrent transactions see eachother as if executed sequentially.
  • Durability = Once a transaction has beencommitted, it will remain so.

Isolation levels

Serializable

  • This is the highest isolation level.
  • Requires read and write locks (acquired on selected data) to be released at the end of the transaction.
  • Also range-locks must be acquired when a SELECT query uses a ranged WHERE clause, especially to avoid the phantom reads phenomenon.

Repeatable reads

  • Keeps read and write locks (acquired on selected data) until the end of the transaction.
  • However, range-locks are not managed, so the phantom reads phenomenon can occur.

Read committed

  • Keeps write locks (acquired on selected data) until the end of the transaction, but read locks are released as soon as the SELECT operation is performed (so the non-repeatable reads phenomenon can occur).
  • Range-locks are not managed.

Read uncommitted

  • This is the lowest isolation level.
  • Dirty reads are allowed (see below), so one transaction may see not-yet-committed changes made by other transactions

 

(5.2) What is the difference between inner and outer join?

 

(5.3) What is an index? What are pros/cons? What is aclustered and non-clustered, bitmap index?

Pros:

  • faster select queries (and sometimes deletequeries)
  • can be used for sorting
  • unique indexes guarantee unique rows

Cons:

  • slower insert, update and delete queries
  • indexes take up disk space
  • need to be re-built from time to time

Clustered index = The actual table (rows) isreorganized according to the index. Increases performance of sequential access.Only one clustered-index per table.

Bitmap index = index data stored in bit arrays.Useful for columns with small domains (for example gender).

(5.4) What are cursors? Explain different types of cursors.What are the disadvantages of cursors? How can you avoid cursors?

Scrollable cursor = can be positioned anywhere in theresult set.

Cursor “with hold” = not released at commit.

Disadvantages:

  • Fetching a row from the cursor may result in anetwork round trip each time.
  • Cursors allocate resources on the server, forinstance locks, packages, processes, temporary storage, etc.

(5.5) What is a database view?  What is a materialized view?

 

(5.6) What are database constraints? What are pros/cons?

Disadvantages:

  • Takes time to execute.

(5.7) What is normalization? What are the benefits?

Normalization – process of enforcing / increasing the NormalForm (NF) of the database.

NF1 - Table faithfully represents a relation,primarily meaning it has at least one candidate key.

NF2 - No non-prime attribute in the table isfunctionally dependent on a proper subset of any candidate key.

NF3 - Every non-prime attribute is non-transitivelydependent on every candidate key in the table. The attributes that do notcontribute to the description of the primary key are removed from the table. Inother words, no transitive dependency is allowed.

 

JI_4