Created
July 13, 2018 15:55
-
-
Save JamesMenetrey/db5b393a23851568952b173fe5c69772 to your computer and use it in GitHub Desktop.
Java 10 Cleaner
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class InstanceAroundResource implements AutoCloseable{ | |
//(1)We will delegeta cleaning to Cleaner from Java 9 | |
private static final Cleaner cleaner=Cleaner.create(); | |
//(2)This is definition of internal state, static -> so it has no ref to external instance | |
//private - to better hide information | |
private static class EncapsulatedResource implements Runnable{ | |
(...) | |
} | |
//(3)no getters for those two fields, no strange hakiers annotations either | |
private final EncapsulatedResource state; | |
//this triggers cleaning procedure | |
private final Cleaner.Cleanable cleanable; | |
public InstanceAroundResource(String resourceId) { | |
//(4)notice that both instances are created inside constructor , no direct assignment, | |
//no information how resourceId is escapes outside | |
//compare this with stntaxt 'this.field = field' which is hiding information like in the sentence | |
// "think about number seven but don't tell what the number is" | |
this.state = new EncapsulatedResource("[opened :"+resourceId+"]"); | |
this.cleanable = cleaner.register(this, state); | |
} | |
//(5) here we are connecting Cleaner with Autocloseable from Java7 | |
@Override | |
public void close() throws Exception { | |
cleanable.clean(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment