Java Doc for Freezable.java in  » Internationalization-Localization » icu4j » com » ibm » icu » util » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Internationalization Localization » icu4j » com.ibm.icu.util 
Source Cross Reference  Class Diagram Java Document (Java Doc) 


com.ibm.icu.util.Freezable

All known Subclasses:   com.ibm.icu.dev.test.util.UnicodeMap,  com.ibm.icu.util.GlobalizationPreferences,  com.ibm.icu.text.DateTimePatternGenerator,  com.ibm.icu.text.UnicodeSet,
Freezable
public interface Freezable extends Cloneable(Code)
 DRAFT
 Copyright (C) 2005, International Business Machines Corporation and
 others. All Rights Reserved.
 
Provides a flexible mechanism for controlling access, without requiring that a class be immutable. Once locked, an object can never be unlocked, so it is thread-safe from that point onward. The implementation of both methods must be synchronized. Once the object has been locked, it must guarantee that no changes can be made to it. Any attempt to alter it must raise an UnsupportedOperationException exception. This means that when the object returns internal objects, or if anyone has references to those internal objects, that those internal objects must either be immutable, or must also raise exceptions if any attempt to modify them is made. Of course, the object can return clones of internal objects, since those are safe.

Background

There are often times when you need objects to be objects 'safe', so that they can't be modified. Examples are when objects need to be thread-safe, or in writing robust code, or in caches. If you are only creating your own objects, you can guarantee this, of course -- but only if you don't make a mistake. If you have objects handed into you, or are creating objects using others handed into you, it is a different story. It all comes down to whether you want to take the Blanche Dubois approach ("depend on the kindness of strangers") or the Andy Grove approach ("Only the Paranoid Survive").

For example, suppose we have a simple class:

 public class A {
 protected Collection b;
 protected Collection c;
 public Collection get_b() {
 return b;
 }
 public Collection get_c() {
 return c;
 }
 public A(Collection new_b, Collection new_c) {
 b = new_b;
 c = new_c;
 }
 }
 

Since the class doesn't have any setters, someone might think that it is immutable. You know where this is leading, of course; this class is unsafe in a number of ways. The following illustrates that.

 public test1(SupposedlyImmutableClass x, SafeStorage y) {
 <font color="#0000FF">    <b>// unsafe getter</b>
 </font>    A a = x.getA();
 Collection col = a.get_b();
 col.add(something);<font color="#0000FF"> // a has now been changed, and x too
 </font>
 <font color="#0000FF"><b>// unsafe constructor</b></font>
 a = new A(col, col);
 y.store(a);
 col.add(something);<font color="#0000FF"> // a has now been changed, and y too
 </font>}
 

There are a few different techniques for having safe classes.

  1. Const objects. In C++, you can declare parameters const.
  2. Immutable wrappers. For example, you can put a collection in an immutable wrapper.
  3. Always-Immutable objects. Java uses this approach, with a few variations. Examples:
    1. Simple. Once a Color is created (eg from R, G, and B integers) it is immutable.
    2. Builder Class. There is a separate 'builder' class. For example, modifiable Strings are created using StringBuffer (which doesn't have the full String API available). Once you want an immutable form, you create one with toString().
    3. Primitives. These are always safe, since they are copied on input/output from methods.
  4. Cloning. Where you need an object to be safe, you clone it.

There are advantages and disadvantages of each of these.

  1. Const provides a certain level of protection, but since const can be and is often cast away, it only protects against most inadvertent mistakes. It also offers no threading protection, since anyone who has a pointer to the (unconst) object in another thread can mess you up.
  2. Immutable wrappers are safer than const in that the constness can't be cast away. But other than that they have all the same problems: not safe if someone else keeps hold of the original object, or if any of the objects returned by the class are mutable.
  3. Always-Immutable Objects are safe, but usage can require excessive object creation.
  4. Cloning is only safe if the object truly has a 'safe' clone; defined as one that ensures that no change to the clone affects the original. Unfortunately, many objects don't have a 'safe' clone, and always cloning can require excessive object creation.

Freezable Model

The Freezable model supplements these choices by giving you the ability to build up an object by calling various methods, then when it is in a final state, you can make it immutable. Once immutable, an object cannot ever be modified, and is completely thread-safe: that is, multiple threads can have references to it without any synchronization. If someone needs a mutable version of an object, they can use cloneAsThawed(), and modify the copy. This provides a simple, effective mechanism for safe classes in circumstances where the alternatives are insufficient or clumsy. (If an object is shared before it is immutable, then it is the responsibility of each thread to mutex its usage (as with other objects).)

Here is what needs to be done to implement this interface, depending on the type of the object.

Immutable Objects

These are the easiest. You just use the interface to reflect that, by adding the following:

 public class A implements Freezable {
 ...
 public final boolean isFrozen() {return true;}
 public final Object freeze() {return this;}
 public final Object cloneAsThawed() { return this; }
 }
 

These can be final methods because subclasses of immutable objects must themselves be immutable. (Note: freeze is returning this for chaining.)

Mutable Objects

Add a protected 'flagging' field:

 protected boolean immutable;
 

Add the following methods:

 public final boolean isFrozen() {
 return frozen;
 };
 public Object freeze() {
 frozen = true;
 return this;
 }
 

Add a cloneAsThawed() method following the normal pattern for clone(), except that frozen=false in the new clone.

Then take the setters (that is, any method that can change the internal state of the object), and add the following as the first statement:

 if (isFrozen()) {
 throw new UnsupportedOperationException("Attempt to modify frozen object");
 }
 

Subclassing

Any subclass of a Freezable will just use its superclass's flagging field. It must override freeze() and cloneAsThawed() to call the superclass, but normally does not override isFrozen(). It must then just pay attention to its own getters, setters and fields.

Internal Caches

Internal caches are cases where the object is logically unmodified, but internal state of the object changes. For example, there are const C++ functions that cast away the const on the "this" pointer in order to modify an object cache. These cases are handled by mutexing the internal cache to ensure thread-safety. For example, suppose that UnicodeSet had an internal marker to the last code point accessed. In this case, the field is not externally visible, so the only thing you need to do is to synchronize the field for thread safety.

Unsafe Internal Access

Internal fields are called safe if they are either frozen or immutable (such as String or primitives). If you've never allowed internal access to these, then you are all done. For example, converting UnicodeSet to be Freezable is just accomplished with the above steps. But remember that you have allowed access to unsafe internals if you have any code like the following, in a getter, setter, or constructor:

 Collection getStuff() {
 return stuff;
 } // caller could keep reference & modify
 void setStuff(Collection x) {
 stuff = x;
 } // caller could keep reference & modify
 MyClass(Collection x) {
 stuff = x;
 } // caller could keep reference & modify
 

These also illustrated in the code sample in Background above.

To deal with unsafe internals, the simplest course of action is to do the work in the freeze() function. Just make all of your internal fields frozen, and set the frozen flag. Any subsequent getter/setter will work properly. Here is an example:

 public Object freeze() {
 if (!frozen) {
 foo.freeze();
 frozen = true;
 }
 return this;
 }
 

If the field is a Collection or Map, then to make it frozen you have two choices. If you have never allowed access to the collection from outside your object, then just wrap it to prevent future modification.

 zone_to_country = Collections.unmodifiableMap(zone_to_country);
 

If you have ever allowed access, then do a clone() before wrapping it.

 zone_to_country = Collections.unmodifiableMap(zone_to_country.clone());
 

If a collection (or any other container of objects) itself can contain mutable objects, then for a safe clone you need to recurse through it to make the entire collection immutable. The recursing code should pick the most specific collection available, to avoid the necessity of later downcasing.

Note: An annoying flaw in Java is that the generic collections, like Map or Set, don't have a clone() operation. When you don't know the type of the collection, the simplest course is to just create a new collection:

 zone_to_country = Collections.unmodifiableMap(new HashMap(zone_to_country));
 




Method Summary
public  ObjectcloneAsThawed()
     Provides for the clone operation.
public  Objectfreeze()
     Locks the object.
public  booleanisFrozen()
     Determines whether the object has been locked or not.



Method Detail
cloneAsThawed
public Object cloneAsThawed()(Code)
Provides for the clone operation. Any clone is initially unlocked.



freeze
public Object freeze()(Code)
Locks the object. the object itself.



isFrozen
public boolean isFrozen()(Code)
Determines whether the object has been locked or not.



www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.