Wednesday, March 30, 2011

Java Transient Variables

If you mark an instance variable as transient, you're telling the JVM to skip (ignore) this variable when you attempt to serialize the object containing it. Serialization is one of the coolest features of Java; it lets you save an object by writing its state to the serialisation stream.

Java Instance variables and Class variables

aka static/non-static variables.

In object-oriented programming with classes, an instance variable is a variable defined in a class (i.e. a member variable), for which each object of the class has a separate copy. They live in memory for the life of the class.

An instance variable is the opposite of class variable, and it is a special type of instance member.

A class variable is a variable defined in a class (i.e. a member variable) of which a single copy exists, regardless of how many instances of the class exist. We use keyword static for declaring class variables.

Instance variable:
■ Can be marked final
■ Can be marked transient
■ Cannot be marked abstract
■ Cannot be marked synchronized
■ Cannot be marked strictfp
■ Cannot be marked native
■ Cannot be marked static, because then they'd become class variables.

Java default values

There is a simple rule - when you define a member variable, it gets a default value. When you define local value, it do not get any default value - it has to be inicialized before the first use, or an compile-time exception will be thrown.

Default values for member variables:

Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
Any object null
boolean false

Java constructors

Here are some legal and illegal examples:

class ConstructorExamples {
    // legal constructors
    ConstructorExamples () { }
    private ConstructorExamples (byte b) { }
    ConstructorExamples (int x) { }
    ConstructorExamples (int x, int... y) { }

    // illegal constructors
    void ConstructorExamples () { }           // it's a method, not a constructor
    ConstructorLike () { }                    // not a method nor a constructor
    ConstructorExamples (short s);            // looks like an abstract method
    static ConstructorExamples (float f) { }  // can't be static
    final ConstructorExamples (long x) { }    // can't be final
    abstract ConstructorExamples (char c) { } // can't be abstract
    ConstructorExamples (int... x, int t) { } // bad var-arg syntax
}

Java Methods with Variable Argument Lists, var-args

As of 5.0, Java allows you to create methods that can take a variable number of
arguments. This feature is also known as "var-args", "varargs", "variable-length argument lists" or "variable arguments,".

Var-args declarations
Here are some legal and illegal var-arg declarations:

Legal:
void myMethodX( int... a ) { } // expects from 0 to many ints
                             // as parameters
void myMethodY( char c, int... a ) { } // expects first a char,
                                     // then 0 to many ints
void myMethodZ( Animal... animal ) { } // 0 to many Animals
void myMethodXYZ( Object... anyKindOfObjects ) { } 
                            // 0 to many Objects

Illegal:
void myMethodA( int x... ) { }              // illegal syntax
void myMethodB( String... str, byte b ) { } // var-arg must be last
void myMethodC( int... x, char... y ) { }   // too many var-args

Accessing var-args
Example 1:
    public static void test(int some, String... args) {
        System.out.print("\n" + some);
        for(String arg: args) {
            System.out.print(", " + arg);
        }
    }


Example 2:
static int sum (int ... numbers)
{
   int total = 0;
   for (int i = 0; i < numbers.length; i++)
        total += numbers [i];
   return total;
}

Java HttpServletResponse

HttpServletResponse is an interface from package javax.servlet.http. It extends javax.servlet.ServletResponse.

The important interface members are:
* addCookie(Cookie cookie);
* addHeader(String name, String value);
* sendError(int sc) Sends an error response to the client using the specified status code and clearing the buffer;
* sendError(int sc, String msg) Sends an error response to the client using the specified status.
* sendRedirect( String newLocation ) throws IOException - Sends a temporary redirect response to the client using the specified redirect location URL. Realised by http code 302 (Redirect).
* setHeader(String name, String value);
* setStatus(int sc) Sets the status code for this response.

Noticable methods from the super interface javax.servlet.ServletResponse:
* String getCharacterEncoding();
* String getContentType() - Returns the content type used for the MIME body;
* boolean isCommitted();
* setCharacterEncoding(String charset);
* setContentType(String type);

Tuesday, March 29, 2011

Java ServletContext

ServletContext is an interface from package javax.servlet;

Getting ServletContext
ServletContext could be get by session.getServletContext() method.
HttpSession could be get by request.getSession( boolean create );

The most important members are:
* addFilter(java.lang.String filterName, Filter filter) - Registers the given filter instance with this ServletContext under the given filterName;
* addListener(java.lang.Class listenerClass) - Adds a listener of the given class type to this ServletContext;
* Object getAttribute(java.lang.String name);
* ClassLoader getClassLoader();
* String getContextPath();
* getMimeType(java.lang.String file);
* log( String message, Throwable throwable );
* setAttribute( String name, java.lang.Object object );

Java HttpSession

HttpSession is interface from package javax.servlet.http.

Getting HttpSession
A HttpSession object could be get by request.getSession( boolean create );

The most important methods are:
* Object getAttribute(java.lang.String name);
* Enumeration getAttributeNames();
* long getCreationTime();
* long getLastAccessedTime();
* ServletContext getServletContext();
* invalidate();
* removeAttribute(java.lang.String name);
* setAttribute( String name, Object value );
* setMaxInactiveInterval(int interval) - Specifies the time, in seconds;
*

java HttpRequest

The interface HttpRequest is located in package javax.servlet.http.

Here are some important members:
* Cookie[] getCookies()
* String getHeader(java.lang.String name) - Returns the value of the specified request header as a String
* String getMethod() - GET, POST, or PUT
* String getQueryString() - Returns the query string that is contained in the request URL after the path.
* String getRemoteUser() - Returns the login of the user making this request, if the user has been authenticated;
* String getRequestURI() - Returns the part of this request's URL from the protocol name up to the query string;
* StringBuffer getRequestURL() - Reconstructs the URL the client used to make the request;
* HttpSession getSession( boolean create );
* boolean isUserInRole( String role );

----
And some inherited from javax.servlet.http.Request:
* Object getAttribute( String name );
* Enumeration getAttributeNames();
* String getContentType() - Returns the MIME type of the body of the request;
* String getParameter( String name );
* Enumeration getParameterNames();
* String getServerName();
* int getServerPort();
* String getRemoteHost() - Returns the fully qualified name of the client ( or the last proxy that sent the request);
* setAttribute( String name, Object o);
* removeAttribute(java.lang.String name);
* Locale getLocale();

Java Native Interface

Java Native Methods

The native modifier indicates that a method is implemented in platform-dependent code, often in C / C++. Native is a modifier and a reserved keyword and that native can be applied only to methods. Note that a native method's body must be a semicolon (;) (like abstract methods), indicating that the implementation is omitted.

Pros and cons
The ability to write just one set of code in Java and have it run on every system with a Java run-time is one of Java's primary strengths. But this platform independence has one key drawback: What do we do with the vast amount of existing code? The trick is to use the so-called native method interface (JNI).

Writing native methods involves importing code from other programming language (eg. C code) into your Java application.

Step-by-step guide
In the example we will use C language and linux/unix host platform. The steps are:
* Write Java code
* Compile Java code
* Create C header (.h file)
* Create C stubs file
* Write C code
* Create shared code library (or DLL)
* Run application

Example Java code
class JavaPrinter {
    public native void printText();
    static
    {
       System.loadLibrary( "nativeprinter" );   
           // Attention: Note lowercase of library name
    }

    public static void main (String[] args) {
       JavaPrinter p = new JavaPrinter();
       p.printText();
    }
}

Compile the Java code
javac JavaPrinter.java

Create a C header file
javah JavaPrinter

Create a C source file
javah -stubs JavaPrinter

Add C/C++ code
Now, let's write the actual code to print out our greeting. By convention we put this code in a file named after our Java class with the string "Imp" appended to it. This results in JavaPrinterImp.c. Place the following into JavaPrinterImp.c:
#include   // Standard native method stuff.
#include "JavaPrinter.h"   // Generated before.
#include          // Standard C IO
void JavaPrinter_printText (struct HJavaPrinter *this) {
    puts ("Hi from C language!!!");
} 

Create a shared library
This is for GCC compiler. First, compile the C source files that we have already created. You have to tell the compiler where to find the Java native method support files, but the main trick here is that you have to explicitly tell the compiler to produce Position Independent Code (PIC):

gcc -I/usr/local/java/include -I/usr/local/java/include/genunix -fPIC -c JavaPrinter.c JavaPrinterImp.c

ow, create a shared library out of the resulting object (.o) files with the following magical incantation:

gcc -shared -Wl,-soname,libnativeprinter.so.1 
-o libnativeprinter.so.1.0 JavaPrinter.o JavaPrinter.o

Copy the shared library file to the standard short name:

cp libnativeprinter.so.1.0 libnativeprinter.so

JNI notes:
* subtle errors in the use of JNI can destabilize the entire JVM in ways that are very difficult to reproduce and debug.
* only applications and signed applets can invoke JNI.
* an application that relies on JNI loses the platform portability Java offers.
* the JNI framework does not provide any automatic garbage collection for non-JVM memory resources allocated by code executing on the native side. Consequently, native side code must assume the responsibility for explicitly releasing any such memory resources that it itself acquires.
* error checking is a MUST or it has the potential to crash the JNI side and the JVM.

Monday, March 28, 2011

Java Reentrant Synchronization

Recall that a thread cannot acquire a lock owned by another thread. But a thread can acquire a lock that it already owns. Allowing a thread to acquire the same lock more than once enables reentrant synchronization. This describes a situation where synchronized code, directly or indirectly, invokes a method that also contains synchronized code, and both sets of code use the same lock. Without reentrant synchronization, synchronized code would have to take many additional precautions to avoid having a thread cause itself to block.

Java Synchronized Statements

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

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

In this example, the addName method needs to synchronize changes to lastName and nameCount, but also needs to avoid synchronizing invocations of other objects' methods. (Invoking other objects' methods from synchronized code can create problems that are described in the section on Liveness.) Without synchronized statements, there would have to be a separate, unsynchronized method for the sole purpose of invoking nameList.add.

Synchronized statements are also useful for improving concurrency with fine-grained synchronization. Suppose, for example, class MsLunch has two instance fields, c1 and c2, that are never used together. All updates of these fields must be synchronized, but there's no reason to prevent an update of c1 from being interleaved with an update of c2 — and doing so reduces concurrency by creating unnecessary blocking. Instead of using synchronized methods or otherwise using the lock associated with this, we create two objects solely to provide locks.

    public class MsLunch {
        private long c1 = 0;
        private long c2 = 0;
        private Object lock1 = new Object();
        private Object lock2 = new Object();

        public void inc1() {
            synchronized(lock1) {
                c1++;
            }
        }

        public void inc2() {
            synchronized(lock2) {
                c2++;
            }
        }
    }

Use this idiom with extreme care. You must be absolutely sure that it really is safe to interleave access of the affected fields.

Java syncronized methods

The synchronized keyword indicates that a method can be accessed by only one
thread at a time.

public synchronized BagContainer readBag( int bagId ) {
// do getting of object
}

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

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

Java abstract methods

An abstract method is a method that's been declared as abstract but not implemented, so, the method contains no functional code.

It is illegal to have an abstract method in a class that is not explicitly declared abstract.

The first concrete subclass of an abstract class must implement all abstract methods of the superclass.

Abstract and static modifiers are NOT allowed. The compiler will output such error:

SomeClass.java:37: illegal combination of modifiers: abstract and
static
abstract static void doMethod();

Java final methods

The final keyword prevents a method from being overridden in a subclass, and is
often used to enforce the API functionality of a method.

class SomeClass{
public final void finalMethod() {
System.out.println("One thing.");
}
}

It's legal to extend SuperClass, since the class isn't marked final, but we can't
override the final method finalMethod()

Java interface constants

All interface constants are "public static final", no matter they are daclared this way or not.

Java strictfp keyword

strictfp is a keyword in the Java programming language that restricts floating-point calculations to ensure portability. Using strictfp guarantees that results of floating-point calculations are identical on all platforms. It was introduced into version 1.2.

Just an example: x86 processors support 80 bit double values. This type is used for intermidiate opetations in Java, to avoid buffer overflows and underflows. The result value is stored according IEEE 754 standard, as 64 bit double. This is when we do not use strictfp keyword.

When we add strictfp, intermidiate java calculations are also reduced to 64 bits. The chance for underflows/overflows is greater but we keep the the results will be compatible with results in Java 1.1.

Usage
strictfp can be used on classes, interfaces and non-abstract methods. When applied to a method, it causes all calculations inside the method to use strict floating-point math. When applied to a class, all calculations inside the class use strict floating-point math.

Java interfeces

Some rules about java interfeces:
■ All interface methods are implicitly public and abstract. In other words, you do not need to actually type the public or abstract modifiers in the method declaration, but the method is still always public and abstract.
■ All variables defined in an interface must be public, static, and final — in other words, interfaces can declare only constants, not instance variables. Interface methods must not be static.
■ Because interface methods are abstract, they cannot be marked final, strictfp, or native. (More on these modifiers later.)
■ An interface can extend one or more other interfaces.
■ An interface cannot extend anything but another interface.
■ An interface cannot implement another interface or class.
■ Interface types can be used polymorphically.

Java Final Classes

When used in a class declaration, the final keyword means the class can't be subclassed. In other words, no other class can ever extend (inherit from) a final class, and any attempts to do so will give you a compiler error.

Java access control

There are two levels of access control:

* At the top level—public, or package-private (no explicit modifier).
* At the member level—public, private, protected, or package-private (no explicit modifier).

Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

Rules for creating Java source files

■ There can be only one public class per source code file.
■ If there is a public class in a file, the name of the file must match the name
of the public class. For example, a class declared as public class Dog { }
must be in a source code file named Dog.java.
■ If the class is part of a package, the package statement must be the first line
in the source code file, before any import statements that may be present.
■ If there are import statements, they must go between the package statement
(if there is one) and the class declaration. If there isn't a package statement,
then the import statement(s) must be the first line(s) in the source code file.
If there are no package or import statements, the class declaration must be
the first line in the source code file.
■ import and package statements apply to all classes within a source code file.
In other words, there's no way to declare multiple classes in a file and have
them in different packages, or use different imports.
■ A file can have more than one nonpublic class.
■ Files with no public classes can have a name that does not match any of the
classes in the file.

Java Enums

Simple enum
The ; after the last element is optional, when this is the end of enum definition.

public enum Color {
WHITE, BLACK, RED, YELLOW, BLUE; //; is optional
}

Simple enum embedded inside a class

public class Outter {
public enum Color {
WHITE, BLACK, RED, YELLOW, BLUE
}
}
Outside the enclosing class, elements are referenced as Outter.Color.RED, Outter.Color.BLUE, etc.

Enum that overrides toString method

A semicolon after the last element is required to be able to compile it. More details on overriding enum toString method can be found here.

public enum Color {
WHITE, BLACK, RED, YELLOW, BLUE; //; is required here.

@Override public String toString() {
String prev = super.toString();
return prev.substring(0, 1) + prev.substring(1).toLowerCase();
}
}

Enum with additional fields and custom constructor

Enum constructors must be either private or package default, and protected or public access modifier is not allowed. When custom constructor is declared, all elements declaration must match that constructor.

public enum Color {
WHITE(21), BLACK(22), RED(23), YELLOW(24), BLUE(25);

private int code;

private Color(int c) {
code = c;
}

public int getCode() {
return code;
}

Java Beans

JavaBeans are Java classes that have properties. You could think of properties as private instance variables. If they are private, the they can be accessed from outside of their class through methods in the class.

JavaBean Naming Rules for properties's members:
■ 'is' or 'get' for boolean values, example: boolean isOdd() or boolean getOdd(), boolean isError() or boolean getError();
■ get/set for other values

JavaBean Listener Naming Rules:
■ Listener method names which "register" a listener with an event source
must use the prefix add, followed by the listener type. For example,
addActionListener().
■ Listener method names which unregister a listener must use the prefix remove, followed by the listener type.
■ Listener method names must end with the word "Listener".

Keywords in Java

The keywords cannot be used as identifiers.

assert - keyword from java 1.4
abstract
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
enum - keyword from java 1.5
extends
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
try
void
volatile
while

Java Legal & Illegal identifiers

Legal identifiers:
int _x;
int $z;
int _$$;
int ___4_a;
int javatests_dot_blogspot_dot_com;

Illegal identifiers:
int :joro;
int -z;
int z#;
int .z;
int 7z;