Advertisement
DulcetAirman

Leaking Constructor

Apr 19th, 2013
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.88 KB | None | 0 0
  1. package com.example.foo;
  2.  
  3. public class SomeClass {
  4.   public static volatile SomeClass leak = null;
  5.   public final String string;
  6.  
  7.   public SomeClass(final boolean tru3) {
  8.     leak = this;
  9.     if (tru3)// always true!
  10.       throw new RuntimeException();
  11.     // This is the only place where something is assigned to "string":
  12.     this.string = "something";
  13.   }
  14.  
  15.   @Override
  16.   public String toString() {
  17.     return this.string;
  18.   }
  19.  
  20.   public static void main(final String[] args) throws Exception {
  21.     Object object = "nothing";
  22.     try {
  23.       object = new SomeClass(true);
  24.     } catch (final Exception e) {
  25.     }
  26.     System.out.printf("object = %s (%s)\n", object, object.getClass().getSimpleName());
  27.     try {
  28.       System.out.printf("leak = %s (%s)\n", leak, leak.getClass().getSimpleName());
  29.     } catch (final Exception e) {
  30.       System.out.println("" + e);
  31.     }
  32.   }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement