com.google.j2objc.annotations.AutoreleasePool Java Examples

The following examples show how to use com.google.j2objc.annotations.AutoreleasePool. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AsyncStorageActor.java    From actor-platform with GNU Affero General Public License v3.0 6 votes vote down vote up
@AutoreleasePool
public void loadHead(LoadItemCallback<T> callback) {
    List<ListEngineRecord> records = storage.loadForward(null, 1);

    if (records.size() != 1) {
        callback.onLoaded(null);
        return;
    }

    ListEngineRecord record = records.get(0);
    try {
        callback.onLoaded(Bser.parse(creator.createInstance(), record.getData()));
    } catch (IOException e) {
        e.printStackTrace();
        callback.onLoaded(null);
    }
}
 
Example #2
Source File: CBCBlockCipher.java    From actor-platform with GNU Affero General Public License v3.0 6 votes vote down vote up
@AutoreleasePool
private void encrypt(byte[] iv, byte[] data, byte[] res) {
    byte[] currentBlock = new byte[blockSize];

    byte[] currentIV = new byte[blockSize];
    for (int i = 0; i < blockSize; i++) {
        currentIV[i] = iv[i];
    }

    int count = data.length / blockSize;
    for (int i = 0; i < count; i++) {

        for (int j = 0; j < blockSize; j++) {
            currentBlock[j] = (byte) ((data[i * blockSize + j] & 0xFF) ^ (currentIV[j] & 0xFF));
        }

        blockCipher.encryptBlock(currentBlock, 0, res, i * blockSize);

        for (int j = 0; j < blockSize; j++) {
            currentIV[j] = res[i * blockSize + j];
        }
    }
}
 
Example #3
Source File: RetainedWithTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@AutoreleasePool
private void createMapChildren(MapFactory<K> factory,
    List<Integer> objectCodes) {
  // Use separate maps for each of the views to ensure that each view type is strengthening its
  // reference to the map.
  Map<K, ValueType> m1 = factory.newMap();
  Map<K, ValueType> m2 = factory.newMap();
  Map<K, ValueType> m3 = factory.newMap();
  ValueType v = new ValueType();
  m1.put(factory.getKey(), v);
  m2.put(factory.getKey(), v);
  m3.put(factory.getKey(), v);
  keys = m1.keySet();
  values = m2.values();
  entrySet = m3.entrySet();
  objectCodes.add(System.identityHashCode(v));
}
 
Example #4
Source File: SquidbTestRunner.java    From squidb with Apache License 2.0 6 votes vote down vote up
/**
 * Runs the test classes given in {@param classes}.
 *
 * @returns Zero if all tests pass, non-zero otherwise.
 */
public static int run(Class[] classes, RunListener listener, PrintStream out) {
    JUnitCore junitCore = new JUnitCore();
    junitCore.addListener(listener);
    boolean hasError = false;
    int numTests = 0;
    int numFailures = 0;
    long start = System.currentTimeMillis();
    for (@AutoreleasePool Class c : classes) {
        out.println("Running " + c.getName());
        Result result = junitCore.run(c);
        numTests += result.getRunCount();
        numFailures += result.getFailureCount();
        hasError = hasError || !result.wasSuccessful();
    }
    long end = System.currentTimeMillis();
    out.println(String.format("Ran %d tests, %d failures. Total time: %s seconds", numTests, numFailures,
            NumberFormat.getInstance().format((double) (end - start) / 1000)));
    return hasError ? 1 : 0;
}
 
Example #5
Source File: AsyncStorageActor.java    From actor-platform with GNU Affero General Public License v3.0 6 votes vote down vote up
@AutoreleasePool
private void callCallback(ListEngineDisplayLoadCallback<T> callback, List<T> res) {
    if (res.size() == 0) {
        callback.onLoaded(res, 0, 0);
    } else {
        long topSort, bottomSort;
        topSort = bottomSort = res.get(0).getEngineSort();

        for (T t : res) {
            long sort = t.getEngineSort();
            if (topSort < sort) {
                topSort = sort;
            }
            if (bottomSort > sort) {
                bottomSort = sort;
            }
        }

        callback.onLoaded(res, topSort, bottomSort);
    }
}
 
Example #6
Source File: Rewriter.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Override
public boolean visit(MethodDeclaration node) {
  ExecutableElement element = node.getExecutableElement();
  if (ElementUtil.hasAnnotation(element, AutoreleasePool.class)) {
    if (TypeUtil.isReferenceType(element.getReturnType())) {
      ErrorUtil.warning(
          "Ignoring AutoreleasePool annotation on method with retainable return type");
    } else if (node.getBody() != null) {
      node.getBody().setHasAutoreleasePool(true);
    }
  }

  if (ElementUtil.hasNullableAnnotation(element) || ElementUtil.hasNonnullAnnotation(element)) {
    unit.setHasNullabilityAnnotations();
  }
  return true;
}
 
Example #7
Source File: Rewriter.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Override
public void endVisit(ForStatement node) {
  // It should not be possible to have multiple VariableDeclarationExpression
  // nodes in the initializers.
  if (node.getInitializers().size() == 1) {
    Object initializer = node.getInitializer(0);
    if (initializer instanceof VariableDeclarationExpression) {
      List<VariableDeclarationFragment> fragments =
          ((VariableDeclarationExpression) initializer).getFragments();
      for (VariableDeclarationFragment fragment : fragments) {
        if (ElementUtil.hasAnnotation(fragment.getVariableElement(), AutoreleasePool.class)) {
          Statement loopBody = node.getBody();
          if (!(loopBody instanceof Block)) {
            Block block = new Block();
            node.setBody(block);
            block.addStatement(loopBody);
          }
          ((Block) node.getBody()).setHasAutoreleasePool(true);
        }
      }
    }
  }
}
 
Example #8
Source File: EnhancedForRewriter.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Override
public void endVisit(EnhancedForStatement node) {
  Expression expression = node.getExpression();
  TypeMirror expressionType = expression.getTypeMirror();
  VariableElement loopVariable = node.getParameter().getVariableElement();

  if (ElementUtil.hasAnnotation(loopVariable, AutoreleasePool.class)) {
    makeBlock(node.getBody()).setHasAutoreleasePool(true);
  }

  if (TypeUtil.isArray(expressionType)) {
    handleArrayIteration(node);
  } else if (emitJavaIteratorLoop(loopVariable)) {
    convertToJavaIteratorLoop(node);
  } else if (loopVariable.asType().getKind().isPrimitive()) {
    boxLoopVariable(node, expressionType, loopVariable);
  } else {
    VariableElement newLoopVariable = GeneratedVariableElement.mutableCopy(loopVariable)
        .setTypeQualifiers("__strong");
    node.getParameter().setVariableElement(newLoopVariable);
  }
}
 
Example #9
Source File: WeakHashMapTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void testWeakHashMap() {
  WeakHashMap<Integer, String> weakMap = new WeakHashMap<Integer, String>();
  for (@AutoreleasePool int i = 0; i < 1; i++) {
    // Add a map entry.
    String value = "value";
    Integer key = Integer.valueOf(666);
    Object[] array = new Object[1];
    array[0] = key;
    array = null;
    weakMap.put(key, value);
    assertSame("weak map get doesn't return referent", value, weakMap.get(key));

    // Clear key, verify it's still available in the reference.
    key = null;
    assertEquals("weak map released key/value before autorelease", 1, weakMap.size());
  }

  // Verify weak reference was cleared.
  assertTrue("weakMap not empty", weakMap.isEmpty());
}
 
Example #10
Source File: WeakReferenceTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void testWeakReferenceMap() {
  // weak_ref_maps in IOSReference should not call referent's hashCode().
  final int[] hashCodeCount = { 0 };
  for (@AutoreleasePool int i = 0; i < 1; i++) {
    Object referent = new Object() {
      @Override
      public int hashCode() {
        hashCodeCount[0]++;
        return super.hashCode();
      }
    };

    weakRef = new WeakReference<Object>(referent);
    referent = null;
  }
  // Verify that referent's hashCode() was not called
  assertEquals("referent's hashCode() was called", 0, hashCodeCount[0]);
}
 
Example #11
Source File: CBCBlockCipher.java    From actor-platform with GNU Affero General Public License v3.0 6 votes vote down vote up
@AutoreleasePool
private void decrypt(byte[] iv, byte[] data, byte[] res) {
    byte[] r = new byte[blockSize];
    for (int i = 0; i < blockSize; i++) {
        r[i] = iv[i];
    }

    int count = data.length / blockSize;
    for (int i = 0; i < count; i++) {

        blockCipher.decryptBlock(data, i * blockSize, res, i * blockSize);

        for (int j = 0; j < blockSize; j++) {
            res[i * blockSize + j] = (byte) ((res[i * blockSize + j] & 0xFF) ^ (r[j] & 0xFF));
        }

        for (int j = 0; j < blockSize; j++) {
            r[j] = data[i * blockSize + j];
        }
    }
}
 
Example #12
Source File: WeakReferenceTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void testWeakReference() {
  final int[] finalizeCount = { 0 };
  for (@AutoreleasePool int i = 0; i < 1; i++) {
    // Create a referent inside this autorelease pool.
    Object referent = new Object() {
      public void finalize() {
        finalizeCount[0]++;
      }
    };
    weakRef = new WeakReference<Object>(referent);
    assertSame("weakRef get doesn't return referent", referent, weakRef.get());

    // Clear referent ref, verify it's still available in the reference.
    referent = null;
    assertNotNull("weakRef cleared too soon", weakRef.get());
    assertEquals("referent dealloc'ed too soon", 0, finalizeCount[0]);
  }

  // Verify weak reference was cleared.
  assertNull("weakRef wasn't cleared", weakRef.get());
  assertEquals("referent wasn't dealloc'ed", 1, finalizeCount[0]);
}
 
Example #13
Source File: SoftReferenceTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void testSoftReferenceSet() {
  // soft_references in IOSReference should not call referent's hashCode().
  final int[] hashCodeCount = { 0 };
  for (@AutoreleasePool int i = 0; i < 1; i++) {
    Object referent = new Object() {
      @Override
      public int hashCode() {
        hashCodeCount[0]++;
        return super.hashCode();
      }
    };

    softRef = new SoftReference<Object>(referent);
    referent = null;
  }
  fakeLowMemoryNotification();
  // Verify that referent's hashCode() was not called
  assertEquals("referent's hashCode() was called", 0, hashCodeCount[0]);
}
 
Example #14
Source File: SoftReferenceTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void testSoftReferenceCleanedUpWhenNotReachable() {
  final boolean[] dealloced = { false };
  for (@AutoreleasePool int i = 0; i < 1; i++) {
    for (@AutoreleasePool int j = 0; j < 1; j++) {
      Object referent = new Object() {
        public void finalize() {
          dealloced[0] = true;
        }
      };
      softRef = new SoftReference<Object>(referent);
      assertFalse("referent dealloc'ed too soon", dealloced[0]);
    }
    softRef = null;
    assertFalse("referent dealloc'ed too soon", dealloced[0]);
  }
  assertTrue("referent wasn't dealloc'ed", dealloced[0]);
}
 
Example #15
Source File: AsyncPipedNSInputStreamAdapterTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@AutoreleasePool
public void testPartialWrite() {
  DataProvider provider = new DataProvider(randomData, PARTIAL_SIZE);
  NativeInputStreamConsumer consumer = new NativeInputStreamConsumer();
  Object stream = AsyncPipedNSInputStreamAdapter.create(provider, STREAM_BUFFER_SIZE);
  consumer.readUntilEnd(stream);
  assertEquals(PARTIAL_SIZE, provider.getTotalWritten());
  assertEquals(PARTIAL_SIZE, consumer.getBytes().length);
  assertTrue(
      "Unexpected data was read",
      Arrays.equals(Arrays.copyOfRange(randomData, 0, PARTIAL_SIZE), consumer.getBytes()));
}
 
Example #16
Source File: AsyncPipedNSInputStreamAdapterTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@AutoreleasePool
public void testNothingRead() {
  DataProvider provider = new DataProvider(randomData);
  NativeInputStreamConsumer consumer = new NativeInputStreamConsumer(0);
  Object stream = AsyncPipedNSInputStreamAdapter.create(provider, STREAM_BUFFER_SIZE);
  consumer.readUntilEnd(stream);
  assertTrue("Less was written than expected", provider.getTotalWritten() >= 0);
  assertEquals(0, consumer.getBytes().length);
}
 
Example #17
Source File: AsyncPipedNSInputStreamAdapterTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@AutoreleasePool
public void testPartialRead() {
  DataProvider provider = new DataProvider(randomData);
  NativeInputStreamConsumer consumer = new NativeInputStreamConsumer(PARTIAL_SIZE);
  Object stream = AsyncPipedNSInputStreamAdapter.create(provider, STREAM_BUFFER_SIZE);
  consumer.readUntilEnd(stream);
  assertTrue("Less was written than expected: " + provider.getTotalWritten(),
      provider.getTotalWritten() >= PARTIAL_SIZE);
  assertEquals(PARTIAL_SIZE, consumer.getBytes().length);
  assertTrue(Arrays.equals(Arrays.copyOfRange(randomData, 0, PARTIAL_SIZE), consumer.getBytes()));
}
 
Example #18
Source File: LinkedListTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@AutoreleasePool
public void testLongListWithClear() {
  LinkedList<Integer> list = new LinkedList<>();
  insertIntoList(list, SIZE_LARGE);
  list.clear();
  assertTrue(list.isEmpty());
}
 
Example #19
Source File: AsyncPipedNSInputStreamAdapterTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@AutoreleasePool
public void testNothingWritten() {
  DataProvider provider = new DataProvider(randomData, 0);
  NativeInputStreamConsumer consumer = new NativeInputStreamConsumer();
  Object stream = AsyncPipedNSInputStreamAdapter.create(provider, STREAM_BUFFER_SIZE);
  consumer.readUntilEnd(stream);
  assertEquals(0, provider.getTotalWritten());
  assertEquals(0, consumer.getBytes().length);
}
 
Example #20
Source File: AsyncPipedNSInputStreamAdapterTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@AutoreleasePool
public void testFullWriteAndRead() {
  DataProvider provider = new DataProvider(randomData);
  NativeInputStreamConsumer consumer = new NativeInputStreamConsumer();
  Object stream = AsyncPipedNSInputStreamAdapter.create(provider, STREAM_BUFFER_SIZE);
  consumer.readUntilEnd(stream);

  assertTrue("The source was not fully read", Arrays.equals(randomData, consumer.getBytes()));
}
 
Example #21
Source File: RetainedWithTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@AutoreleasePool
private void checkMapChildren(MapFactory<K> factory, List<Integer> objectCodes) {
  createMapChildren(factory, objectCodes);
  // Call some methods to make sure they still exist and can access the parent
  assertEquals(1, keys.size());
  assertEquals(1, values.size());
  assertEquals(1, entrySet.size());
  assertTrue(keys.contains(factory.getKey()));
  assertFalse(values.contains(new ValueType()));
  assertEquals(factory.getKey(), entrySet.iterator().next().getKey());
  keys = null;
  values = null;
  entrySet = null;
}
 
Example #22
Source File: SoftReferenceTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void testSoftReference() {
  final int[] finalizeCount = { 0 };
  for (@AutoreleasePool int i = 0; i < 1; i++) {
    for (@AutoreleasePool int j = 0; j < 1; j++) {
      // Create a referent inside this autorelease pool.
      Object referent = new Object() {
        public void finalize() {
          finalizeCount[0]++;
        }
      };
      softRef = new SoftReference<Object>(referent);
      assertSame("softRef get doesn't return referent", referent, softRef.get());

      // Clear referent ref, verify it's still available in the reference.
      referent = null;
      assertNotNull("softRef was cleared", softRef.get());
      assertEquals("referent dealloc'ed too soon", 0, finalizeCount[0]);
    }

    // Verify soft reference wasn't cleared.
    assertNotNull("softRef was cleared", softRef.get());
    assertEquals("referent dealloc'ed too soon", 0, finalizeCount[0]);
  }

  // Send low memory notification and verify reference was released.
  fakeLowMemoryNotification();
  assertNull("softRef was not cleared", softRef.get());
  assertEquals("referent wasn't dealloc'ed", 1, finalizeCount[0]);
}
 
Example #23
Source File: AsyncPipedNSInputStreamAdapterTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@AutoreleasePool
public void testTrivialCreate() {
  DataProvider provider = new DataProvider(randomData);
  Object stream = AsyncPipedNSInputStreamAdapter.create(provider, STREAM_BUFFER_SIZE);
  assertNotNull(stream);

  // This is to test that the background thread created by the adapter is retaining the stream
  // objects properly. If it were not, the program would crash after this method exits and its
  // outer autorelease pool drains.
}
 
Example #24
Source File: JUnitTestRunner.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the test classes given in {@param classes}.
 * @returns Zero if all tests pass, non-zero otherwise.
 */
public static int run(Class<?>[] classes, RunListener listener) {
  JUnitCore junitCore = new JUnitCore();
  junitCore.addListener(listener);
  boolean hasError = false;
  for (@AutoreleasePool Class<?> c : classes) {
    Result result = junitCore.run(c);
    hasError = hasError || !result.wasSuccessful();
  }
  return hasError ? 1 : 0;
}
 
Example #25
Source File: MemoryTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testRetainingConstructorThrows() {
  for (@AutoreleasePool int i = 0; i < 1; i++) {
    try {
      // Assigning directly to a field will translate to the retaining constructor.
      staticObjectField = new ConstructorThrowsType();
      fail("Constructor was expected to throw.");
    } catch (ConstructionException t) {
      // Expected
    }
  }
  assertEquals(1, ConstructorThrowsType.dealloced);
}
 
Example #26
Source File: RetainedWithTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@AutoreleasePool
private void newAPlusClone(List<Integer> objectCodes) {
  A a = new A();
  A a2 = a.clone();
  assertSame(a.b, a2.b);
  // We allow this reassignment of a2.b because the child's return reference points at "a" not
  // "a2". It is important to support setting the child reference to null after cloning the
  // parent.
  a2.b = null;
  objectCodes.add(System.identityHashCode(a));
  objectCodes.add(System.identityHashCode(a2));
  objectCodes.add(System.identityHashCode(a.b));
}
 
Example #27
Source File: WeakReferenceTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueuedWeakReference() {
  final boolean[] dealloced = { false };
  ReferenceQueue<? super Object> queue = new ReferenceQueue<Object>();
  for (@AutoreleasePool int i = 0; i < 1; i++) {
    Object referent = new Object() {
      public void finalize() {
        dealloced[0] = true;
      }
    };
    weakRef = new WeakReference<Object>(referent, queue);
    assertSame("weakRef.get doesn't return referent", referent, weakRef.get());

    // Remove reference to o, verify it's still available in the reference.
    referent = null;
    assertNotNull("weakRef cleared too soon", weakRef.get());
    assertFalse("referent dealloc'ed too soon", dealloced[0]);
  }

  // Verify weak reference was queued.
  Reference<?> queuedRef = queue.poll();
  assertNotNull("weakRef wasn't queued", queuedRef);

  // Verify weak reference was cleared.
  assertNull("weakRef wasn't cleared", weakRef.get());
  assertTrue("referent wasn't dealloc'ed", dealloced[0]);
}
 
Example #28
Source File: PhantomReferenceTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueuedPhantomReference() {
  ReferenceQueue<? super Object> queue = new ReferenceQueue<Object>();
  for (@AutoreleasePool int i = 0; i < 1; i++) {
    Object referent = new Object();
    phantomRef = new PhantomReference<Object>(referent, queue);
    assertNull("phantomRef returned referent", phantomRef.get());
  }

  // Verify phantom reference was queued.
  Reference<?> queuedRef = queue.poll();
  assertNotNull("phantomRef wasn't queued", queuedRef);
}
 
Example #29
Source File: SoftReferenceTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueuedSoftReference() {
  final boolean[] dealloced = { false };
  ReferenceQueue<? super Object> queue = new ReferenceQueue<Object>();
  for (@AutoreleasePool int i = 0; i < 1; i++) {
    for (@AutoreleasePool int j = 0; j < 1; j++) {
      Object referent = new Object() {
        public void finalize() {
          dealloced[0] = true;
        }
      };
      softRef = new SoftReference<Object>(referent, queue);
      assertSame("softRef.get doesn't return referent", referent, softRef.get());

      // Remove reference to o, verify it's still available in the reference.
      referent = null;
      assertNotNull("softRef was cleared", softRef.get());
      assertFalse("referent dealloc'ed too soon", dealloced[0]);
    }

    // Verify soft reference wasn't queued.
    Reference<?> queuedRef = queue.poll();
    assertNull("softRef was queued", queuedRef);

    // Verify soft reference wasn't cleared.
    assertNotNull("softRef was cleared", softRef.get());
    assertFalse("referent dealloc'ed too soon", dealloced[0]);
  }

  // Send low memory notification and verify reference was queued.
  fakeLowMemoryNotification();
  Reference<?> queuedRef2 = queue.poll();
  assertNotNull("softRef wasn't queued", queuedRef2);

  // Verify soft reference was cleared.
  assertNull("softRef wasn't cleared", softRef.get());
  assertTrue("referent wasn't dealloc'ed", dealloced[0]);
}
 
Example #30
Source File: ConcurrentHashMapTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Elements of non-comparable classes equal to those of classes
 * with erased generic type parameters based on Comparable can be
 * inserted and found.
 */
public void testGenericComparable2() {
    int size = 500;         // makes measured test run time -> 60ms
    ConcurrentHashMap<Object, Boolean> m =
        new ConcurrentHashMap<Object, Boolean>();
    for (int i = 0; i < size; i++) {
        m.put(Collections.singletonList(new BI(i)), true);
    }

    for (@AutoreleasePool int i = 0; i < size; i++) {
        LexicographicList<BI> bis = new LexicographicList<BI>(new BI(i));
        assertTrue(m.containsKey(bis));
    }
}