com.doctor.getting_started.UsingJava8BetterByUseMethodReference.java Source code

Java tutorial

Introduction

Here is the source code for com.doctor.getting_started.UsingJava8BetterByUseMethodReference.java

Source

/*
 * Copyright (C) 2014-present  The  Disruptor-2015  Authors
 *
 * https://github.com/sdcuike
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.doctor.getting_started;

import java.nio.ByteBuffer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import com.google.common.base.Stopwatch;
import com.lmax.disruptor.dsl.Disruptor;

/**
 * This would create a capturing lambda, meaning that it would need to instantiate an object to hold the ByteBuffer bb variable as it passes the lambda through to the publishEvent() call. This will create additional (unnecessary) garbage, so the call that passes the argument through to the lambda
 * should be preferred if low GC pressure is a requirement.
 * 
 * Give that method references can be used instead of anonymous lamdbas it is possible to rewrite the example in this fashion.
 * 
 * @author doctor
 * 
 * @see https://github.com/LMAX-Exchange/disruptor/wiki/Getting-Started
 *
 * @time 201573 ?10:52:37
 */
public class UsingJava8BetterByUseMethodReference {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newCachedThreadPool();
        int ringBufferSize = 1024;

        Disruptor<LongEvent> disruptor = new Disruptor<>(LongEvent::new, ringBufferSize, executor);
        disruptor.handleEventsWith(UsingJava8BetterByUseMethodReference::onEvent);
        disruptor.start();

        ByteBuffer buffer = ByteBuffer.allocate(8);

        Stopwatch stopwatch = Stopwatch.createStarted();

        for (long i = 0; i < 10; i++) {
            buffer.putLong(0, i);
            disruptor.publishEvent(UsingJava8BetterByUseMethodReference::translateTo, buffer);
        }

        long elapsed = stopwatch.elapsed(TimeUnit.MICROSECONDS);
        System.out.println("elapsed:" + elapsed);
        stopwatch.stop();

        disruptor.shutdown();
        executor.shutdown();
    }

    public static final void onEvent(LongEvent event, long sequence, boolean endOfBatch) {
        System.out.println(event);
    }

    public static final void translateTo(final LongEvent event, long sequence, final ByteBuffer buffer) {
        event.setValue(buffer.getLong(0));
    }
}