Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 8d8d201fa8168312bd31dd52a8182e8138b2c5c9 (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
/***************************************************************************
 * Copyright (c) 2004-2007 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.internal.util.om.trace.PrintTraceHandler;
import org.eclipse.net4j.util.ReflectUtil;
import org.eclipse.net4j.util.lifecycle.LifecycleUtil;
import org.eclipse.net4j.util.om.OMPlatform;

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

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

  private static Collection memory = new ArrayList();

  public static void main(String[] args) throws InterruptedException
  {
    OMPlatform.INSTANCE.addTraceHandler(PrintTraceHandler.CONSOLE);
    OMPlatform.INSTANCE.setDebugging(true);
    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())
    {
      Thread.sleep(200);
      ReflectUtil.dump(bufferPool);
    }

    LifecycleUtil.deactivate(bufferPool);
  }

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

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

      msg();
      return true;
    }
    catch (Exception ex)
    {
      return false;
    }
  }

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

Back to the top