Re: Peterson's Algorithm in java, sequencial instruction execution ?
"Mike Schilling" <mscottschilling@hotmail.com> wrote or quoted in
Message-ID: <Bxoah.15796$Sw1.9105@newssvr13.news.prodigy.com>:
OK. Can you give me an example of how you'd use a PhantomReference
programmatically? I've asked this before on the n.g, and never gotten an
answer.
As far as I know, PhantomReference can be used for cleanup.
For example ..
<code_0>
//
// Suppose that Resource R must be cleaned up after used.
//
class Resource_Bank {
Resource loan() {
...
return R;
}
void refund(Resource R) {
// Clean up R
}
}
class Customer {
void X...(..) {
R = resource_Bank.loan();
...
}
void Y..(..) {
...
resource_Bank.refund( R );
}
}
</code_0>
For some reason, if Customer lose the reference of R before
she refunds R, Resource leak will occur.
To prevent this situation, the following code is possible:
<code_1>
class Resource_Wrap {
Resource R = ....;
...
protected void finalize() ... {
// Clean up R
}
}
</code_1>
But ...
If the cleanup process of R take long time, GC may exert
a harmful influence upon the performance of App.
Therefore, the following code will be better:
<code_2>
//
// Data structure, thread-safe etc were ignored to simplify
// this "code_2".
//
class Resource_Wrap {
Resource R = ....;
...
Resource getR() {
return R;
}
}
class Phantom extends PhantomReference<Resource_Wrap> {
Resource R;
public Phantom(Resource_Wrap RW, ReferenceQueue<...> rq) {
super(RW, rq);
R = RW.getR();
}
Resource getR() {
return R;
}
}
class Resource_Bank {
// Resource R0, R1, ... , Rn
ReferenceQueue<Resource_Wrap> rq = ...;
final int MAX_NUMBER = ...;
Resource_Wrap[] rw = ...;
Phantom[] pm = ...;
void initialize() {
for (int i = 0; i < MAX_NUMBER; ..) {
rw[i] = new Resource_Wrap( ... ); // Ri
pm[i] = new Phantom( rw[i], rq );
}
}
Resource_Wrap loan() {
for ( ... ) {
if ( .. ) {
Resource_Wrap RW = rw[i];
rw[i] = null; // if Customer lose RW,
// she will become phontom.
return RW;
}
}
....
}
void refund(Resource_Wrap RW) {
// Clean up R
}
void cleanupDaemon() {
Thread tr = new Thread() {
public void run() {
while (true) {
Phantom RW = (Phantom) rq.remove();
Resource R = RW.getR();
... // Clean up R
... // Clean up RW
}
}
};
.....
}
}
</code_2>
In addition to the above case,
I think that there will be other cases.