Java Programming Advanced Features Security Volume II - Chapter 9.

86
COMP201 Topic 17 / Slide 1 Java Programming Advanced Features Security Volume II - Chapter 9

Transcript of Java Programming Advanced Features Security Volume II - Chapter 9.

Page 1: Java Programming Advanced Features Security Volume II - Chapter 9.

Java Programming

Advanced Features

SecurityVolume II - Chapter 9

Page 2: Java Programming Advanced Features Security Volume II - Chapter 9.

About Security Application Security Java Security from the Ground Up Standalone Java Application Techniques

Agenda

Page 3: Java Programming Advanced Features Security Volume II - Chapter 9.

Common Security ThreatsThree concepts of CIA security modelDefinition of security

About Security

Page 4: Java Programming Advanced Features Security Volume II - Chapter 9.

Identity interceptionSteal your identity and use it as their own

MasqueradingGrab your identity and use it elsewhere with the intention of perpetrating fraud

Replay attackCapture your request and replay that request

Data interception and manipulationRead your data (such as credit card info)

Common Security Threats

Page 5: Java Programming Advanced Features Security Volume II - Chapter 9.

RepudiationDeny your/his completed transaction

Denial of ServiceTerminate the service

Common Security Threats

Page 6: Java Programming Advanced Features Security Volume II - Chapter 9.

Three concepts of CIA security model

Confidentiality information must not be disclosed to any unauthorized

person Integrity

authorized actions (unauthorized data changes) separation and protection for resources error detection and correction (data corruption)

Availability presence of objects or service in a usable form capacity to meet service needs adequate timeliness of a service

Page 7: Java Programming Advanced Features Security Volume II - Chapter 9.

Definition of security

Detect Detect how, when and where intrusion has taken place

Protect Manage people and the Information System in an

effective manner so as to protect against unauthorized usage

Page 8: Java Programming Advanced Features Security Volume II - Chapter 9.

Definition of security

React react to an intrusion ensure that penetration does not happen again. vulnerability is eliminated

Recover recover all data and programs from a breach in

security

Page 9: Java Programming Advanced Features Security Volume II - Chapter 9.

Application Security - Not just technology; it’s a process… -

System-level Security Vs.

Application-level Security

Operating System

JVM

Java/J2EE APIs

Application code Application

Level{

System Level{

Page 10: Java Programming Advanced Features Security Volume II - Chapter 9.

System-level Security Vs. Application-level Security

Defeating System-level security may not provide attackers with appropriate access to the application-level data, logic, or methods that they seek

Attacker

Sy

ste

m-

lev

el

s

ecu

rity

Ap

plic

ati

on

-le

ve

l

Se

curi

ty

E

nte

rpri

se

Da

ta

Page 11: Java Programming Advanced Features Security Volume II - Chapter 9.

System-level Security Vs. Application-level Security

(cont.) Work together to build a secure system/application

combination

Attacker

Sy

ste

m-

lev

el

s

ecu

rity

Ap

plic

ati

on

-le

ve

l

Se

curi

ty

E

nte

rpri

se

Da

ta

Attacker

Page 12: Java Programming Advanced Features Security Volume II - Chapter 9.

System-level Security Vs. Application-level Security (cont.)

It is more efficient to push some security responsibilities up to the application level instead of handling them at the operating-system level

OS (Solaris)

JVM (Solaris)

Java/J2EE APIs

Application code

OS (IBM AIX)

JVM (IBM AIX)

Java/J2EE APIs

Application code

OS (MS Window)

JVM (MS Window)

Java/J2EE APIs

Application code

Page 13: Java Programming Advanced Features Security Volume II - Chapter 9.

Java Security from the Ground Up

Java Language Safety Features Java Security Model Java Security Architecture

Page 14: Java Programming Advanced Features Security Volume II - Chapter 9.

Java Language Safety Features

Objects have access levels: private: Accessible by defining class package (default): Accessible by classes in the same

package protected: Same as package, with addition of access by

any subclass public: Accessible by any class

Page 15: Java Programming Advanced Features Security Volume II - Chapter 9.

Java Language Safety Features

Access methods are strictly adhered to No pointers (no access to arbitrary memory and

automatic garbage collection) “final” methods or variables cannot be changed Variables MUST be initialized before use Array bounds are enforced Strict object casting rules

Page 16: Java Programming Advanced Features Security Volume II - Chapter 9.

Java Security Enforcement

Page 17: Java Programming Advanced Features Security Volume II - Chapter 9.

Java Security Enforcement

Enforcement happens at different times Compile time enforcement Class load time enforcement Runtime enforcement

Page 18: Java Programming Advanced Features Security Volume II - Chapter 9.

Compile Time Enforcement

Java Source

Java Compiler Bytecode

Class Loader Bytecode

Verifier

Java Virtual Machine

Runtime

Page 19: Java Programming Advanced Features Security Volume II - Chapter 9.

Compile Time Enforcement

Validate language syntaxEnforce method and variable access rulesEnforce variable initializationEnforce some casting operations

Page 20: Java Programming Advanced Features Security Volume II - Chapter 9.

Class Load Time Enforcement Java Source

Java Compiler Bytecode

Class Loader Bytecode

Verifier

Java Virtual Machine

Runtime

Page 21: Java Programming Advanced Features Security Volume II - Chapter 9.

Class Load Time Enforcement

Bytecode verificationVerifies class file formatAccesses objects as correct typeFinal classes are not subclassedFinal methods are not overriddenEvery class has a single superclass Verify that casting legality checks are in place

Page 22: Java Programming Advanced Features Security Volume II - Chapter 9.

Class Load Time Enforcement

No operand stack overflowsAll field and method accesses are legalMethod calls use correct number & types of arguments

Page 23: Java Programming Advanced Features Security Volume II - Chapter 9.

Runtime Enforcement

Java Compiler

Java Source

BytecodeClass Loader Bytecode

Verifier

Java Virtual Machine

Runtime

Java Compiler

Page 24: Java Programming Advanced Features Security Volume II - Chapter 9.

Runtime Enforcement

Array bounds checkingThrows ArrayIndexOutOfBoundsException

Object castingThrows ClassCastException

Security ManagerThrows SecurityExceptionDepends on the Access Controller

Page 25: Java Programming Advanced Features Security Volume II - Chapter 9.

Java Security Model

Page 26: Java Programming Advanced Features Security Volume II - Chapter 9.

Java Security Model

Sandbox – a strictly defined arena where they cannot affect other system resources. It provides virtually no flexibility.

Page 27: Java Programming Advanced Features Security Volume II - Chapter 9.

Java Security Model (cont.)

Page 28: Java Programming Advanced Features Security Volume II - Chapter 9.

What does this code do?

Page 29: Java Programming Advanced Features Security Volume II - Chapter 9.

Using java security mechanisms

Applets are restricted to the sandbox by default: Can only phone home and create pop-up window

with warning Cannot read/write/delete local files, run another

program, connecting to a server other than its home server, …

More permissions can be granted with Security policy file Code signing

Page 30: Java Programming Advanced Features Security Volume II - Chapter 9.

What happens when executing ? Use caution when executing Applets as Applications

public class BadApplet extends Applet{ public void init(){ try { Runtime.getRuntime().exec(“rmdir

foo”); } catch (Exception e) { System.out.println(e); } } public static void main(String args[]) { BadApplet a = new BadApplet(); a.init(); } }

1. Exception thrown if run in an Applet container

2. Exception thrown if run as an application using Applet security

Java –Djava.security.manager BadApplet

3. OK if run as an application Java BadApplet

Page 31: Java Programming Advanced Features Security Volume II - Chapter 9.

Security Policy Files Consist of a sequence of grant entries.

Each gives some specific permissions to applets from a specific location and/or signed by a specific person

A grant entry has the following general form:grant signedBy “name”, codeBase “file source”{ permission1; permission2; …}

signedBy part omitted if signatures not required for this entry. codeBase part omitted if the entry applies to code from all sources

Page 32: Java Programming Advanced Features Security Volume II - Chapter 9.

Security Policy Files codeBase examples:

grant codeBase “http://www.cs.ust.hk/~liao/comp201/”{ } //premission entry for all classes under the directory grant codeBase “http://www.cs.ust.hk/~liao/comp201/tmp.jar”{ }

// permission entry for tmp.jar

grant codeBase “file:C:/dir/tmp” { }grant codeBase “file:/C:/dir/tmp” { }grant codeBase “file://C:/dir/tmp” { }/* permission entry for tmp on local machine */

Note: Forward slash even for the Windows OSCode signing will be discussed later.

Page 33: Java Programming Advanced Features Security Volume II - Chapter 9.

Security Policy Files General form for permissions:

permission className tagetName, actionList;className must be fully qualified.

Examples: permission java.io.FilePermission "D:\\-","read, write"; // permission to read and write all files in D drive

permission java.awt.AWTPermission "showWindowWithoutWarningBanner";

// permission to create pop-up window without warning

permission java.net.SocketPermission “*:8000-8999", “connect";

//permission to connect to any host via port 8000 - 8999.

Page 34: Java Programming Advanced Features Security Volume II - Chapter 9.

Security Policy Files Permission classes:

java.io.FilePermission java.awt.AWTPermission java.net.SocketPermissionjava.net.NetPermissionjava.util.PropertyPermissionjava.lang.RuntimePermissionjava.security.AllPermission….

See page 712 for details

Page 35: Java Programming Advanced Features Security Volume II - Chapter 9.

Security Policy Files java.io.FilePermission

Targets:File a fileDirectory a directoryDirectory/* all files in the directory* all files in current directoryDirectory/- all files in this and all its subdirectories- all files in current directory and all its subs<<ALL FILES>> all files in the file system

In Windows OS, use \\ as file separator Actions

read, write, delete, execute

Page 36: Java Programming Advanced Features Security Volume II - Chapter 9.

Security Policy Files java.net.SocketPermission

Targets: (hostRange:portRange)HostName or IPAddreses a single hostlocalhost or empty local host*.domainSuffix all hosts whose domain names end

with the suffix . E.g. *.com* all hosts

:n single port:n1-n2 all ports in the range

Actions:accept, connect, listen

Page 37: Java Programming Advanced Features Security Volume II - Chapter 9.

Security Policy Files An example policy filegrant codeBase

"http://www.cs.ust.hk/~liao/comp201/codes/secu/awt/" { permission java.awt.AWTPermission

"showWindowWithoutWarningBanner";};

grant codeBase "http://www.cs.ust.hk/~liao/comp201/codes/secu/file/" {

permission java.awt.AWTPermission "showWindowWithoutWarningBanner";

permission java.io.FilePermission "<<ALL FILES>>", "read, write";

};

grant codeBase "http://www.cs.ust.hk/~liao/comp201/codes/secu/socket/" {

permission java.net.SocketPermission "*", "connect";};

Page 38: Java Programming Advanced Features Security Volume II - Chapter 9.

Security Policy Files policytool: a utility for creating policy files

Page 39: Java Programming Advanced Features Security Volume II - Chapter 9.

Security Policy FilesLocation of policy file: On client machine Method 1:

${user.home}/.java.policy

On XP: C:\Documents and Settings\liao\.java.policy${java.home}/lib/security/java.policy on my machine: C:\Program Files\j2sdk1.4.0\jre\lib\security

Method 2: place a policy file on the internet or on local machine, add to the master security properties file: ${java.home}/jre/lib/security/java.security

the a link to the policy file. E.g.: policy.url.3=http://www.cs.ust.hk/~liao/comp201/codes/secu/applet.policy

Manage the policy file at a single location. Good for intranet.

Page 40: Java Programming Advanced Features Security Volume II - Chapter 9.

Permission Granting Examples AWT Permission example: (check code page)

Normally, pop-up windows created by applets come with warning banners.

However, the pop-up window created by the applet from

http://www.cs.ust.hk/~liao/comp201/codes/secu/awt/

has no warning banner if one includes the following entry into thepolicy filegrant codeBase "http://www.cs.ust.hk/~liao/comp201/codes/secu/awt/" { permission java.awt.AWTPermission

"showWindowWithoutWarningBanner"; };

Page 41: Java Programming Advanced Features Security Volume II - Chapter 9.

Permission Granting Examples File Permission example:

Normally, applets cannot read and write local files. However, FileIOApplet from

http://www.cs.ust.hk/~liao/comp201/codes/secu/file/ can read and write local files if one includes the following grant entry

in the policy file: grant codeBase "http://www.cs.ust.hk/~liao/comp201/codes/secu/file/" { permission java.io.FilePermission “<<ALL FILES>> ",

"read,write"; permission java.awt.AWTPermission

"showWindowWithoutWarningBanner"; };

Page 42: Java Programming Advanced Features Security Volume II - Chapter 9.

Permission Granting Examples Socket Permission example:

Normally, applets cannot connect to a server other than its home server.

However, SocketApplet from

http://www.cs.ust.hk/~liao/comp201/codes/secu/socket/

can connect to other http servers if one includes the following grant entry in the policy file:

grant codeBase “http://www.cs.ust.hk/~liao/comp201/codes/secu/socket/” { permission java.net.SocketPermission "*", "connect"; };

Page 43: Java Programming Advanced Features Security Volume II - Chapter 9.

In your paper try to explain the contents following permission policy file

Page 44: Java Programming Advanced Features Security Volume II - Chapter 9.
Page 45: Java Programming Advanced Features Security Volume II - Chapter 9.
Page 46: Java Programming Advanced Features Security Volume II - Chapter 9.

Outline Using java security mechanisms

Security policy files Code signing

Page 47: Java Programming Advanced Features Security Volume II - Chapter 9.

Code Signing Developer

Generates a certificate, which contains a pair of keys, a public key and a private key.

Send the public key to its users. Sign applets with the private key.

Client Gets public key from the developer Adds the public key to his/her own public key collection Modify its own security policy file to give more permissions to

applets signed by THE developer.

Page 48: Java Programming Advanced Features Security Volume II - Chapter 9.

Code Signing /Developer

Java comes with the keytool program for managing keystore – database of certificates.

To generate a keystore liao.store and generate a pair of keys with alias liao use the command:keytool –genkey –keystore liao.store –alias liao

A dialog follows and liao.store created.

Keep liao.store at a safe location!

Page 49: Java Programming Advanced Features Security Volume II - Chapter 9.

Enter keystore password: 123456 What is your first and last name? [Unknown]: Renlan LiaoWhat is the name of your organizational unit? [Unknown]: Computer ScienceWhat is the name of your organization? [Unknown]: Hong Kong University of Science and TechnologyWhat is the name of your City or Locality? [Unknown]: Hong KongWhat is the name of your State or Province? [Unknown]: Hong KongWhat is the two-letter country code for this unit? [Unknown]: CNIs <CN=Renlan Liao, OU=Computer Science, O=Hong Kong University of

Science and Technology, L=Hong Kong, ST=Hong Kong, C=CN> correct? [no]: yes

Enter key password for <Renlan>

(RETURN if same as keystore password):

Code Signing /Developer

Page 50: Java Programming Advanced Features Security Volume II - Chapter 9.

Export the public key to a certificate file and sent it to user.keytool –export –keystore liao.store –alias liao –file liao.cert

What is inside?D:\Users\public_html\COMP201\codes\secu>keytool -printcert -

file liao.certOwner: CN=Renlan Liao, OU=Computer Science, O=Hong Kong University of

Science and Technology, L=Hong Kong, ST=Hong Kong, C=cnIssuer: CN=Renlan Liao, OU=Computer Science, O=Hong Kong University

of Science and Technology, L=Hong Kong, ST=Hong Kong, C=cnSerial number: 40a08a25Valid from: Tue May 11 16:09:09 GMT+08:00 2004 until: Mon Aug 09

16:09:09 GMT+08:00 2004Certificate fingerprints: MD5: A0:60:35:22:28:42:3B:18:77:12:EB:43:13:B1:D7:C6 SHA1: 9:34:84:4C:F0:32:B5:B1:17:55:3B:0C:03:FC:87:FE:EC:69:A0:6F

Code Signing /Developer

Page 51: Java Programming Advanced Features Security Volume II - Chapter 9.

Sign applets

Create a jar filejar cvf MyApplet.jar *.class

Run the jarsigner tooljarsigner –keystore Liao.store MyApplet.jar Liao

Keystore containing private key

Alias of private key

Code Signing /Developer

Page 52: Java Programming Advanced Features Security Volume II - Chapter 9.

Add public key received to his/her store of public keyskeytool –import –keystore certs.store –alias liao –file liao.cert

Include location of public key store to policy fileKeystore “keystoreURL”, “keystoreType”;

Ex: keystore “file:C:\Windows\cert.store”, "JKS";

keystore "http://www.cs.ust.hk/~liao/comp201/codes/secu/certs.store", "JKS";

JKS: type of keystore generated by keytool

Code Signing /Client

Page 53: Java Programming Advanced Features Security Volume II - Chapter 9.

Add signedBy “alias” to grant clauses in policy file

grant signedBy “liao" { permission java.awt.AWTPermission "showWindowWithoutWarningBanner"; };

What if client’s policy file does not grant permissions to signed applets Browser will ask for permissions when loading the applets Example: http://www.cs.ust.hk/~liao/comp201/codes/secu/sign2/

Code Signing /User

Page 54: Java Programming Advanced Features Security Volume II - Chapter 9.

Effective Java:Creating and Destroying Objects

Page 55: Java Programming Advanced Features Security Volume II - Chapter 9.

Agenda Material From Joshua Bloch

Effective Java: Programming Language Guide

Cover Items 1-7

Bottom Line: Understand Java Construction First C++ Creation/Destruction More Complex

Page 56: Java Programming Advanced Features Security Volume II - Chapter 9.

Item 1: Consider Static Factory Methods Instead of Constructors

Constructor Calls vs Static Factory Method Alternate way to get an object Sometimes replaces constructors Sometimes augments constructors

// Simple example from Boolean classpublic static Boolean valueOf (boolean b) { return b ? Boolean.TRUE : Boolean.FALSE;}

Page 57: Java Programming Advanced Features Security Volume II - Chapter 9.

Item 1: Advantages Unlike constructors, static factory

methods Can have meaningful names Need not create new instances – Can return any subtype of return type

–Reduces client dependency on specific class Can reduce verbosity of creating parameterized type

instances

Page 58: Java Programming Advanced Features Security Volume II - Chapter 9.

Advantage 1: Meaningful Names Consider the constructor/factory pair:// Constructs a randomly generated positive BigInteger // that is probably prime, with the specified bitLength BigInteger (int bitLength, int certainty, Random rnd)

vs.

// Returns a positive BigInteger that is probably prime,// with the specified bitLength.

BigInteger.probablePrime (int bitLength, Random rnd)

– Note: The extra constructor argument avoids a clash with another constructor

– Unique parameter lists on constructors are really restrictive

Page 59: Java Programming Advanced Features Security Volume II - Chapter 9.

Advantage 2: Not Required To Create New Object

Instance-controlled classes can be useful Can avoid creating unnecessary duplicate objects

–Boolean.valueOf(boolean) is an example

Can guarantee a “singleton” or “noninstatiable” object

Can allow for very fast “equals” test

Page 60: Java Programming Advanced Features Security Volume II - Chapter 9.

Advantage 3: Can Return Subtype of Return Type

Consider the java.util.Collections class 32 Convenience implementations of Collection interfaces

– All are static factory methods Interface return type vs. actual classes

Static factory methods can hide multiple implementations

Page 61: Java Programming Advanced Features Security Volume II - Chapter 9.

Advantage 4: Reduce Verbosity of Parameterized Type Instances

// Parameterized type instancesMap<String, List<String>> m = new HashMap<String,

List<String>>();

vs.

// Static factory alternative

public static <K, V> HashMap<K, V> newInstance() { return new HashMap<K, V>();}

// Now, client code looks like this// Compiler does type inference!

Map<String, List<String>> m = HashMap.newInstance();

Page 62: Java Programming Advanced Features Security Volume II - Chapter 9.

Item 1: Disadvantages of Static Factory Methods

Subclassing impossible without constructors

Naming conventions necessary– valueOf – effectively a type converter (also just of)– getInstance – return instance described by parameters– newInstance – like getInstance, but guarantees distinct

object– getType – like getInstance, but converts type– newType – like newInstance, but converts type

Page 63: Java Programming Advanced Features Security Volume II - Chapter 9.

Item 2: Consider a Builder vs. Many Constructor Parameters

Static factories and constructors don’t scale well to large numbers of optional parameters

Bloch’s examples: NutritionFactsTelescoping.java NutritionFactsBeans.java NutritionFactsBuilder.java

The last version enjoys significant advantages

Page 64: Java Programming Advanced Features Security Volume II - Chapter 9.

The problem ?

Consider the case of a class representing the Nutrition Facts label that appears on packaged foods. These labels have a few required fields: serving size, servings per container, and calories per serving and over twenty optional fields—total fat, saturated fat, trans fat, cholesterol, sodium, and so on. Most products have nonzero values for only a few of these optional fields.

What sort of constructors or static factories should you write for such a class?

Page 65: Java Programming Advanced Features Security Volume II - Chapter 9.

Telescoping Constructor Pattern.

Traditionally, programmers have used the telescoping constructor pattern.

Provide a constructor with only the required parameters,

Another with a single optional parameter, A third with two optional parameters, and so on,

culminating in a constructor with all the optional parameters.

Here’s how it looks in practice

Page 66: Java Programming Advanced Features Security Volume II - Chapter 9.

What do you think of this code? Is it good or bad?

Page 67: Java Programming Advanced Features Security Volume II - Chapter 9.

Continue….

When you want to create an instance, you use the constructor with the shortest parameter list containing all the parameters you want to set:

Page 68: Java Programming Advanced Features Security Volume II - Chapter 9.

Disadvantages This constructor invocation will require many parameters that you

don’t want to set, but you’re forced to pass a value for them anyway.

It is hard to write client code when there are many parameters, and harder still to read it.

If the client accidentally reverses two such parameters, the compiler won’t complain, but the program will misbehave at runtime.

Think of another solution ??????

Page 69: Java Programming Advanced Features Security Volume II - Chapter 9.

Second Solution

A second alternative when you are faced with many constructor parameters is the JavaBeans pattern.

How does it look like??????

Page 70: Java Programming Advanced Features Security Volume II - Chapter 9.

JavaBeans Pattern Solution

Page 71: Java Programming Advanced Features Security Volume II - Chapter 9.

Problems It is easy, if a bit wordy, to create instances, and easy to

read the resulting code.

JavaBeans pattern has serious disadvantages of its own. Construction is split across multiple calls, a JavaBean may

be in an inconsistent state partway through its construction.

The class does not have the option of enforcing consistency merely by checking the validity of the constructor parameters.

It can cause errors at runtime, as the compiler cannot ensure that the programmer calls the freeze method on an object before using it.

Page 72: Java Programming Advanced Features Security Volume II - Chapter 9.

Builder pattern Solution There is a third alternative that combines the safety of

the telescoping constructor pattern with the readability of the JavaBeans pattern.

It is a form of the Builder pattern Instead of making the desired object directly, the client calls a constructor

(or static factory) with all of the required parameters and gets a builder object.

Then the client calls setter-like methods on the builder object to set each optional parameter of interest.

Finally, the client calls a parameterless build method to generate the object, which is immutable. The builder is a static member class of the class it builds

Page 73: Java Programming Advanced Features Security Volume II - Chapter 9.
Page 74: Java Programming Advanced Features Security Volume II - Chapter 9.
Page 75: Java Programming Advanced Features Security Volume II - Chapter 9.
Page 76: Java Programming Advanced Features Security Volume II - Chapter 9.

Item 3: Enforce Singleton Property

A Singleton is a class that’s instantiated exactly once Two approaches before Enums:

Public static member (a constant, of course) Public static factory method

Enum singleton is now preferred Lots of subtle advantages: security, serialization, etc.

Page 77: Java Programming Advanced Features Security Volume II - Chapter 9.

Item 3: Code Example// Option 1: public final fieldpublic class Elvis { public static final Elvis INSTANCE = new Elvis(); private Elvis() {...}}// Option 2: static factory methodpublic class Elvis { private static final Elvis INSTANCE = new Elvis(); private Elvis() {...} public static Elvis getInstance() { return INSTANCE;

}}// Option 3: Enum type – now the preferred approachpublic enum Elvis { INSTANCE; …}

Page 78: Java Programming Advanced Features Security Volume II - Chapter 9.

Item 4: Enforce Noninstantiability With a Private Constructor

Some classes just group static methods and/or fields Makes no sense to instantiate such a class

Trying to enforce noninstantiability by making class abstract doesn’t work Subclassing is possible Clients are led to believe subclassing makes sense

However, a private constructor does the job

Page 79: Java Programming Advanced Features Security Volume II - Chapter 9.

Item 4: Code Example

// Noninstantiable utility classpublic class UtilityClass { // Suppress default constructor for noninstantiability private UtilityClass() { throw new AssertionError(); } ... // Remainder of class omitted}

// Note that no subclassing is possible (constructor chaining...)// Note that client can’t call constructor// Note that if constructor is mistakenly called inside class,there

is an immediate assertion violation.

Page 80: Java Programming Advanced Features Security Volume II - Chapter 9.

Item 5: Avoid Creating Unnecessary Objects

On the one hand, performance is a secondary concern behind correctness

On the other, gratuitous object creation is just bad programming// String s = new String(“stringette”); // Don’t do this!vs. // String s = “stringette”; // Let JVM optimize for you

// Also see earlier Boolean.valueOf() static factory example

Page 81: Java Programming Advanced Features Security Volume II - Chapter 9.

Item 5: Code Examplepublic class Person { private final Date birthDate; // Other fields, methods, and constructor omitted // DON’T DO THISpublic boolean isBabyBoomer() { // Unnecessary allocation of expensive object Calendar gmtCal =

Calendar.getInstance(TimeZone.getTimeZone(“GMT”)); gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0, 0); Date boomStart = gmtCal.getTime(); gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0, 0); Date boomEnd = gmtCal.getTime(); return birthDate.compareTo(boomStart) >= 0 && birthDate.compareTo(boomEnd) < 0; }}

Page 82: Java Programming Advanced Features Security Volume II - Chapter 9.

Item 5: Code Example Fixed

public class Person { private final Date birthDate; // Other fields, methods, and constructor omitted private static final Date BOOM_START; private static final Date BOOM_END; static { // Note static block Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone(“GMT”)); gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0, 0); BOOM_START = gmtCal.getTime(); gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0, 0); BOOM_END = gmtCal.getTime(); } public boolean isBabyBoomer() { return birthDate.compareTo(BOOM_START) >= 0 && birthDate.compareTo(BOOM_END) < 0; }}

Page 83: Java Programming Advanced Features Security Volume II - Chapter 9.

Item 5: Autoboxing Overhead

// Hideously slow program! Can you spot the object creation?

public static void main(String[] args) { Long sum = 0L; for (long i =0; i < Integer.MAX_VALUE; i++) { sum += i; } System.out.println(sum);}

// Lessons: 1) prefer primitives to Boxed primitives// 2) watch for unintentional autoboxing

The variable sum is declared as a Long instead of a long, which means that the program constructs about 231 unnecessary Long instances (roughly one for each time the long i is added to the Long sum).

Page 84: Java Programming Advanced Features Security Volume II - Chapter 9.

Item 7: Avoid Finalizers

finalize() is a method in the Object class What the garbage collector may call when cleaning up an

unused object Finalizers: unpredictable, dangerous, unnecessary!

They are NOT the analog of C++ destructors There is no guarantee a finalizer will ever be called Finalizers have severe performance penalties Instead, provide explicit termination methods

Sometimes requires “finalizer chaining”

Page 85: Java Programming Advanced Features Security Volume II - Chapter 9.

Item 7: Code Example

// try-finally block guarantees execution of termination method

// termination method ensures resources are released

// Example resources: database connections, threads, windows

Foo foo = new Foo();try { // Do what must be done with foo} finally { foo.terminate(); // Explicit termination method in Foo

}

Page 86: Java Programming Advanced Features Security Volume II - Chapter 9.

Item 7: Finalizer chaining// Manual finalizer chaining// Only do this if you *have* to use the finalizer@Override protected void finalize() throws Throwable { try { .. . // Finalize subclass state } finally super.finalize(); // Note order of finalizer chaining }}

// Also consider “Finalizer Guardian” idiom for public, nonfinal// classes. The goal is to ensure that finalization takes place// even if subclass finalizer fails to invoke super.finalize()