星期四, 九月 30, 2004
FireFox中的XML和XSLT的使用及SOAP的引用..
这里有几篇文章非常不错.关于在FireFox中的确XML/XSLT的引用.
Updating DHTML Web Pages for next generation browsers
SOAP in Netscape Gecko-based Browsers
Accessing Web Services In Netscape 7.1/Mozilla 1.4 Using WSDL Proxying
Groovy 1.0 beta 7增加了embed 使用的jar库
Today 2004.9.30.groovy 1 beta 7发表
不过看了看change log.文档没有加入,修改的几个BUG.我都没碰到.
有关ClassLoader的问题,也没有修改.
只是一个小小的版本改动.
星期三, 九月 29, 2004
利用XMLHttpRequest对象来提交数据.
When using XMLHttpRequest object, there is a way to post data in the same way that an HTML Form is posted.
All you need to do is add an HTTP header, and send the data the same way you'd send it on the QueryString.
Here's a JScript example for the client side, that submits form data to another page:
var objHTTP, strResult;
objHTTP = new ActiveXObject('Microsoft.XMLHTTP');
objHTTP.Open('POST',"OtherPage.asp",false);
objHTTP.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
objHTTP.send("id=1&user="+txtUser.value+"&password="+txtPassword.value);
strResult=objHTTP.responseText;
星期一, 九月 27, 2004
欢迎你来到异次元空间!
自爱因斯坦之后,我们关于时空的最奇幻的构思.
我们处在一个最多11维的时空中.
自1995 Nova发表 Welcome to the 11th Dimension论文以来的进展有多少呢?实验室数据如何设计来证明这个理论呢?
有趣的思考.
图片来自:http://groups.msn.com/Realms-Of-Light/thedivinehologramofspirit.msnw
|
Nova The Elegant Universe: Welcome to the 11th Dimension "The Elegant Universe: Welcome to the 11th Dimension," shows how in 1995 Edward Witten of Princeton's Institute for Advanced Study, aided by others, revolutionized string theory by successfully uniting the five different versions into a single theory that is cryptically named "M-theory," a development which required a total of eleven dimensions. Ten...eleven...who's counting? But the new eleventh dimension is different from all the others, since it implies that strings can come in higher dimensional shapes called membranes, or " branes" for short. These have truly science-fiction-like qualities, since in principle they can be as large as the universe. A brane can even be a universe -- a parallel universe -- and we may be living on one right now. Branes might also explain why gravity is the weakest force, requiring all the matter in the Earth to produce a measly one g. According to this idea, gravity may be far more potent, but most of its strength is leaking into a parallel universe. Witten has described string theory as "a part of 21st-century physics that fell by chance into the 20th century." In fact, the theory is so far ahead of experimental technique that there is as yet no way to verify whether strings are real or a figment of some very creative imaginations. But scientists at the CERN atom-smasher on the French- Swiss border are working to test of one of the predictions of string theory. Scheduled to run later in this decade, this experiment may take an important step in showing that string theory is not just a crazy idea, but crazy reality. (CC) (D) |
如何让Google机器人搜索自己的网站呢?
http://webdesign.about.com/cs/googleoptimization/
关于SEO(Search Engine Optimized)的话题很久了.
但是我不知道Googlebot关于robots.txt和<meta name="Googlebot" content="index,follow"/>
的优先级别顺序是怎样的?
所以需要测试.不过先把<meta>标志加入网页再说其他了.:)
星期五, 九月 24, 2004
B/S开发的新里程碑(B/S application Milestone)XMLHttpRequest
动态HTML及XML:介绍XMLHttpRequest对象
(翻译:有增删:原文见:TaH Website
随着XML数据和Web服务的部署越来越普遍,你偶尔会觉的如果在HTML表现层不需要刷新页面而直接
得到XML数据来更新中间状态也是非常方便的.要感谢可爱的 XMLHttpRequest对象,可以在后台直接
提交或获得XML 数据,这扩展了Web Client的使用范围.
为了改变接受到的XML 数据并渲染成HTML内容,依赖于客户端DOM读取XML文档节点树组成用户最终
看见的HTML元素
历史和支持
Microsoft首先在IE 5 window版本用ActiveX技术实现了XMLHttpRequest对象.Mozilla 项目的工程
师们实现了兼容的本地版本Mozilla 1.0(及Netscape 7).Apple在Safari 1.2上完成了同样的工作.
包含W3C标准期望的相似的功能,DOM level 3载入及保存规范.同时随着支持XMLHttpRequest对象意味着这已经成为事实的标准.以后W3C的规范最终应该会支持它并且所有的browser都会支持的。
如何建立对象?
建立一个XMLHttpRequest对象要求根据不同的Browser用不同的方式来实例化对象.对Safari和
Mozila系列.简单调用对象的constructor功能就可以完成这个:
var req = new XMLHttpRequest();
对使用ActiveX的对象,通过传递对象名称来建立:
var req = new ActiveXObject("Microsoft.XMLHTTP");
两种构造方法都返回一个抽象对象的引用.它的方法控制所有的操作,同时他的属性从服务器返回的数据
对象方法
XMLHttpRequest对象在所有支持的环境中使用都非常简明,但是非常强大,列表所有的方法和属性
Table 1显示Safari 1.2,Mozilla及IE 5及以后的windows版本.
Table 1. 一般XMLHttpRequest对象方法
| 方法 | 描述 |
| abort() | 停止当前请求 |
| getAllResponseHeaders() | 返回一组标题头(标识及其值)字符串 |
| getResponseHeader("headerLabel") | 返回指定头标识的字符串值 |
| open("method", "URL"[, asyncFlag[, "userName"[, "password"]]]) | 给一个等待状态的请求制定目标URL,方法及其它可选的属性 |
| send(content) | 发送请求,另外可以附加提交的字符传或DOM对象数据 |
| setRequestHeader("label", "value") | 跟随请求设定指顶的标题标识及其值. |
在Table 1中显示的方法.open()和send()方法可能是你最常用的.
首先open(),用来设置一个将要用的操作场景.两个必须的参数是你将要请求的HTTP方法和连接的目
的URL.对于method参数,你可以设置"GET"接受基本数据.然后使用"POST"发送数据到服务器,尤其是数据可能大于512字节.URL可以是绝对或相对地址(不过可能引起Browser安全问题)
重要的第三个选项参数是Boolean值用来控制是否将来的事物是否异步.默认的行为是true既异步,
这表示脚本进程在调用send()后立即返回不要等待回应.如果你设置这个值为false,那么,脚本将等
到服务器返回数据为止.看起来似乎等待服务器返回数据再继续脚本进程是个好主意.但是这样做可能导致脚本因为网络或服务器问题而不能完成事务,导致脚本挂死.一个安全的主意是用send 异步操作方式,但把代码挂在onreadstatechange事件上是个好主意.
如下例:
var req;
function loadXMLDoc(url) {
// branch for native XMLHttpRequest object
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.send(null);
// branch for IE/Windows ActiveX version
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.send();
}
}
}
注意:从服务器返回的数据必须保证Content-Type是:text/xml 内容设置为text/plain或text/html
不被request对象接受.
对象属性
Table 2. 所有属性都是只读的
Table 2. 常见 XMLHttpRequest对象属性
| 属性 | 说明 |
| onreadystatechange | 当每个状态改变时产生的事件 |
| ReadyState | 对象状态整数0 = uninitialized1 = loading2 = loaded3 = interactive4 = complete |
| responseText | 服务器返回结果的字符串样本 |
| responseXML | DOM规范的服务器返回结果 |
| status Numeric | code returned by server, such as 404 for "Not Found" or 200 for "OK" |
| statusText | String message accompanying the status code |
如何使用XMLHttpRequest和DIV来动态载入内容
红色的为关键代码。
<div id=content name="content" width=80% heigth=80% >
wait
</div>
<script>
var http;
http = new XMLHttpRequest();
try
{
http.open("GET", "http://wang.journalspace.com", true);
}catch(e)
{
netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead');
//弹出安全限制对话框,要用户授权。
http.open("GET", "http://wang.journalspace.com", true);
http.onreadystatechange=function() {
if (http.readyState==4) {
alert(http.responseText);
document.getElementById('content').innerHTML=http.responseText;
}
}
document.getElementById('content').innerHTML="Wait...";
http.send('');
}
</script>
Signed Scripts in Mozilla
http://www.mozilla.org/projects/security/components/signed-scripts.html
星期四, 九月 23, 2004
MySql如何增加一个新用户或改密码.
GRANT ALL PRIVILEGES ON *.* TO ehrm@"myhost" IDENTIFIED BY 'xxxxx' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON *.* TO ehrm@"%" IDENTIFIED BY 'xxxxx' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON *.* TO ehrm@localhost IDENTIFIED BY 'xxxxx' WITH GRANT OPTION;
FLUSH PRIVILEGES;
利用IE6和Javascript同服务器交互
When using XMLHttpRequest object, there is a way to post data in the same way that an HTML Form is posted.
All you need to do is add an HTTP header, and send the data the same way you'd send it on the QueryString.
Here's a JScript example for the client side, that submits form data to another page:
var objHTTP, strResult;
objHTTP = new ActiveXObject('Microsoft.XMLHTTP');
objHTTP.Open('POST',"OtherPage.asp",false);
objHTTP.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
objHTTP.send("id=1&user="+txtUser.value+"&password="+txtPassword.value);
strResult=objHTTP.responseText;
Javascript 同Regua参考资料
http://developer.netscape.com/viewsource/angus_strings.html
及通过.prototype扩展Javascript的功能.
http://www.javascriptkit.com/javatutors/proto4.shtml
星期三, 九月 22, 2004
如何避免GroovyClassLoader Defect 不足.避免动态类占用内存资源.
GroovyShell _shell=new GroovyShell(new Binding());
String text="tax=0.4; return 1000*tax;";
for(int i=0;i<3000;i++)
{
System.out.println(_shell.evaluate(text,"textScript.groovy"));
}
通过使用GroovyShell.evaluate(String script,String fileName)可以避免同一段脚本,被GroovyShell生成多个动态类保存在cache里.
如何使用JAX-RPC使用Java Object 当做Web Service
详细内容参考http://java.sun.com/developer/EJTechTips/2004/tt0824.html#1
星期二, 九月 21, 2004
如何利用Dynamic ClassLoader 来动态载入Class
import groovy.lang.GroovyShell;
import groovy.lang.Binding;
import groovy.lang.Closure;
import groovy.lang.Script;
import groovy.lang.*;
public class testGroovyMemoryLeak
{
public static void main(String[] args) throws Exception
{
String text="tax=0.4; return 1000*tax;";
ClassLoader parent = Thread.currentThread().getContextClassLoader();
GroovyObject groovyObject=null;
GroovyClassLoader loader=null;
Class groovyClass =null;
Object temp=null;
for(int i=0;i<3000;i++)
{
loader = new GroovyClassLoader(Thread.currentThread().getContextClassLoader());
groovyClass = loader.parseClass(text);
groovyObject = (GroovyObject) groovyClass.newInstance();
temp = groovyObject.invokeMethod("run", args);
System.out.println("value="+temp);
temp=null;
loader=null;
System.gc();
}
}
}
星期一, 九月 20, 2004
Java Groovy 1.0 beta 6避免GroovyClassloader不能GC Class的问题
不能回收解析脚本动态产生的Scriptxxxx class.
原因是Groovy MetaClass使用了 static HashMap 来cache生成的class.
解决办法,模拟groovy 自己产生一个GroovyObject Arrays.
然后,把动态生成的GroovyObject放入数组,只生成一次,以后直接从数组中载入Class对象实例。
星期日, 九月 19, 2004
TTS Ask:What do you want in Next Java?
1.Better NullPointerException display(臭名远播的NPE问题)
display what name and property get Null
2.Dynamic class
通过申明生成动态类(如果Groovy加入很多问题就解决了)
3.改善ClassLoader behavior
JVM ClassLoader drive me madness.要求清晰简单的行为定义
4.Raw Socket Support
本地Socket支持。哈。这样大多数黑客(Cracker)软件就用Java development了。:)
5.XML/XSLT/XPATH支持.目前的JAXP使用太复杂了。典型的过度设计(over Designed)
6.discard setter 和getter 在Bean上的使用。
目前的沉闷的getter和setter对策略让人发疯。为什么不使用bean.propetyName直接引用呢?
7.Debug 功能要加强
包括#ifdef macro和JVM DUMP及Heap snapshot功能。Third Part module is argly.
What is Next Bigger Feature of Java?
今天看到TSS上也有人赞赏加入Closure在下一个版本中。
自从J2SE 5.0发布后,支持Closure成了一个水到渠成的步骤。
因为AutoBox,AutoUnbox和Generetor泛型的支持已经为
J2SE支持Closure的自然加入了低层支持。
在C# 2中加入了匿名代理的功能,从设计角度来说,提供了基本相识的功能。
其实JVM只要在inner class的基础上加上Autobox和Generetor的提高。
基本上可以提供Closure的功能了。不过很多Closure可以提供的比如data Pine
依然无法提供。
所以最好重新设计Closure替代inner class.
原文:
http://www.theserverside.com/news/thread.tss?thread_id=28808
星期六, 九月 18, 2004
关于Java ClassLoader和Groovy Temporary Class Load and Unload
在Java 中通过GroovyShell或GroovyClassloader来调用存放在数据库中的脚本,Groovy 编译会产生大量的Scriptxxx,xxx表示顺序好的临时class,这些class根据java classloader的规范,就存放在cache中了。
所以一个循环调用Groovy script脚本,会引起内存为了保存这些临时class产生大量的空间。
为了避免ClassLoader对这些class的引用。
需要每次执行脚本时候,必须生成一个新的ClassLoader来调用,然后释放掉。
这样就可以让JVM回收这些空间了。
代码:
星期五, 九月 17, 2004
关于Java GC(Gargabe Collection)回收的机制
The Truth About Garbage Collection
Garbage collection (GC) is probably the most widely misunderstood feature
of the Java platform. GC is typically advertised as removing all memory management
responsibility from the application developer. This just isn't the case. On the
other hand, some developers bend over backwards trying to please the collector,
and often wind up doing much more work than is required. A solid understanding
of the garbage collection model is essential to writing robust, high-performance
software for the Java platform.
This appendix provides an overview of the garbage collection mechanisms that will help you make intelligent choices about memory management issues. It also contains information to help you debug complex problems such as memory leaks.
A.1 Why Should You Care About Garbage Collection?
The cost of allocating and collecting memory can play a significant role in how
your software performs. The overall memory requirements of your software can
have a huge impact on the speed of your program when large RAM requirements
force the OS to use virtual memory. This often occurs when memory is allocated,
but not properly released. Although the JVM is responsible for freeing unused
memory, you have to make it clear what is unused. To write successful, large-scale
programs, you need to understand the basics of the GC mechanism.
A.2 The Guarantees of GC
The specification for the Java platform makes very few promises about how garbage
collection actually works. Here is what the Java Virtual Machine Specification
(JVMS) has to say about memory management.
The heap is created on virtual machine start-up. Heap storage for objects is reclaimed by an automatic storage management system (known as a garbage collector); objects are never explicitly deallocated. The Java virtual machine assumes no particular type of automatic storage management system, and the storage management technique may be chosen according to the implementor's system requirements.1
While it can seem confusing, the fact that the garbage collection model is not rigidly defined is actually important and useful-a rigidly defined garbage collection model might be impossible to implement on all platforms. Similarly, it might preclude useful optimizations and hurt the performance of the platform in the long term.
Although there is no one place that contains a full definition of required garbage collector behavior, much of the GC model is implicitly specified through a number of sections in the Java Language Specification and JVMS. While there are no guarantees about the exact process followed, all compliant virtual machines share the basic object lifecycle described in this chapter.A.3 The Object Lifecycle
In order to discuss garbage collection, it is first useful to examine the object
lifecycle. An object typically goes through most of the following states between
the time it is allocated and the time its resources are finally returned to the system
for reuse.
A.3.1 Created
When an object is created, several things occur:2
- Space is allocated for the object.
- Object construction begins.
- The superclass constructor is called.
- Instance initializers and instance variable initializers are run.
- The rest of constructor body is executed.
The exact costs of these operations depend on the implementation of the JVM, as
well as the implementation of the class being constructed. The thing to keep in
mind is that these costs exist. Once the object has been created, assuming it is
assigned to some variable, it moves directly to the in use state.A.3.2 In Use
Objects that are held by at least one strong reference are considered to be in use.
In JDK 1.1.x, all references are strong references. Java 2 introduces three other
kinds of references: weak, soft and phantom. (These reference types are discussed
in Section A.4.1.) The example shown in Listing A-1 creates an object and assigns
it to some variables.
public class CatTest {
static Vector catList = new Vector();
static void makeCat() {
Object cat = new Cat();
catList.addElement(cat);
}
public static void main(String[] arg) {
makeCat();
// do more stuff
}
}
Creating and referencing an object
Figure A-1 shows the structure of the objects inside the VM just before themakeCatmethod returns. At that moment, two strong references point to theCatobject.
Object reference graph![]()
When themakeCatmethod returns, the stack frame for that method and any temporary variables it declares are removed. This leaves theCatobject with just a single reference from thecatListstatic variable (indirectly via theVector).A.3.3 Invisible
An object is in the invisible state when there are no longer any strong references
that are accessible to the program, even though there might still be references. Not
all objects go through this state, and it has been a source of confusion for some developers.
Listing A-2 shows a code fragment that creates an invisible object.public void run() {
try {
Object foo = new Object();
foo.doSomething();
} catch (Exception e) {
// whatever
}
while (true) { // do stuff } // loop forever
}
Invisible object
In this example, the objectfoofalls out of scope when thetryblock finishes. It might seem that thefootemporary reference variable would be pulled off the stack at this point and the associated object would become unreachable. After all, once thetryblock finishes, there is no syntax defined that would allow the program to access the object again. However, an efficient implementation of the JVM is unlikely to zero the reference when it goes out of scope. The object referenced byfoocontinues to be strongly referenced, at least until therunmethod returns. In this case, that might not happen for a long time. Because invisible objects can't be collected, this is a possible cause of memory leaks. If you run into this situation, you might have to explicitly null your references to enable garbage collection.
A.3.4 Unreachable
An object enters an unreachable state when no more strong references to it exist.
When an object is unreachable, it is a candidate for collection. Note the wording:
Just because an object is a candidate for collection doesn't mean it will be immediately
collected. The JVM is free to delay collection until there is an immediate
need for the memory being consumed by the object.
It's important to note that not just any strong reference will hold an object in memory. These must be references that chain from a garbage collection root. GC roots are a special class of variable that includes
- Temporary variables on the stack (of any thread)
- Static variables (from any class)
- Special references from JNI native code
Circular strong references don't necessarily cause memory leaks. Consider the code in Listing A-3. It creates two objects, and assigns them references to each other.public void buidDog() {
Dog newDog = new Dog();
Tail newTail = new Tail();
newDog.tail = newTail;
newTail.dog = newDog;
}
Circular reference
Figure A-2 shows the reference graph for the objects before thebuildDogmethod returns. Before the method returns, there are strong references from the temporary stack variables in thebuildDogmethod pointing to both theDogand theTail.Reference graph beforebuildDogreturns
![]()
Reference graph afterbuildDogreturns![]()
Figure A-3 shows the graph for the objects after thebuildDogmethod returns. At this point, theDogandTailboth become unreachable from a root and are candidates for collection (although the VM might not actually collect these objects for an indefinite amount of time).A.3.5 Collected
An object is in the collected state when the garbage collector has recognized an
object as unreachable and readies it for final processing as a precursor to deallocation.
If the object has afinalizemethod, then it is marked for finalization. If it
does not have a finalizer then it moves straight to the finalized state.
If a class defines a finalizer, then any instance of that class must have the finalizer called prior to deallocation. This means that deallocation is delayed by the inclusion of a finalizer.
A.3.6 Finalized
An object is in the finalized state if it is still unreachable after itsfinalize
method, if any, has been run. A finalized object is awaiting deallocation. Note that
the VM implementation controls when the finalizer is run. The only thing that can
be said for certain is that adding a finalizer will extend the lifetime of an object.
This means that adding finalizers to objects that you intend to be short-lived is a
bad idea. You are almost always better off doing your own cleanup instead of relying
on a finalizer. Using a finalizer can also leave behind critical resources that
won't be recovered for an indeterminate amount of time. If you are considering
using a finalizer to ensure that important resources are freed in a timely manner,
you might want to reconsider.
One case where afinalizemethod delayed GC was discovered by the quality assurance (QA) team working on Swing. The QA team created a stress testing application that simulated user input by using a thread to send artificial events to the GUI. Running on one version of the toolkit, the application reported anOutOfMemoryErrorafter just a few minutes of testing. The problem was finally traced back to the fact that the thread sending the events was running at a higher priority than the finalizer thread. The program ran out of memory because about 10,000Graphicsobjects were held in the finalizer queue waiting for a chance to run their finalizers. It turned out that theseGraphicsobjects were holding onto fairly substantial native resources. The problem was fixed by assuring that whenever Swing is done with aGraphicsobject,disposeis called to ensure that the native resources are freed as soon as possible.
In addition to lengthening object lifetimes, finalize methods can increase object size. For example, some JVMs, such as the classic JVM implementation, add an extra hidden field to objects withfinalizemethods so that they can be held in a linked list finalization queue.A.3.7 Deallocated
The deallocated state is the final step in garbage collection. If an object is still unreachable
after all the above work has occurred, then it is a candidate for deallocation.
Again, when and how deallocation occurs is up to the JVM.A.4 Reference Objects
Prior to the introduction of the Java 2 platform, all references were strong
references. This meant that there was no way for the developer to interact with the
garbage collector, except through brute force methods such asSystem.gc.
Thejava.lang.refpackage was introduced as part of Java 2. Figure A-4 shows the class hierarchy for the classes in this package. This package defines reference-object classes that enable a limited degree of interaction with the garbage collector.Referenceobjects are used to maintain a reference to some other object in such a way that the collector can still reclaim the target object. As you might expect, the addition of these new reference objects complicates the concept of reachability as defined in the object lifecycle. Understanding this is important,
even if you don't intend to make direct use of this package. Some of the core class libraries useWeakReferencesinternally, so you might encounter them while using memory profilers to track memory usage.Referenceclass hierarchy![]()
A.4.1 Types of Reference Objects
Three types of reference objects are provided, each weaker than the last: soft,
weak, and phantom. Each type corresponds to a different level of reachability:
- Soft references are for implementing memory-sensitive caches.
- Weak references are for implementing mappings that do not prevent their keys
(or values) from being reclaimed.
- Phantom references are for scheduling pre-mortem cleanup actions in a more
flexible way than is possible with the Java finalization mechanism.
Going from strongest to weakest, the different levels of reachability reflect the
lifecycle of an object:
- An object is strongly reachable if some thread can reach it without traversing
any reference objects.
- An object is softly reachable if it is not strongly reachable but can be reached
by traversing a soft reference.
- An object is weakly reachable if it is neither strongly nor softly reachable but
can be reached by traversing a weak reference. When the weak references
to a weakly reachable object are cleared, the object becomes eligible for
finalization.
- An object is phantom reachable if it is neither strongly, softly, nor weakly
reachable, it has been finalized, and some phantom reference refers to it.
- An object is unreachable, and therefore eligible for reclamation, when it is not
reachable in any of the preceding ways.
A.4.2 Example GC with WeakReference
You're likely to encounter special reference objects while using tools to look for
memory leaks. Only strong references will directly interfere with garbage collection.
If you find chains of objects linked by weak references, you should be able to
ignore them from a GC perspective. (For additional information on the use of
special reference objects, see the API documentation.)
Figure A-5 shows a graph of objects in memory for a sample program. Let's say that the problem with this program is that theDogobjects are not being collected, leading to a memory leak. By using a memory profiler, you can find all the pointers to theDogobject and follow them back to their GC roots. There are two GC roots in Figure A-5, a static variable in classKenneland a stack frame in a live thread. In this case, theWagTaskthread is in an infinite loop, forcing the dog's tail to wag. The question is how to get rid of theDogobject.
There are two references pointing to theDogobject, but only one of them is interesting from a GC perspective. TheWeakReferencefrom thedogCacheis not important. The interesting reference is the reference from theTail, which chains from a stack frame in a live thread. To free theDog, and the associatedTail, you need to terminate the thread that is wagging theTail. Once this thread is gone, everything falls into place. When an object that is pointed to by aWeakReferenceis collected, theWeakReferenceis automatically set tonull.Figure A-6 shows the result of terminating the wag thread.
Reference graph![]()
When the thread dies, its stack is removed. Now the only strong reference to theDogis via theTail, and this becomes a simple circular reference that isn't reachable from a GC root. TheDog, and by extension theTail, are no longer strongly reachable through any references. They are only weakly reachable through thedogCache.When the collector discovers this (which it does on its own schedule), it might set the weak reference tonull,making theDogandTailtotally unreachable. They then become candidates for collection and will be removed at the collector's discretion.
Results of garbage collection![]()
A.5 References on Garbage Collection
Arnold, Ken, and James Gosling. The Java Programming Language, Second Edition, Addison-Wesley, Reading, MA, 1998.
Gosling, James, Bill Joy, and Guy Steele. The Java Language Specification, Second Edition, Addison-Wesley, Reading, MA, 2000.
Jones, Richard, and Rafael Lins. Garbage Collection: Algorithms for Automatic Dynamic Memory Management, John Wiley & Sons, New York, 1996.
Lindholm, Tim and Frank Yellin. The Java Virtual Machine Specification, Second Edition, Addison-Wesley, Reading, MA, 1999.
Tim Lindholm and Frank Yellin, The Java Virtual Machine Specification, Second Edition, Section 3.5.3. Addison-Wesley, 1999.
James Gosling, Bill Joy, and Guy Steele, The Java Language Specification, Second Edition. Addison-Wesley, 2000.