Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: d09f1fb3640fd9ebaa4d6034ac4e9eabeb27d28c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/***************************************************************************
 * Copyright (c) 2004 - 2008 Eike Stepper, Germany.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *    Eike Stepper - initial API and implementation
 **************************************************************************/
package org.eclipse.net4j.tests;

import org.eclipse.net4j.IBuffer;
import org.eclipse.net4j.IBufferPool;
import org.eclipse.net4j.Net4jUtil;
import org.eclipse.net4j.util.ReflectUtil;
import org.eclipse.net4j.util.io.IOUtil;
import org.eclipse.net4j.util.lifecycle.LifecycleUtil;
import org.eclipse.net4j.util.tests.AbstractOMTest;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author Eike Stepper
 */
public class BufferPoolTest extends AbstractOMTest
{
  private static IBufferPool bufferPool = Net4jUtil.createBufferPool();

  private static Collection<byte[]> memory = new ArrayList<byte[]>();

  @Override
  protected void doTearDown() throws Exception
  {
    memory.clear();
    super.doTearDown();
  }

  public void testBufferPool() throws Exception
  {
    LifecycleUtil.activate(bufferPool);

    IBuffer[] buffers = new IBuffer[10];
    for (int i = 0; i < buffers.length; i++)
    {
      buffers[i] = bufferPool.provideBuffer();
    }

    for (int i = 0; i < buffers.length; i++)
    {
      bufferPool.retainBuffer(buffers[i]);
      buffers[i] = null;
    }

    while (Net4jUtil.getPooledBuffers(bufferPool) > 0 && allocate())
    {
      sleep(200);
      ReflectUtil.dump(bufferPool);
    }

    LifecycleUtil.deactivate(bufferPool);
  }

  private static void msg()
  {
    msg("pooledBuffers = " + Net4jUtil.getPooledBuffers(bufferPool));
  }

  private static boolean allocate()
  {
    try
    {
      IOUtil.OUT().println("allocating from " + Runtime.getRuntime().freeMemory());
      for (int i = 0; i < 10; i++)
      {
        memory.add(new byte[1000000]);
      }

      msg();
      return true;
    }
    catch (Throwable t)
    {
      return false;
    }
  }

  @SuppressWarnings("unused")
  private static void gc()
  {
    msg();
    IOUtil.OUT().println("collecting garbage");
    System.gc();
    msg();
  }
}

Back to the top