proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/event/ExecutionScheduledEvent.java
ExecutionScheduledEvent
toString
class ExecutionScheduledEvent<R> extends ExecutionEvent { private final R result; private final Throwable exception; private final Duration delay; public ExecutionScheduledEvent(R result, Throwable exception, Duration delay, ExecutionContext<R> context) { super(context); this.result = result; this.exception = exception; this.delay = delay; } /** * Returns the failure that preceded the event, else {@code null} if there was none. */ public Throwable getLastException() { return exception; } /** * Returns the result that preceded the event, else {@code null} if there was none. */ public R getLastResult() { return result; } /** * Returns the delay before the next execution attempt. */ public Duration getDelay() { return delay; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "ExecutionScheduledEvent[" + "result=" + result + ", exception=" + exception + ", delay=" + delay + ']';
260
37
297
<methods>public int getAttemptCount() ,public java.time.Duration getElapsedAttemptTime() ,public java.time.Duration getElapsedTime() ,public int getExecutionCount() ,public Optional<java.time.Instant> getStartTime() ,public boolean isFirstAttempt() ,public boolean isRetry() <variables>private final non-sealed ExecutionContext<?> context
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/internal/BulkheadExecutor.java
BulkheadExecutor
preExecuteAsync
class BulkheadExecutor<R> extends PolicyExecutor<R> { private final BulkheadImpl<R> bulkhead; private final Duration maxWaitTime; public BulkheadExecutor(BulkheadImpl<R> bulkhead, int policyIndex) { super(bulkhead, policyIndex); this.bulkhead = bulkhead; maxWaitTime = bulkhead.getConfig().getMaxWaitTime(); } @Override protected ExecutionResult<R> preExecute() { try { return bulkhead.tryAcquirePermit(maxWaitTime) ? null : ExecutionResult.exception(new BulkheadFullException(bulkhead)); } catch (InterruptedException e) { // Set interrupt flag Thread.currentThread().interrupt(); return ExecutionResult.exception(e); } } @Override protected CompletableFuture<ExecutionResult<R>> preExecuteAsync(Scheduler scheduler, FailsafeFuture<R> future) {<FILL_FUNCTION_BODY>} @Override public void onSuccess(ExecutionResult<R> result) { bulkhead.releasePermit(); } @Override protected ExecutionResult<R> onFailure(ExecutionContext<R> context, ExecutionResult<R> result) { bulkhead.releasePermit(); return result; } }
CompletableFuture<ExecutionResult<R>> promise = new CompletableFuture<>(); CompletableFuture<Void> acquireFuture = bulkhead.acquirePermitAsync(); acquireFuture.whenComplete((result, error) -> { // Signal for execution to proceed promise.complete(ExecutionResult.none()); }); if (!promise.isDone()) { try { // Schedule bulkhead permit timeout Future<?> timeoutFuture = scheduler.schedule(() -> { promise.complete(ExecutionResult.exception(new BulkheadFullException(bulkhead))); acquireFuture.cancel(true); return null; }, maxWaitTime.toNanos(), TimeUnit.NANOSECONDS); // Propagate outer cancellations to the promise, bulkhead acquire future, and timeout future future.setCancelFn(this, (mayInterrupt, cancelResult) -> { promise.complete(cancelResult); acquireFuture.cancel(mayInterrupt); timeoutFuture.cancel(mayInterrupt); }); } catch (Throwable t) { // Hard scheduling failure promise.completeExceptionally(t); } } return promise;
344
297
641
<methods>public Function<SyncExecutionInternal<R>,ExecutionResult<R>> apply(Function<SyncExecutionInternal<R>,ExecutionResult<R>>, dev.failsafe.spi.Scheduler) ,public Function<AsyncExecutionInternal<R>,CompletableFuture<ExecutionResult<R>>> applyAsync(Function<AsyncExecutionInternal<R>,CompletableFuture<ExecutionResult<R>>>, dev.failsafe.spi.Scheduler, FailsafeFuture<R>) ,public int getPolicyIndex() ,public ExecutionResult<R> postExecute(ExecutionInternal<R>, ExecutionResult<R>) <variables>private final non-sealed EventHandler<R> failureHandler,private final non-sealed FailurePolicy<R> failurePolicy,private final non-sealed int policyIndex,private final non-sealed EventHandler<R> successHandler
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/internal/BulkheadImpl.java
BulkheadImpl
tryAcquirePermit
class BulkheadImpl<R> implements Bulkhead<R> { private static final CompletableFuture<Void> NULL_FUTURE = CompletableFuture.completedFuture(null); private final BulkheadConfig<R> config; private final int maxPermits; // Mutable state private int permits; private final FutureLinkedList futures = new FutureLinkedList(); public BulkheadImpl(BulkheadConfig<R> config) { this.config = config; maxPermits = config.getMaxConcurrency(); permits = maxPermits; } @Override public BulkheadConfig<R> getConfig() { return config; } @Override public void acquirePermit() throws InterruptedException { try { acquirePermitAsync().get(); } catch (CancellationException | ExecutionException ignore) { // Not possible since the future will always be completed with null } } @Override public synchronized boolean tryAcquirePermit() { if (permits > 0) { permits -= 1; return true; } return false; } @Override public boolean tryAcquirePermit(Duration maxWaitTime) throws InterruptedException {<FILL_FUNCTION_BODY>} /** * Returns a CompletableFuture that is completed when a permit is acquired. Externally completing this future will * remove the waiter from the bulkhead's internal queue. */ synchronized CompletableFuture<Void> acquirePermitAsync() { if (permits > 0) { permits -= 1; return NULL_FUTURE; } else { return futures.add(); } } @Override public synchronized void releasePermit() { if (permits < maxPermits) { permits += 1; CompletableFuture<Void> future = futures.pollFirst(); if (future != null){ permits -= 1; future.complete(null); } } } @Override public PolicyExecutor<R> toExecutor(int policyIndex) { return new BulkheadExecutor<>(this, policyIndex); } }
CompletableFuture<Void> future = acquirePermitAsync(); if (future == NULL_FUTURE) return true; try { future.get(maxWaitTime.toNanos(), TimeUnit.NANOSECONDS); return true; } catch (CancellationException | ExecutionException | TimeoutException e) { return false; }
565
99
664
<no_super_class>
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/internal/BurstyRateLimiterStats.java
BurstyRateLimiterStats
acquirePermits
class BurstyRateLimiterStats extends RateLimiterStats { /* The permits per period */ final long periodPermits; /* The nanos per period */ private final long periodNanos; /* Available permits. Can be negative during a deficit. */ private long availablePermits; private long currentPeriod; BurstyRateLimiterStats(RateLimiterConfig<?> config, Stopwatch stopwatch) { super(stopwatch); periodPermits = config.getMaxPermits(); periodNanos = config.getPeriod().toNanos(); availablePermits = periodPermits; } @Override public synchronized long acquirePermits(long requestedPermits, Duration maxWaitTime) {<FILL_FUNCTION_BODY>} synchronized long getAvailablePermits() { return availablePermits; } synchronized long getCurrentPeriod() { return currentPeriod; } @Override synchronized void reset() { stopwatch.reset(); availablePermits = periodPermits; currentPeriod = 0; } }
long currentNanos = stopwatch.elapsedNanos(); long newCurrentPeriod = currentNanos / periodNanos; // Update current period and available permits if (currentPeriod < newCurrentPeriod) { long elapsedPeriods = newCurrentPeriod - currentPeriod; long elapsedPermits = elapsedPeriods * periodPermits; currentPeriod = newCurrentPeriod; availablePermits = availablePermits < 0 ? availablePermits + elapsedPermits : periodPermits; } long waitNanos = 0; if (requestedPermits > availablePermits) { long nextPeriodNanos = (currentPeriod + 1) * periodNanos; long nanosToNextPeriod = nextPeriodNanos - currentNanos; long permitDeficit = requestedPermits - availablePermits; long additionalPeriods = permitDeficit / periodPermits; long additionalUnits = permitDeficit % periodPermits; // Do not wait for an additional period if we're not using any permits from it if (additionalUnits == 0) additionalPeriods -= 1; // The nanos to wait until the beginning of the next period that will have free permits waitNanos = nanosToNextPeriod + (additionalPeriods * periodNanos); if (exceedsMaxWaitTime(waitNanos, maxWaitTime)) return -1; } availablePermits -= requestedPermits; return waitNanos;
284
375
659
<methods><variables>final non-sealed dev.failsafe.internal.RateLimiterStats.Stopwatch stopwatch
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/internal/CircuitBreakerImpl.java
CircuitBreakerImpl
transitionTo
class CircuitBreakerImpl<R> implements CircuitBreaker<R>, FailurePolicy<R>, DelayablePolicy<R> { private final CircuitBreakerConfig<R> config; /** Writes guarded by "this" */ protected final AtomicReference<CircuitState<R>> state = new AtomicReference<>(); public CircuitBreakerImpl(CircuitBreakerConfig<R> config) { this.config = config; state.set(new ClosedState<>(this)); } @Override public CircuitBreakerConfig<R> getConfig() { return config; } @Override public boolean tryAcquirePermit() { return state.get().tryAcquirePermit(); } @Override public void close() { transitionTo(State.CLOSED, config.getCloseListener(), null); } @Override public State getState() { return state.get().getState(); } @Override public int getExecutionCount() { return state.get().getStats().getExecutionCount(); } @Override public Duration getRemainingDelay() { return state.get().getRemainingDelay(); } @Override public long getFailureCount() { return state.get().getStats().getFailureCount(); } @Override public int getFailureRate() { return state.get().getStats().getFailureRate(); } @Override public int getSuccessCount() { return state.get().getStats().getSuccessCount(); } @Override public int getSuccessRate() { return state.get().getStats().getSuccessRate(); } @Override public void halfOpen() { transitionTo(State.HALF_OPEN, config.getHalfOpenListener(), null); } @Override public boolean isClosed() { return State.CLOSED.equals(getState()); } @Override public boolean isHalfOpen() { return State.HALF_OPEN.equals(getState()); } @Override public boolean isOpen() { return State.OPEN.equals(getState()); } @Override public void open() { transitionTo(State.OPEN, config.getOpenListener(), null); } @Override public void recordFailure() { recordExecutionFailure(null); } @Override public void recordException(Throwable exception) { recordResult(null, exception); } @Override public void recordResult(R result) { recordResult(result, null); } @Override public void recordSuccess() { state.get().recordSuccess(); } @Override public String toString() { return getState().toString(); } protected void recordResult(R result, Throwable exception) { if (isFailure(result, exception)) state.get().recordFailure(null); else state.get().recordSuccess(); } /** * Transitions to the {@code newState} if not already in that state and calls any associated event listener. */ protected void transitionTo(State newState, EventListener<CircuitBreakerStateChangedEvent> listener, ExecutionContext<R> context) {<FILL_FUNCTION_BODY>} /** * Records an execution failure. */ protected void recordExecutionFailure(ExecutionContext<R> context) { state.get().recordFailure(context); } /** * Opens the circuit breaker and considers the {@code context} when computing the delay before the circuit breaker * will transition to half open. */ protected void open(ExecutionContext<R> context) { transitionTo(State.OPEN, config.getOpenListener(), context); } @Override public PolicyExecutor<R> toExecutor(int policyIndex) { return new CircuitBreakerExecutor<>(this, policyIndex); } }
boolean transitioned = false; State currentState; synchronized (this) { currentState = getState(); if (!getState().equals(newState)) { switch (newState) { case CLOSED: state.set(new ClosedState<>(this)); break; case OPEN: Duration computedDelay = computeDelay(context); state.set(new OpenState<>(this, state.get(), computedDelay != null ? computedDelay : config.getDelay())); break; case HALF_OPEN: state.set(new HalfOpenState<>(this)); break; } transitioned = true; } } if (transitioned && listener != null) { try { listener.accept(new CircuitBreakerStateChangedEvent(currentState)); } catch (Throwable ignore) { } }
1,024
227
1,251
<no_super_class>
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/internal/ClosedState.java
ClosedState
checkThreshold
class ClosedState<R> extends CircuitState<R> { public ClosedState(CircuitBreakerImpl<R> breaker) { super(breaker, CircuitStats.create(breaker, capacityFor(breaker), true, null)); } @Override public boolean tryAcquirePermit() { return true; } @Override public State getState() { return State.CLOSED; } @Override public synchronized void handleConfigChange() { stats = CircuitStats.create(breaker, capacityFor(breaker), true, stats); } /** * Checks to see if the executions and failure thresholds have been exceeded, opening the circuit if so. */ @Override synchronized void checkThreshold(ExecutionContext<R> context) {<FILL_FUNCTION_BODY>} /** * Returns the capacity of the breaker in the closed state. */ private static int capacityFor(CircuitBreaker<?> breaker) { if (breaker.getConfig().getFailureExecutionThreshold() != 0) return breaker.getConfig().getFailureExecutionThreshold(); else return breaker.getConfig().getFailureThresholdingCapacity(); } }
// Execution threshold can only be set for time based thresholding if (stats.getExecutionCount() >= config.getFailureExecutionThreshold()) { // Failure rate threshold can only be set for time based thresholding double failureRateThreshold = config.getFailureRateThreshold(); if ((failureRateThreshold != 0 && stats.getFailureRate() >= failureRateThreshold) || (failureRateThreshold == 0 && stats.getFailureCount() >= config.getFailureThreshold())) breaker.open(context); }
320
134
454
<methods>public java.time.Duration getRemainingDelay() ,public abstract dev.failsafe.CircuitBreaker.State getState() ,public dev.failsafe.internal.CircuitStats getStats() ,public void handleConfigChange() ,public synchronized void recordFailure(ExecutionContext<R>) ,public synchronized void recordSuccess() <variables>final non-sealed CircuitBreakerImpl<R> breaker,final non-sealed CircuitBreakerConfig<R> config,volatile dev.failsafe.internal.CircuitStats stats
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/internal/CountingCircuitStats.java
CountingCircuitStats
setNext
class CountingCircuitStats implements CircuitStats { final BitSet bitSet; private final int size; /** Index to write next entry to */ volatile int currentIndex; private volatile int occupiedBits; private volatile int successes; private volatile int failures; public CountingCircuitStats(int size, CircuitStats oldStats) { this.bitSet = new BitSet(size); this.size = size; if (oldStats != null) { synchronized (oldStats) { copyStats(oldStats); } } } /** * Copies the most recent stats from the {@code oldStats} into this in order from oldest to newest. */ void copyStats(CircuitStats oldStats) { if (oldStats instanceof CountingCircuitStats) { CountingCircuitStats old = (CountingCircuitStats) oldStats; int bitsToCopy = Math.min(old.occupiedBits, size); int oldIndex = old.currentIndex - bitsToCopy; if (oldIndex < 0) oldIndex += old.occupiedBits; for (int i = 0; i < bitsToCopy; i++, oldIndex = old.indexAfter(oldIndex)) setNext(old.bitSet.get(oldIndex)); } else { copyExecutions(oldStats); } } @Override public void recordSuccess() { setNext(true); } @Override public void recordFailure() { setNext(false); } @Override public int getExecutionCount() { return occupiedBits; } @Override public int getFailureCount() { return failures; } @Override public synchronized int getFailureRate() { return (int) Math.round(occupiedBits == 0 ? 0 : (double) failures / (double) occupiedBits * 100.0); } @Override public int getSuccessCount() { return successes; } @Override public synchronized int getSuccessRate() { return (int) Math.round(occupiedBits == 0 ? 0 : (double) successes / (double) occupiedBits * 100.0); } @Override public synchronized void reset() { bitSet.clear(); currentIndex = 0; occupiedBits = 0; successes = 0; failures = 0; } /** * Sets the value of the next bit in the bitset, returning the previous value, else -1 if no previous value was set * for the bit. * * @param value true if positive/success, false if negative/failure */ synchronized int setNext(boolean value) {<FILL_FUNCTION_BODY>} /** * Returns an array representation of the BitSet entries. */ @Override public String toString() { StringBuilder sb = new StringBuilder().append('['); for (int i = 0; i < occupiedBits; i++) { if (i > 0) sb.append(", "); sb.append(bitSet.get(i)); } return sb.append(']').toString(); } /** * Returns the index after the {@code index}. */ private int indexAfter(int index) { return index == size - 1 ? 0 : index + 1; } }
int previousValue = -1; if (occupiedBits < size) occupiedBits++; else previousValue = bitSet.get(currentIndex) ? 1 : 0; bitSet.set(currentIndex, value); currentIndex = indexAfter(currentIndex); if (value) { if (previousValue != 1) successes++; if (previousValue == 0) failures--; } else { if (previousValue != 0) failures++; if (previousValue == 1) successes--; } return previousValue;
879
160
1,039
<no_super_class>
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/internal/FallbackExecutor.java
FallbackExecutor
apply
class FallbackExecutor<R> extends PolicyExecutor<R> { private final FallbackImpl<R> fallback; private final FallbackConfig<R> config; private final EventHandler<R> failedAttemptHandler; public FallbackExecutor(FallbackImpl<R> fallback, int policyIndex) { super(fallback, policyIndex); this.fallback = fallback; this.config = fallback.getConfig(); this.failedAttemptHandler = EventHandler.ofExecutionAttempted(config.getFailedAttemptListener()); } /** * Performs an execution by applying the {@code innerFn}, applying a fallback if it fails, and calling post-execute. */ @Override public Function<SyncExecutionInternal<R>, ExecutionResult<R>> apply( Function<SyncExecutionInternal<R>, ExecutionResult<R>> innerFn, Scheduler scheduler) {<FILL_FUNCTION_BODY>} /** * Performs an async execution by applying the {@code innerFn}, applying a fallback if it fails, and calling * post-execute. */ @Override public Function<AsyncExecutionInternal<R>, CompletableFuture<ExecutionResult<R>>> applyAsync( Function<AsyncExecutionInternal<R>, CompletableFuture<ExecutionResult<R>>> innerFn, Scheduler scheduler, FailsafeFuture<R> future) { return execution -> innerFn.apply(execution).thenCompose(result -> { if (result == null || future.isDone()) return ExecutionResult.nullFuture(); if (execution.isCancelled(this)) return CompletableFuture.completedFuture(result); if (!isFailure(result)) return postExecuteAsync(execution, result, scheduler, future); if (failedAttemptHandler != null) failedAttemptHandler.handle(result, execution); CompletableFuture<ExecutionResult<R>> promise = new CompletableFuture<>(); Callable<R> callable = () -> { try { CompletableFuture<R> fallbackFuture = fallback.applyStage(result.getResult(), result.getException(), execution); fallbackFuture.whenComplete((innerResult, exception) -> { if (exception instanceof CompletionException) exception = exception.getCause(); ExecutionResult<R> r = exception == null ? result.withResult(innerResult) : ExecutionResult.exception(exception); promise.complete(r); }); } catch (Throwable t) { promise.complete(ExecutionResult.exception(t)); } return null; }; try { if (!config.isAsync()) callable.call(); else { Future<?> scheduledFallback = scheduler.schedule(callable, 0, TimeUnit.NANOSECONDS); // Propagate outer cancellations to the Fallback future and its promise future.setCancelFn(this, (mayInterrupt, cancelResult) -> { scheduledFallback.cancel(mayInterrupt); promise.complete(cancelResult); }); } } catch (Throwable t) { // Hard scheduling failure promise.completeExceptionally(t); } return promise.thenCompose(ss -> postExecuteAsync(execution, ss, scheduler, future)); }); } }
return execution -> { ExecutionResult<R> result = innerFn.apply(execution); if (execution.isCancelled(this)) return result; if (isFailure(result)) { if (failedAttemptHandler != null) failedAttemptHandler.handle(result, execution); try { result = fallback == FallbackImpl.NONE ? result.withNonResult() : result.withResult(fallback.apply(result.getResult(), result.getException(), execution)); } catch (Throwable t) { result = ExecutionResult.exception(t); } } return postExecute(execution, result); };
842
176
1,018
<methods>public Function<SyncExecutionInternal<R>,ExecutionResult<R>> apply(Function<SyncExecutionInternal<R>,ExecutionResult<R>>, dev.failsafe.spi.Scheduler) ,public Function<AsyncExecutionInternal<R>,CompletableFuture<ExecutionResult<R>>> applyAsync(Function<AsyncExecutionInternal<R>,CompletableFuture<ExecutionResult<R>>>, dev.failsafe.spi.Scheduler, FailsafeFuture<R>) ,public int getPolicyIndex() ,public ExecutionResult<R> postExecute(ExecutionInternal<R>, ExecutionResult<R>) <variables>private final non-sealed EventHandler<R> failureHandler,private final non-sealed FailurePolicy<R> failurePolicy,private final non-sealed int policyIndex,private final non-sealed EventHandler<R> successHandler
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/internal/FallbackImpl.java
FallbackImpl
applyStage
class FallbackImpl<R> implements Fallback<R>, FailurePolicy<R> { /** * A fallback that will return null if execution fails. */ public static Fallback<Void> NONE = Fallback.<Void>builder(() -> null).build(); private final FallbackConfig<R> config; public FallbackImpl(FallbackConfig<R> config) { this.config = config; } @Override public FallbackConfig<R> getConfig() { return config; } /** * Returns the applied fallback result. */ protected R apply(R result, Throwable exception, ExecutionContext<R> context) throws Throwable { ExecutionAttemptedEvent<R> event = new ExecutionAttemptedEvent<>(result, exception, context); return config.getFallback() != null ? config.getFallback().apply(event) : config.getFallbackStage().apply(event).get(); } /** * Returns a future applied fallback result. */ protected CompletableFuture<R> applyStage(R result, Throwable exception, ExecutionContext<R> context) throws Throwable {<FILL_FUNCTION_BODY>} @Override public PolicyExecutor<R> toExecutor(int policyIndex) { return new FallbackExecutor<>(this, policyIndex); } }
ExecutionAttemptedEvent<R> event = new ExecutionAttemptedEvent<>(result, exception, context); return config.getFallback() != null ? CompletableFuture.completedFuture(config.getFallback().apply(event)) : config.getFallbackStage().apply(event);
363
82
445
<no_super_class>
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/internal/HalfOpenState.java
HalfOpenState
checkThreshold
class HalfOpenState<R> extends CircuitState<R> { protected final AtomicInteger permittedExecutions = new AtomicInteger(); public HalfOpenState(CircuitBreakerImpl<R> breaker) { super(breaker, CircuitStats.create(breaker, capacityFor(breaker), false, null)); permittedExecutions.set(capacityFor(breaker)); } @Override public boolean tryAcquirePermit() { return permittedExecutions.getAndUpdate(permits -> permits == 0 ? 0 : permits - 1) > 0; } @Override public void releasePermit() { permittedExecutions.incrementAndGet(); } @Override public State getState() { return State.HALF_OPEN; } @Override public synchronized void handleConfigChange() { stats = CircuitStats.create(breaker, capacityFor(breaker), false, stats); } /** * Checks to determine if a threshold has been met and the circuit should be opened or closed. * * <p> * If a success threshold is configured, the circuit is opened or closed based on whether the ratio was exceeded. * <p> * Else the circuit is opened or closed based on whether the failure threshold was exceeded. */ @Override synchronized void checkThreshold(ExecutionContext<R> context) {<FILL_FUNCTION_BODY>} /** * Returns the capacity of the breaker in the half-open state. */ private static int capacityFor(CircuitBreaker<?> breaker) { int capacity = breaker.getConfig().getSuccessThresholdingCapacity(); if (capacity == 0) capacity = breaker.getConfig().getFailureExecutionThreshold(); if (capacity == 0) capacity = breaker.getConfig().getFailureThresholdingCapacity(); return capacity; } }
boolean successesExceeded; boolean failuresExceeded; int successThreshold = config.getSuccessThreshold(); if (successThreshold != 0) { int successThresholdingCapacity = config.getSuccessThresholdingCapacity(); successesExceeded = stats.getSuccessCount() >= successThreshold; failuresExceeded = stats.getFailureCount() > successThresholdingCapacity - successThreshold; } else { // Failure rate threshold can only be set for time based thresholding int failureRateThreshold = config.getFailureRateThreshold(); if (failureRateThreshold != 0) { // Execution threshold can only be set for time based thresholding boolean executionThresholdExceeded = stats.getExecutionCount() >= config.getFailureExecutionThreshold(); failuresExceeded = executionThresholdExceeded && stats.getFailureRate() >= failureRateThreshold; successesExceeded = executionThresholdExceeded && stats.getSuccessRate() > 100 - failureRateThreshold; } else { int failureThresholdingCapacity = config.getFailureThresholdingCapacity(); int failureThreshold = config.getFailureThreshold(); failuresExceeded = stats.getFailureCount() >= failureThreshold; successesExceeded = stats.getSuccessCount() > failureThresholdingCapacity - failureThreshold; } } if (successesExceeded) breaker.close(); else if (failuresExceeded) breaker.open(context);
487
387
874
<methods>public java.time.Duration getRemainingDelay() ,public abstract dev.failsafe.CircuitBreaker.State getState() ,public dev.failsafe.internal.CircuitStats getStats() ,public void handleConfigChange() ,public synchronized void recordFailure(ExecutionContext<R>) ,public synchronized void recordSuccess() <variables>final non-sealed CircuitBreakerImpl<R> breaker,final non-sealed CircuitBreakerConfig<R> config,volatile dev.failsafe.internal.CircuitStats stats
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/internal/OpenState.java
OpenState
getRemainingDelay
class OpenState<R> extends CircuitState<R> { private final long startTime = System.nanoTime(); private final long delayNanos; public OpenState(CircuitBreakerImpl<R> breaker, CircuitState<R> previousState, Duration delay) { super(breaker, previousState.stats); this.delayNanos = delay.toNanos(); } @Override public boolean tryAcquirePermit() { if (System.nanoTime() - startTime >= delayNanos) { breaker.halfOpen(); return breaker.tryAcquirePermit(); } return false; } @Override public Duration getRemainingDelay() {<FILL_FUNCTION_BODY>} @Override public State getState() { return State.OPEN; } }
long elapsedTime = System.nanoTime() - startTime; long remainingDelay = delayNanos - elapsedTime; return Duration.ofNanos(Math.max(remainingDelay, 0));
222
57
279
<methods>public java.time.Duration getRemainingDelay() ,public abstract dev.failsafe.CircuitBreaker.State getState() ,public dev.failsafe.internal.CircuitStats getStats() ,public void handleConfigChange() ,public synchronized void recordFailure(ExecutionContext<R>) ,public synchronized void recordSuccess() <variables>final non-sealed CircuitBreakerImpl<R> breaker,final non-sealed CircuitBreakerConfig<R> config,volatile dev.failsafe.internal.CircuitStats stats
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/internal/RateLimiterExecutor.java
RateLimiterExecutor
preExecuteAsync
class RateLimiterExecutor<R> extends PolicyExecutor<R> { private final RateLimiterImpl<R> rateLimiter; private final Duration maxWaitTime; public RateLimiterExecutor(RateLimiterImpl<R> rateLimiter, int policyIndex) { super(rateLimiter, policyIndex); this.rateLimiter = rateLimiter; maxWaitTime = rateLimiter.getConfig().getMaxWaitTime(); } @Override protected ExecutionResult<R> preExecute() { try { return rateLimiter.tryAcquirePermit(maxWaitTime) ? null : ExecutionResult.exception(new RateLimitExceededException(rateLimiter)); } catch (InterruptedException e) { // Set interrupt flag Thread.currentThread().interrupt(); return ExecutionResult.exception(e); } } @Override protected CompletableFuture<ExecutionResult<R>> preExecuteAsync(Scheduler scheduler, FailsafeFuture<R> future) {<FILL_FUNCTION_BODY>} }
CompletableFuture<ExecutionResult<R>> promise = new CompletableFuture<>(); long waitNanos = rateLimiter.reservePermits(1, maxWaitTime); if (waitNanos == -1) promise.complete(ExecutionResult.exception(new RateLimitExceededException(rateLimiter))); else { try { // Wait for the permit Future<?> permitWaitFuture = scheduler.schedule(() -> { // Signal for execution to proceed promise.complete(ExecutionResult.none()); return null; }, waitNanos, TimeUnit.NANOSECONDS); // Propagate outer cancellations to the promise and permit wait future future.setCancelFn(this, (mayInterrupt, cancelResult) -> { promise.complete(cancelResult); permitWaitFuture.cancel(mayInterrupt); }); } catch (Throwable t) { // Hard scheduling failure promise.completeExceptionally(t); } } return promise;
280
259
539
<methods>public Function<SyncExecutionInternal<R>,ExecutionResult<R>> apply(Function<SyncExecutionInternal<R>,ExecutionResult<R>>, dev.failsafe.spi.Scheduler) ,public Function<AsyncExecutionInternal<R>,CompletableFuture<ExecutionResult<R>>> applyAsync(Function<AsyncExecutionInternal<R>,CompletableFuture<ExecutionResult<R>>>, dev.failsafe.spi.Scheduler, FailsafeFuture<R>) ,public int getPolicyIndex() ,public ExecutionResult<R> postExecute(ExecutionInternal<R>, ExecutionResult<R>) <variables>private final non-sealed EventHandler<R> failureHandler,private final non-sealed FailurePolicy<R> failurePolicy,private final non-sealed int policyIndex,private final non-sealed EventHandler<R> successHandler
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/internal/RateLimiterImpl.java
RateLimiterImpl
tryAcquirePermits
class RateLimiterImpl<R> implements RateLimiter<R> { private final RateLimiterConfig<R> config; private final RateLimiterStats stats; public RateLimiterImpl(RateLimiterConfig<R> config) { this(config, new Stopwatch()); } RateLimiterImpl(RateLimiterConfig<R> config, Stopwatch stopwatch) { this.config = config; stats = config.getMaxRate() != null ? new SmoothRateLimiterStats(config, stopwatch) : new BurstyRateLimiterStats(config, stopwatch); } @Override public RateLimiterConfig<R> getConfig() { return config; } @Override public void acquirePermits(int permits) throws InterruptedException { long waitNanos = reservePermits(permits).toNanos(); if (waitNanos > 0) TimeUnit.NANOSECONDS.sleep(waitNanos); } @Override public Duration reservePermits(int permits) { Assert.isTrue(permits > 0, "permits must be > 0"); return Duration.ofNanos(stats.acquirePermits(permits, null)); } @Override public boolean tryAcquirePermits(int permits) { return reservePermits(permits, Duration.ZERO) == 0; } @Override public boolean tryAcquirePermits(int permits, Duration maxWaitTime) throws InterruptedException {<FILL_FUNCTION_BODY>} @Override public Duration tryReservePermits(int permits, Duration maxWaitTime) { return Duration.ofNanos(reservePermits(permits, maxWaitTime)); } @Override public PolicyExecutor<R> toExecutor(int policyIndex) { return new RateLimiterExecutor<>(this, policyIndex); } long reservePermits(int permits, Duration maxWaitTime) { Assert.isTrue(permits > 0, "permits must be > 0"); Assert.notNull(maxWaitTime, "maxWaitTime"); return stats.acquirePermits(permits, Durations.ofSafeNanos(maxWaitTime)); } }
long waitNanos = reservePermits(permits, maxWaitTime); if (waitNanos == -1) return false; if (waitNanos > 0) TimeUnit.NANOSECONDS.sleep(waitNanos); return true;
588
74
662
<no_super_class>
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/internal/RetryPolicyImpl.java
RetryPolicyImpl
isAbortable
class RetryPolicyImpl<R> implements RetryPolicy<R>, FailurePolicy<R>, DelayablePolicy<R> { private final RetryPolicyConfig<R> config; public RetryPolicyImpl(RetryPolicyConfig<R> config) { this.config = config; } @Override public RetryPolicyConfig<R> getConfig() { return config; } /** * Returns whether an execution result can be aborted given the configured abort conditions. * * @see RetryPolicyBuilder#abortOn(Class...) * @see RetryPolicyBuilder#abortOn(List) * @see RetryPolicyBuilder#abortOn(CheckedPredicate) * @see RetryPolicyBuilder#abortIf(CheckedBiPredicate) * @see RetryPolicyBuilder#abortIf(CheckedPredicate) * @see RetryPolicyBuilder#abortWhen(R) */ public boolean isAbortable(R result, Throwable failure) {<FILL_FUNCTION_BODY>} @Override public PolicyExecutor<R> toExecutor(int policyIndex) { return new RetryPolicyExecutor<>(this, policyIndex); } }
for (CheckedBiPredicate<R, Throwable> predicate : config.getAbortConditions()) { try { if (predicate.test(result, failure)) return true; } catch (Throwable ignore) { } } return false;
309
73
382
<no_super_class>
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/internal/SmoothRateLimiterStats.java
SmoothRateLimiterStats
acquirePermits
class SmoothRateLimiterStats extends RateLimiterStats { /* The nanos per interval between permits */ final long intervalNanos; // The amount of time, relative to the start time, that the next permit will be free. // Will be a multiple of intervalNanos. private long nextFreePermitNanos; SmoothRateLimiterStats(RateLimiterConfig<?> config, Stopwatch stopwatch) { super(stopwatch); intervalNanos = config.getMaxRate().toNanos(); } @Override public synchronized long acquirePermits(long requestedPermits, Duration maxWaitTime) {<FILL_FUNCTION_BODY>} synchronized long getNextFreePermitNanos() { return nextFreePermitNanos; } @Override synchronized void reset() { stopwatch.reset(); nextFreePermitNanos = 0; } }
long currentNanos = stopwatch.elapsedNanos(); long requestedPermitNanos = requestedPermits * intervalNanos; long waitNanos; long newNextFreePermitNanos; // If a permit is currently available if (currentNanos >= nextFreePermitNanos) { // Nanos at the start of the current interval long currentIntervalNanos = Maths.roundDown(currentNanos, intervalNanos); newNextFreePermitNanos = Maths.add(currentIntervalNanos, requestedPermitNanos); } else { newNextFreePermitNanos = Maths.add(nextFreePermitNanos, requestedPermitNanos); } waitNanos = Math.max(newNextFreePermitNanos - currentNanos - intervalNanos, 0); if (exceedsMaxWaitTime(waitNanos, maxWaitTime)) return -1; nextFreePermitNanos = newNextFreePermitNanos; return waitNanos;
245
281
526
<methods><variables>final non-sealed dev.failsafe.internal.RateLimiterStats.Stopwatch stopwatch
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/internal/TimedCircuitStats.java
Bucket
indexAfter
class Bucket extends Stat { long startTimeMillis = -1; void reset(long startTimeMillis) { this.startTimeMillis = startTimeMillis; reset(); } void copyFrom(Bucket other) { startTimeMillis = other.startTimeMillis; successes = other.successes; failures = other.failures; } @Override public String toString() { return "[startTime=" + startTimeMillis + ", s=" + successes + ", f=" + failures + ']'; } } /** * Copies the most recent stats from the {@code oldStats} into this in order from oldest to newest and orders buckets * from oldest to newest, with uninitialized buckets counting as oldest. */ void copyStats(CircuitStats oldStats) { if (oldStats instanceof TimedCircuitStats) { TimedCircuitStats old = (TimedCircuitStats) oldStats; int bucketsToCopy = Math.min(old.buckets.length, buckets.length); // Get oldest index to start copying from int oldIndex = old.indexAfter(old.currentIndex); for (int i = 0; i < bucketsToCopy; i++) oldIndex = old.indexBefore(oldIndex); for (int i = 0; i < bucketsToCopy; i++) { if (i != 0) { oldIndex = old.indexAfter(oldIndex); currentIndex = nextIndex(); } buckets[currentIndex].copyFrom(old.buckets[oldIndex]); summary.add(buckets[currentIndex]); } } else { buckets[0].startTimeMillis = clock.currentTimeMillis(); copyExecutions(oldStats); } } @Override public synchronized void recordSuccess() { getCurrentBucket().successes++; summary.successes++; } @Override public synchronized void recordFailure() { getCurrentBucket().failures++; summary.failures++; } @Override public int getExecutionCount() { return summary.successes + summary.failures; } @Override public int getFailureCount() { return summary.failures; } @Override public synchronized int getFailureRate() { int executions = getExecutionCount(); return (int) Math.round(executions == 0 ? 0 : (double) summary.failures / (double) executions * 100.0); } @Override public int getSuccessCount() { return summary.successes; } @Override public synchronized int getSuccessRate() { int executions = getExecutionCount(); return (int) Math.round(executions == 0 ? 0 : (double) summary.successes / (double) executions * 100.0); } @Override public synchronized void reset() { long startTimeMillis = clock.currentTimeMillis(); for (Bucket bucket : buckets) { bucket.reset(startTimeMillis); startTimeMillis += bucketSizeMillis; } summary.reset(); currentIndex = 0; } /** * Returns the current bucket based on the current time, moving the internal storage to the current bucket if * necessary, resetting bucket stats along the way. */ synchronized Bucket getCurrentBucket() { Bucket previousBucket, currentBucket = buckets[currentIndex]; long currentTime = clock.currentTimeMillis(); long timeDiff = currentTime - currentBucket.startTimeMillis; if (timeDiff >= bucketSizeMillis) { int bucketsToMove = (int) (timeDiff / bucketSizeMillis); if (bucketsToMove <= buckets.length) { // Reset some buckets do { currentIndex = nextIndex(); previousBucket = currentBucket; currentBucket = buckets[currentIndex]; long bucketStartTime = currentBucket.startTimeMillis == -1 ? previousBucket.startTimeMillis + bucketSizeMillis : currentBucket.startTimeMillis + windowSizeMillis; summary.remove(currentBucket); currentBucket.reset(bucketStartTime); bucketsToMove--; } while (bucketsToMove > 0); } else { // Reset all buckets reset(); } } return currentBucket; } /** * Returns the next index. */ private int nextIndex() { return (currentIndex + 1) % buckets.length; } /** * Returns the index after the {@code index}. */ private int indexAfter(int index) {<FILL_FUNCTION_BODY>
return index == buckets.length - 1 ? 0 : index + 1;
1,242
23
1,265
<no_super_class>
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/internal/TimeoutExecutor.java
TimeoutExecutor
apply
class TimeoutExecutor<R> extends PolicyExecutor<R> { private final Timeout<R> policy; private final TimeoutConfig<R> config; public TimeoutExecutor(TimeoutImpl<R> timeout, int policyIndex) { super(timeout, policyIndex); policy = timeout; config = timeout.getConfig(); } @Override public boolean isFailure(ExecutionResult<R> result) { return !result.isNonResult() && result.getException() instanceof TimeoutExceededException; } /** * Schedules a separate timeout call that fails with {@link TimeoutExceededException} if the policy's timeout is * exceeded. * <p> * This implementation sets up a race between a timeout being triggered and the {@code innerFn} returning. Whichever * completes first will be the result that's returned. */ @Override public Function<SyncExecutionInternal<R>, ExecutionResult<R>> apply( Function<SyncExecutionInternal<R>, ExecutionResult<R>> innerFn, Scheduler scheduler) {<FILL_FUNCTION_BODY>} /** * Schedules a separate timeout call that blocks and fails with {@link TimeoutExceededException} if the policy's * timeout is exceeded. * <p> * This implementation sets up a race between a timeout being triggered and the {@code innerFn} returning. Whichever * completes first will be the result that's recorded and used to complete the resulting promise. */ @Override @SuppressWarnings("unchecked") public Function<AsyncExecutionInternal<R>, CompletableFuture<ExecutionResult<R>>> applyAsync( Function<AsyncExecutionInternal<R>, CompletableFuture<ExecutionResult<R>>> innerFn, Scheduler scheduler, FailsafeFuture<R> future) { return execution -> { // Coordinates a race between the timeout and execution threads AtomicReference<ExecutionResult<R>> resultRef = new AtomicReference<>(); AtomicReference<Future<R>> timeoutFutureRef = new AtomicReference<>(); CompletableFuture<ExecutionResult<R>> promise = new CompletableFuture<>(); // Guard against race with future.complete, future.cancel, AsyncExecution.record or AsyncExecution.complete synchronized (future) { // Schedule timeout if we are not done and not recording a result if (!future.isDone() && !execution.isRecorded()) { try { Future<R> timeoutFuture = (Future<R>) Scheduler.DEFAULT.schedule(() -> { // Guard against race with innerFn returning a result ExecutionResult<R> cancelResult = ExecutionResult.exception(new TimeoutExceededException(policy)); if (resultRef.compareAndSet(null, cancelResult)) { // Guard against race with RetryPolicy updating the latest execution synchronized (execution.getLock()) { // Cancel and interrupt the latest attempt ExecutionInternal<R> latestExecution = execution.getLatest(); latestExecution.record(cancelResult); latestExecution.cancel(this); future.cancelDependencies(this, config.canInterrupt(), cancelResult); } } return null; }, config.getTimeout().toNanos(), TimeUnit.NANOSECONDS); timeoutFutureRef.set(timeoutFuture); // Propagate outer cancellations to the Timeout future and its promise future.setCancelFn(this, (mayInterrupt, cancelResult) -> { timeoutFuture.cancel(mayInterrupt); resultRef.compareAndSet(null, cancelResult); }); } catch (Throwable t) { // Hard scheduling failure promise.completeExceptionally(t); return promise; } } } // Propagate execution, cancel timeout future if not done, and postExecute result innerFn.apply(execution).whenComplete((result, error) -> { if (error != null) { promise.completeExceptionally(error); return; } // Fetch timeout result if any if (!resultRef.compareAndSet(null, result)) result = resultRef.get(); if (result != null) { // Cancel timeout task Future<R> timeoutFuture = timeoutFutureRef.get(); if (timeoutFuture != null && !timeoutFuture.isDone()) timeoutFuture.cancel(false); postExecuteAsync(execution, result, scheduler, future); } promise.complete(result); }); return promise; }; } }
return execution -> { // Coordinates a result between the timeout and execution threads AtomicReference<ExecutionResult<R>> result = new AtomicReference<>(); Future<?> timeoutFuture; try { // Schedule timeout check timeoutFuture = Scheduler.DEFAULT.schedule(() -> { // Guard against race with innerFn returning a result ExecutionResult<R> cancelResult = ExecutionResult.exception(new TimeoutExceededException(policy)); if (result.compareAndSet(null, cancelResult)) { // Guard against race with RetryPolicy updating the latest execution synchronized (execution.getLock()) { // Cancel and interrupt the latest attempt ExecutionInternal<R> latestExecution = execution.getLatest(); latestExecution.record(cancelResult); latestExecution.cancel(this); if (config.canInterrupt()) execution.interrupt(); } } return null; }, config.getTimeout().toNanos(), TimeUnit.NANOSECONDS); } catch (Throwable t) { // Hard scheduling failure return postExecute(execution, ExecutionResult.exception(t)); } // Propagate execution, cancel timeout future if not done, and postExecute result if (result.compareAndSet(null, innerFn.apply(execution))) timeoutFuture.cancel(false); return postExecute(execution, result.get()); };
1,144
356
1,500
<methods>public Function<SyncExecutionInternal<R>,ExecutionResult<R>> apply(Function<SyncExecutionInternal<R>,ExecutionResult<R>>, dev.failsafe.spi.Scheduler) ,public Function<AsyncExecutionInternal<R>,CompletableFuture<ExecutionResult<R>>> applyAsync(Function<AsyncExecutionInternal<R>,CompletableFuture<ExecutionResult<R>>>, dev.failsafe.spi.Scheduler, FailsafeFuture<R>) ,public int getPolicyIndex() ,public ExecutionResult<R> postExecute(ExecutionInternal<R>, ExecutionResult<R>) <variables>private final non-sealed EventHandler<R> failureHandler,private final non-sealed FailurePolicy<R> failurePolicy,private final non-sealed int policyIndex,private final non-sealed EventHandler<R> successHandler
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/internal/TimeoutImpl.java
TimeoutImpl
toString
class TimeoutImpl<R> implements Timeout<R> { private final TimeoutConfig<R> config; public TimeoutImpl(TimeoutConfig<R> config) { this.config = config; } @Override public TimeoutConfig<R> getConfig() { return config; } @Override public PolicyExecutor<R> toExecutor(int policyIndex) { return new TimeoutExecutor<>(this, policyIndex); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "Timeout[timeout=" + config.getTimeout() + ", interruptable=" + config.canInterrupt() + ']';
145
36
181
<no_super_class>
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/internal/util/Assert.java
Assert
notNull
class Assert { private Assert() { } public static void isTrue(boolean expression, String errorMessageFormat, Object... args) { if (!expression) throw new IllegalArgumentException(String.format(errorMessageFormat, args)); } public static <T> T notNull(T reference, String parameterName) {<FILL_FUNCTION_BODY>} public static void state(boolean expression, String errorMessageFormat, Object... args) { if (!expression) throw new IllegalStateException(String.format(errorMessageFormat, args)); } }
if (reference == null) throw new NullPointerException(parameterName + " cannot be null"); return reference;
143
32
175
<no_super_class>
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/internal/util/DelegatingScheduler.java
ScheduledCompletableFuture
executorService
class ScheduledCompletableFuture<V> extends CompletableFuture<V> implements ScheduledFuture<V> { // Guarded by this volatile Future<V> delegate; // Guarded by this Thread forkJoinPoolThread; private final long time; ScheduledCompletableFuture(long delay, TimeUnit unit) { this.time = System.nanoTime() + unit.toNanos(delay); } @Override public long getDelay(TimeUnit unit) { return unit.convert(time - System.nanoTime(), TimeUnit.NANOSECONDS); } @Override public int compareTo(Delayed other) { if (other == this) { return 0; } else if (other instanceof ScheduledCompletableFuture) { return Long.compare(time, ((ScheduledCompletableFuture<?>) other).time); } return Long.compare(getDelay(TimeUnit.NANOSECONDS), other.getDelay(TimeUnit.NANOSECONDS)); } @Override public boolean cancel(boolean mayInterruptIfRunning) { boolean result = super.cancel(mayInterruptIfRunning); synchronized (this) { if (delegate != null) result = delegate.cancel(mayInterruptIfRunning); if (forkJoinPoolThread != null && mayInterruptIfRunning) forkJoinPoolThread.interrupt(); } return result; } } private static ScheduledExecutorService delayer() { if (DELAYER == null) { synchronized (DelegatingScheduler.class) { if (DELAYER == null) { ScheduledThreadPoolExecutor delayer = new ScheduledThreadPoolExecutor(1, new DelayerThreadFactory()); delayer.setRemoveOnCancelPolicy(true); DELAYER = delayer; } } } return DELAYER; } private ExecutorService executorService() {<FILL_FUNCTION_BODY>
if (executorService != null) return executorService; if (FORK_JOIN_POOL == null) { synchronized (DelegatingScheduler.class) { if (FORK_JOIN_POOL == null) { if (ForkJoinPool.getCommonPoolParallelism() > 1) FORK_JOIN_POOL = ForkJoinPool.commonPool(); else FORK_JOIN_POOL = new ForkJoinPool(2); } } } return FORK_JOIN_POOL;
516
148
664
<no_super_class>
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/internal/util/FutureLinkedList.java
Node
pollFirst
class Node { Node previous; Node next; CompletableFuture<Void> future; } /** * Adds a new CompletableFuture to the list and returns it. The returned future will be removed from the list when * it's completed. */ public synchronized CompletableFuture<Void> add() { Node node = new Node(); node.future = new CompletableFuture<>(); node.future.whenComplete((result, error) -> remove(node)); if (head == null) head = tail = node; else { tail.next = node; node.previous = tail; tail = node; } return node.future; } /** * Returns and removes the first future in the list, else returns {@code null} if the list is empty. */ public synchronized CompletableFuture<Void> pollFirst() {<FILL_FUNCTION_BODY>
Node previousHead = head; if (head != null) { head = head.next; if (head != null) head.previous = null; } return previousHead == null ? null : previousHead.future;
239
64
303
<no_super_class>
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/internal/util/Lists.java
Lists
of
class Lists { private Lists() { } /** * Returns a list containing the {@code first} element followed by the {@code rest}. */ public static <T> List<T> of(T first, T[] rest) {<FILL_FUNCTION_BODY>} }
List<T> result = new ArrayList<>(rest.length + 1); result.add(first); Collections.addAll(result, rest); return result;
77
46
123
<no_super_class>
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/internal/util/Maths.java
Maths
add
class Maths { private Maths() { } /** * Returns the sum of {@code a} and {@code b} else {@code Long.MAX_VALUE} if the sum would otherwise overflow. */ public static long add(long a, long b) {<FILL_FUNCTION_BODY>} /** * Returns the {@code input} rounded down to the nearest {@code interval}. */ public static long roundDown(long input, long interval) { return (input / interval) * interval; } }
long naiveSum = a + b; return (a ^ b) < 0L | (a ^ naiveSum) >= 0L ? naiveSum : 9223372036854775807L + (naiveSum >>> 63 ^ 1L);
136
77
213
<no_super_class>
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/internal/util/RandomDelay.java
RandomDelay
randomDelay
class RandomDelay { private RandomDelay() { } public static long randomDelayInRange(long delayMin, long delayMax, double random) { return (long) (random * (delayMax - delayMin)) + delayMin; } public static long randomDelay(long delay, long jitter, double random) { double randomAddend = (1 - random * 2) * jitter; return (long) (delay + randomAddend); } public static long randomDelay(long delay, double jitterFactor, double random) {<FILL_FUNCTION_BODY>} }
double randomFactor = 1 + (1 - random * 2) * jitterFactor; return (long) (delay * randomFactor);
152
39
191
<no_super_class>
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/spi/ExecutionResult.java
ExecutionResult
withResult
class ExecutionResult<R> { private static final CompletableFuture<?> NULL_FUTURE = CompletableFuture.completedFuture(null); private static final ExecutionResult<?> NONE = new ExecutionResult<>(null, null, true, 0, true, true, true); /** The execution result, if any */ private final R result; /** The execution exception, if any */ private final Throwable exception; /** Whether the result represents a non result rather than a {@code null} result */ private final boolean nonResult; /** The amount of time to wait prior to the next execution, according to the policy */ // Do we need this here? perhaps we can set delay nanos right against the Execution internals? private final long delayNanos; /** Whether a policy has completed handling of the execution */ private final boolean complete; /** Whether a policy determined the execution to be a success */ private final boolean success; /** Whether all policies determined the execution to be a success */ private final Boolean successAll; /** * Records an initial execution result with {@code complete} true and {@code success} set to true if {@code exception} * is not null. */ public ExecutionResult(R result, Throwable exception) { this(result, exception, false, 0, true, exception == null, exception == null); } private ExecutionResult(R result, Throwable exception, boolean nonResult, long delayNanos, boolean complete, boolean success, Boolean successAll) { this.nonResult = nonResult; this.result = result; this.exception = exception; this.delayNanos = delayNanos; this.complete = complete; this.success = success; this.successAll = successAll; } /** * Returns a CompletableFuture that is completed with {@code null}. Uses an intern'ed value to avoid new object * creation. */ @SuppressWarnings("unchecked") public static <R> CompletableFuture<ExecutionResult<R>> nullFuture() { return (CompletableFuture<ExecutionResult<R>>) NULL_FUTURE; } /** * Returns an ExecutionResult with the {@code result} set, {@code complete} true and {@code success} true. */ public static <R> ExecutionResult<R> success(R result) { return new ExecutionResult<>(result, null, false, 0, true, true, true); } /** * Returns an ExecutionResult with the {@code exception} set, {@code complete} true and {@code success} false. */ public static <R> ExecutionResult<R> exception(Throwable exception) { return new ExecutionResult<>(null, exception, false, 0, true, false, false); } /** * Returns an execution that was completed with a non-result. Uses an intern'ed value to avoid new object creation. */ @SuppressWarnings("unchecked") public static <R> ExecutionResult<R> none() { return (ExecutionResult<R>) NONE; } public R getResult() { return result; } public Throwable getException() { return exception; } public long getDelay() { return delayNanos; } public boolean isComplete() { return complete; } public boolean isNonResult() { return nonResult; } public boolean isSuccess() { return success; } /** * Returns a copy of the ExecutionResult with a non-result, and complete and success set to true. Returns {@code this} * if {@link #success} and {@link #result} are unchanged. */ public ExecutionResult<R> withNonResult() { return success && this.result == null && nonResult ? this : new ExecutionResult<>(null, null, true, delayNanos, true, true, successAll); } /** * Returns a copy of the ExecutionResult with the {@code result} value, and complete and success set to true. Returns * {@code this} if {@link #success} and {@link #result} are unchanged. */ public ExecutionResult<R> withResult(R result) {<FILL_FUNCTION_BODY>} /** * Returns a copy of the ExecutionResult with {@code complete} set to false, else this if nothing has changed. */ public ExecutionResult<R> withNotComplete() { return !this.complete ? this : new ExecutionResult<>(result, exception, nonResult, delayNanos, false, success, successAll); } /** * Returns a copy of the ExecutionResult with success value of {code false}. */ public ExecutionResult<R> withException() { return !this.success ? this : new ExecutionResult<>(result, exception, nonResult, delayNanos, complete, false, false); } /** * Returns a copy of the ExecutionResult with the {@code complete} and {@code success} values of {@code true}. */ public ExecutionResult<R> withSuccess() { return this.complete && this.success ? this : new ExecutionResult<>(result, exception, nonResult, delayNanos, true, true, successAll); } /** * Returns a copy of the ExecutionResult with the {@code delayNanos} value. */ public ExecutionResult<R> withDelay(long delayNanos) { return this.delayNanos == delayNanos ? this : new ExecutionResult<>(result, exception, nonResult, delayNanos, complete, success, successAll); } /** * Returns a copy of the ExecutionResult with the {@code delayNanos}, {@code complete} and {@code success} values. */ public ExecutionResult<R> with(long delayNanos, boolean complete, boolean success) { return this.delayNanos == delayNanos && this.complete == complete && this.success == success ? this : new ExecutionResult<>(result, exception, nonResult, delayNanos, complete, success, successAll == null ? success : success && successAll); } /** * Returns whether the execution was successful for all policies. */ public boolean getSuccessAll() { return successAll != null && successAll; } @Override public String toString() { return "[" + "result=" + result + ", exception=" + exception + ", nonResult=" + nonResult + ", delayNanos=" + delayNanos + ", complete=" + complete + ", success=" + success + ", successAll=" + successAll + ']'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ExecutionResult<?> that = (ExecutionResult<?>) o; return Objects.equals(result, that.result) && Objects.equals(exception, that.exception); } @Override public int hashCode() { return Objects.hash(result, exception); } }
boolean unchangedNull = this.result == null && result == null && exception == null; boolean unchangedNotNull = this.result != null && this.result.equals(result); return success && (unchangedNull || unchangedNotNull) ? this : new ExecutionResult<>(result, null, nonResult, delayNanos, true, true, successAll);
1,843
89
1,932
<no_super_class>
failsafe-lib_failsafe
failsafe/core/src/main/java/dev/failsafe/spi/FailsafeFuture.java
FailsafeFuture
cancelDependencies
class FailsafeFuture<R> extends CompletableFuture<R> { private final BiConsumer<ExecutionResult<R>, ExecutionContext<R>> completionHandler; // Mutable state guarded by "this" // The most recent execution attempt private ExecutionInternal<R> newestExecution; // Functions to apply when this future is cancelled for each policy index, in descending order private Map<Integer, BiConsumer<Boolean, ExecutionResult<R>>> cancelFunctions; // Whether a cancel with interrupt has already occurred private boolean cancelledWithInterrupt; public FailsafeFuture(BiConsumer<ExecutionResult<R>, ExecutionContext<R>> completionHandler) { this.completionHandler = completionHandler; } /** * If not already completed, completes the future with the {@code value}, calling the complete and success handlers. */ @Override public synchronized boolean complete(R value) { return completeResult(ExecutionResult.success(value)); } /** * If not already completed, completes the future with the {@code exception}, calling the complete and failure * handlers. */ @Override public synchronized boolean completeExceptionally(Throwable exception) { return completeResult(ExecutionResult.exception(exception)); } /** * Cancels the future along with any dependencies. */ @Override public synchronized boolean cancel(boolean mayInterruptIfRunning) { if (isDone()) return false; this.cancelledWithInterrupt = mayInterruptIfRunning; newestExecution.cancel(); boolean cancelResult = super.cancel(mayInterruptIfRunning); cancelDependencies(null, mayInterruptIfRunning, null); ExecutionResult<R> result = ExecutionResult.exception(new CancellationException()); super.completeExceptionally(result.getException()); completionHandler.accept(result, newestExecution); newestExecution = null; cancelFunctions = null; return cancelResult; } /** * Completes the execution with the {@code result} and calls the completion handler. */ public synchronized boolean completeResult(ExecutionResult<R> result) { if (isDone()) return false; Throwable exception = result.getException(); boolean completed; if (exception == null) completed = super.complete(result.getResult()); else completed = super.completeExceptionally(exception); if (completed) completionHandler.accept(result, newestExecution); newestExecution = null; cancelFunctions = null; return completed; } /** * Applies any {@link #setCancelFn(PolicyExecutor, BiConsumer) cancel functions} with the {@code cancelResult} for * PolicyExecutors whose policyIndex is < the policyIndex of the {@code cancellingPolicyExecutor}. * * @param cancellingPolicyExecutor the PolicyExecutor that is requesting the cancellation of inner policy executors */ public synchronized void cancelDependencies(PolicyExecutor<R> cancellingPolicyExecutor, boolean mayInterrupt, ExecutionResult<R> cancelResult) {<FILL_FUNCTION_BODY>} /** * Sets the {@code execution} representing the most recent attempt, which will be cancelled if this future is * cancelled. */ public synchronized void setExecution(ExecutionInternal<R> execution) { this.newestExecution = execution; } /** * Sets a {@code cancelFn} to be called when a PolicyExecutor {@link #cancelDependencies(PolicyExecutor, boolean, * ExecutionResult) cancels dependencies} with a policyIndex > the given {@code policyIndex}, or when this future is * {@link #cancel(boolean) cancelled}. */ public synchronized void setCancelFn(int policyIndex, BiConsumer<Boolean, ExecutionResult<R>> cancelFn) { if (cancelFunctions == null) cancelFunctions = new TreeMap<>(Collections.reverseOrder()); cancelFunctions.put(policyIndex, cancelFn); } /** * Sets a {@code cancelFn} to be called when a PolicyExecutor {@link #cancelDependencies(PolicyExecutor, boolean, * ExecutionResult) cancels dependencies} with a policyIndex > the policyIndex of the given {@code policyExecutor}, or * when this future is {@link #cancel(boolean) cancelled}. */ public synchronized void setCancelFn(PolicyExecutor<R> policyExecutor, BiConsumer<Boolean, ExecutionResult<R>> cancelFn) { setCancelFn(policyExecutor.getPolicyIndex(), cancelFn); } /** * Propogates any previous cancellation to the {@code future}, either by cancelling it immediately or setting a cancel * function to cancel it later. */ public synchronized void propagateCancellation(Future<R> future) { if (isCancelled()) future.cancel(cancelledWithInterrupt); else setCancelFn(-2, (mayInterrupt, cancelResult) -> future.cancel(mayInterrupt)); } }
if (cancelFunctions != null) { int cancellingPolicyIndex = cancellingPolicyExecutor == null ? Integer.MAX_VALUE : cancellingPolicyExecutor.getPolicyIndex(); Iterator<Entry<Integer, BiConsumer<Boolean, ExecutionResult<R>>>> it = cancelFunctions.entrySet().iterator(); /* This iteration occurs in descending order to ensure that the {@code cancelResult} can be supplied to outer cancel functions before the inner supplier is cancelled, which would cause PolicyExecutors to complete with CancellationException rather than the expected {@code cancelResult}. */ while (it.hasNext()) { Map.Entry<Integer, BiConsumer<Boolean, ExecutionResult<R>>> entry = it.next(); if (cancellingPolicyIndex > entry.getKey()) { try { entry.getValue().accept(mayInterrupt, cancelResult); } catch (Exception ignore) { } it.remove(); } } }
1,249
238
1,487
<methods>public void <init>() ,public CompletableFuture<java.lang.Void> acceptEither(CompletionStage<? extends R>, Consumer<? super R>) ,public CompletableFuture<java.lang.Void> acceptEitherAsync(CompletionStage<? extends R>, Consumer<? super R>) ,public CompletableFuture<java.lang.Void> acceptEitherAsync(CompletionStage<? extends R>, Consumer<? super R>, java.util.concurrent.Executor) ,public static transient CompletableFuture<java.lang.Void> allOf(CompletableFuture<?>[]) ,public static transient CompletableFuture<java.lang.Object> anyOf(CompletableFuture<?>[]) ,public CompletableFuture<U> applyToEither(CompletionStage<? extends R>, Function<? super R,U>) ,public CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends R>, Function<? super R,U>) ,public CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends R>, Function<? super R,U>, java.util.concurrent.Executor) ,public boolean cancel(boolean) ,public boolean complete(R) ,public CompletableFuture<R> completeAsync(Supplier<? extends R>) ,public CompletableFuture<R> completeAsync(Supplier<? extends R>, java.util.concurrent.Executor) ,public boolean completeExceptionally(java.lang.Throwable) ,public CompletableFuture<R> completeOnTimeout(R, long, java.util.concurrent.TimeUnit) ,public static CompletableFuture<U> completedFuture(U) ,public static CompletionStage<U> completedStage(U) ,public CompletableFuture<R> copy() ,public java.util.concurrent.Executor defaultExecutor() ,public static java.util.concurrent.Executor delayedExecutor(long, java.util.concurrent.TimeUnit) ,public static java.util.concurrent.Executor delayedExecutor(long, java.util.concurrent.TimeUnit, java.util.concurrent.Executor) ,public CompletableFuture<R> exceptionally(Function<java.lang.Throwable,? extends R>) ,public CompletableFuture<R> exceptionallyAsync(Function<java.lang.Throwable,? extends R>) ,public CompletableFuture<R> exceptionallyAsync(Function<java.lang.Throwable,? extends R>, java.util.concurrent.Executor) ,public CompletableFuture<R> exceptionallyCompose(Function<java.lang.Throwable,? extends CompletionStage<R>>) ,public CompletableFuture<R> exceptionallyComposeAsync(Function<java.lang.Throwable,? extends CompletionStage<R>>) ,public CompletableFuture<R> exceptionallyComposeAsync(Function<java.lang.Throwable,? extends CompletionStage<R>>, java.util.concurrent.Executor) ,public static CompletableFuture<U> failedFuture(java.lang.Throwable) ,public static CompletionStage<U> failedStage(java.lang.Throwable) ,public R get() throws java.lang.InterruptedException, java.util.concurrent.ExecutionException,public R get(long, java.util.concurrent.TimeUnit) throws java.lang.InterruptedException, java.util.concurrent.ExecutionException, java.util.concurrent.TimeoutException,public R getNow(R) ,public int getNumberOfDependents() ,public CompletableFuture<U> handle(BiFunction<? super R,java.lang.Throwable,? extends U>) ,public CompletableFuture<U> handleAsync(BiFunction<? super R,java.lang.Throwable,? extends U>) ,public CompletableFuture<U> handleAsync(BiFunction<? super R,java.lang.Throwable,? extends U>, java.util.concurrent.Executor) ,public boolean isCancelled() ,public boolean isCompletedExceptionally() ,public boolean isDone() ,public R join() ,public CompletionStage<R> minimalCompletionStage() ,public CompletableFuture<U> newIncompleteFuture() ,public void obtrudeException(java.lang.Throwable) ,public void obtrudeValue(R) ,public CompletableFuture<R> orTimeout(long, java.util.concurrent.TimeUnit) ,public CompletableFuture<java.lang.Void> runAfterBoth(CompletionStage<?>, java.lang.Runnable) ,public CompletableFuture<java.lang.Void> runAfterBothAsync(CompletionStage<?>, java.lang.Runnable) ,public CompletableFuture<java.lang.Void> runAfterBothAsync(CompletionStage<?>, java.lang.Runnable, java.util.concurrent.Executor) ,public CompletableFuture<java.lang.Void> runAfterEither(CompletionStage<?>, java.lang.Runnable) ,public CompletableFuture<java.lang.Void> runAfterEitherAsync(CompletionStage<?>, java.lang.Runnable) ,public CompletableFuture<java.lang.Void> runAfterEitherAsync(CompletionStage<?>, java.lang.Runnable, java.util.concurrent.Executor) ,public static CompletableFuture<java.lang.Void> runAsync(java.lang.Runnable) ,public static CompletableFuture<java.lang.Void> runAsync(java.lang.Runnable, java.util.concurrent.Executor) ,public static CompletableFuture<U> supplyAsync(Supplier<U>) ,public static CompletableFuture<U> supplyAsync(Supplier<U>, java.util.concurrent.Executor) ,public CompletableFuture<java.lang.Void> thenAccept(Consumer<? super R>) ,public CompletableFuture<java.lang.Void> thenAcceptAsync(Consumer<? super R>) ,public CompletableFuture<java.lang.Void> thenAcceptAsync(Consumer<? super R>, java.util.concurrent.Executor) ,public CompletableFuture<java.lang.Void> thenAcceptBoth(CompletionStage<? extends U>, BiConsumer<? super R,? super U>) ,public CompletableFuture<java.lang.Void> thenAcceptBothAsync(CompletionStage<? extends U>, BiConsumer<? super R,? super U>) ,public CompletableFuture<java.lang.Void> thenAcceptBothAsync(CompletionStage<? extends U>, BiConsumer<? super R,? super U>, java.util.concurrent.Executor) ,public CompletableFuture<U> thenApply(Function<? super R,? extends U>) ,public CompletableFuture<U> thenApplyAsync(Function<? super R,? extends U>) ,public CompletableFuture<U> thenApplyAsync(Function<? super R,? extends U>, java.util.concurrent.Executor) ,public CompletableFuture<V> thenCombine(CompletionStage<? extends U>, BiFunction<? super R,? super U,? extends V>) ,public CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U>, BiFunction<? super R,? super U,? extends V>) ,public CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U>, BiFunction<? super R,? super U,? extends V>, java.util.concurrent.Executor) ,public CompletableFuture<U> thenCompose(Function<? super R,? extends CompletionStage<U>>) ,public CompletableFuture<U> thenComposeAsync(Function<? super R,? extends CompletionStage<U>>) ,public CompletableFuture<U> thenComposeAsync(Function<? super R,? extends CompletionStage<U>>, java.util.concurrent.Executor) ,public CompletableFuture<java.lang.Void> thenRun(java.lang.Runnable) ,public CompletableFuture<java.lang.Void> thenRunAsync(java.lang.Runnable) ,public CompletableFuture<java.lang.Void> thenRunAsync(java.lang.Runnable, java.util.concurrent.Executor) ,public CompletableFuture<R> toCompletableFuture() ,public java.lang.String toString() ,public CompletableFuture<R> whenComplete(BiConsumer<? super R,? super java.lang.Throwable>) ,public CompletableFuture<R> whenCompleteAsync(BiConsumer<? super R,? super java.lang.Throwable>) ,public CompletableFuture<R> whenCompleteAsync(BiConsumer<? super R,? super java.lang.Throwable>, java.util.concurrent.Executor) <variables>static final int ASYNC,private static final java.util.concurrent.Executor ASYNC_POOL,static final int NESTED,private static final java.lang.invoke.VarHandle NEXT,static final java.util.concurrent.CompletableFuture.AltResult NIL,private static final java.lang.invoke.VarHandle RESULT,private static final java.lang.invoke.VarHandle STACK,static final int SYNC,private static final boolean USE_COMMON_POOL,volatile java.lang.Object result,volatile java.util.concurrent.CompletableFuture.Completion stack
failsafe-lib_failsafe
failsafe/modules/okhttp/src/main/java/dev/failsafe/okhttp/FailsafeCall.java
FailsafeCallBuilder
prepareCall
class FailsafeCallBuilder { private FailsafeExecutor<Response> failsafe; private FailsafeCallBuilder(FailsafeExecutor<Response> failsafe) { this.failsafe = failsafe; } public <P extends Policy<Response>> FailsafeCallBuilder compose(P innerPolicy) { failsafe = failsafe.compose(innerPolicy); return this; } public FailsafeCall compose(okhttp3.Call call) { return new FailsafeCall(failsafe, call); } } /** * Returns a FailsafeCallBuilder for the {@code outerPolicy} and {@code policies}. See {@link Failsafe#with(Policy, * Policy[])} for docs on how policy composition works. * * @param <P> policy type * @throws NullPointerException if {@code call} or {@code outerPolicy} are null */ @SafeVarargs public static <P extends Policy<Response>> FailsafeCallBuilder with(P outerPolicy, P... policies) { return new FailsafeCallBuilder(Failsafe.with(outerPolicy, policies)); } /** * Returns a FailsafeCallBuilder for the {@code failsafeExecutor}. * * @throws NullPointerException if {@code failsafeExecutor} is null */ public static FailsafeCallBuilder with(FailsafeExecutor<Response> failsafeExecutor) { return new FailsafeCallBuilder(Assert.notNull(failsafeExecutor, "failsafeExecutor")); } /** * Cancels the call. */ public void cancel() { if (!cancelled.compareAndSet(false, true)) return; if (failsafeCall != null) failsafeCall.cancel(false); if (failsafeFuture != null) failsafeFuture.cancel(false); } /** * Returns a clone of the FailsafeCall. */ public FailsafeCall clone() { return new FailsafeCall(failsafe, initialCall.clone()); } /** * Executes the call until a successful response is returned or the configured policies are exceeded. To avoid leaking * resources callers should {@link Response#close() close} the Response which in turn will close the underlying * ResponseBody. * * @throws IllegalStateException if the call has already been executed * @throws IOException if the request could not be executed due to cancellation, a connectivity problem, or timeout * @throws FailsafeException if the execution fails with a checked Exception. {@link FailsafeException#getCause()} can * be used to learn the underlying checked exception. */ public Response execute() throws IOException { Assert.isTrue(executed.compareAndSet(false, true), "already executed"); failsafeCall = failsafe.newCall(ctx -> { return prepareCall(ctx).execute(); }); try { return failsafeCall.execute(); } catch (FailsafeException e) { if (e.getCause() instanceof IOException) throw (IOException) e.getCause(); throw e; } } /** * Executes the call asynchronously until a successful result is returned or the configured policies are exceeded. To * avoid leaking resources callers should {@link Response#close() close} the Response which in turn will close the * underlying ResponseBody. */ public CompletableFuture<Response> executeAsync() { if (!executed.compareAndSet(false, true)) { CompletableFuture<Response> result = new CompletableFuture<>(); result.completeExceptionally(new IllegalStateException("already executed")); return result; } failsafeFuture = failsafe.getAsyncExecution(exec -> { prepareCall(exec).enqueue(new Callback() { @Override public void onResponse(okhttp3.Call call, Response response) { exec.recordResult(response); } @Override public void onFailure(okhttp3.Call call, IOException e) { exec.recordException(e); } }); }); return failsafeFuture; } /** * Returns whether the call has been cancelled. */ public boolean isCancelled() { return cancelled.get(); } /** * Returns whether the call has been executed. */ public boolean isExecuted() { return executed.get(); } private okhttp3.Call prepareCall(ExecutionContext<Response> ctx) {<FILL_FUNCTION_BODY>
okhttp3.Call call; if (ctx.isFirstAttempt()) { call = initialCall; } else { Response response = ctx.getLastResult(); if (response != null) response.close(); call = initialCall.clone(); } // Propagate cancellation to the call ctx.onCancel(() -> { cancelled.set(true); call.cancel(); }); return call;
1,156
118
1,274
<no_super_class>
failsafe-lib_failsafe
failsafe/modules/retrofit/src/main/java/dev/failsafe/retrofit/FailsafeCall.java
FailsafeCallBuilder
executeAsync
class FailsafeCallBuilder<R> { private FailsafeExecutor<Response<R>> failsafe; private FailsafeCallBuilder(FailsafeExecutor<Response<R>> failsafe) { this.failsafe = failsafe; } public <P extends Policy<Response<R>>> FailsafeCallBuilder<R> compose(P innerPolicy) { failsafe = failsafe.compose(innerPolicy); return this; } public FailsafeCall<R> compose(retrofit2.Call<R> call) { return new FailsafeCall<>(failsafe, call); } } /** * Returns a FailsafeCallBuilder for the {@code outerPolicy} and {@code policies}. See {@link Failsafe#with(Policy, * Policy[])} for docs on how policy composition works. * * @param <R> result type * @param <P> policy type * @throws NullPointerException if {@code call} or {@code outerPolicy} are null */ @SafeVarargs public static <R, P extends Policy<Response<R>>> FailsafeCallBuilder<R> with(P outerPolicy, P... policies) { return new FailsafeCallBuilder<>(Failsafe.with(outerPolicy, policies)); } /** * Returns a FailsafeCallBuilder for the {@code failsafeExecutor}. * * @param <R> result type * @throws NullPointerException if {@code failsafeExecutor} is null */ public static <R> FailsafeCallBuilder<R> with(FailsafeExecutor<Response<R>> failsafeExecutor) { return new FailsafeCallBuilder<>(Assert.notNull(failsafeExecutor, "failsafeExecutor")); } /** * Cancels the call. */ public void cancel() { if (!cancelled.compareAndSet(false, true)) return; if (failsafeCall != null) failsafeCall.cancel(false); if (failsafeFuture != null) failsafeFuture.cancel(false); } /** * Returns a clone of the FailsafeCall. */ public FailsafeCall<R> clone() { return new FailsafeCall<>(failsafe, initialCall.clone()); } /** * Executes the call until a successful response is returned or the configured policies are exceeded. * * @throws IllegalStateException if the call has already been executed * @throws IOException if the request could not be executed due to cancellation, a connectivity problem, or timeout * @throws FailsafeException if the execution fails with a checked Exception. {@link FailsafeException#getCause()} can * be used to learn the underlying checked exception. */ public Response<R> execute() throws IOException { Assert.isTrue(executed.compareAndSet(false, true), "already executed"); failsafeCall = failsafe.newCall(ctx -> { return prepareCall(ctx).execute(); }); try { return failsafeCall.execute(); } catch (FailsafeException e) { if (e.getCause() instanceof IOException) throw (IOException) e.getCause(); throw e; } } /** * Executes the call asynchronously until a successful result is returned or the configured policies are exceeded. */ public CompletableFuture<Response<R>> executeAsync() {<FILL_FUNCTION_BODY>
if (!executed.compareAndSet(false, true)) { CompletableFuture<Response<R>> result = new CompletableFuture<>(); result.completeExceptionally(new IllegalStateException("already executed")); return result; } failsafeFuture = failsafe.getAsyncExecution(exec -> { prepareCall(exec).enqueue(new Callback<R>() { @Override public void onResponse(retrofit2.Call<R> call, Response<R> response) { exec.recordResult(response); } @Override public void onFailure(retrofit2.Call<R> call, Throwable throwable) { exec.recordException(throwable); } }); }); return failsafeFuture;
882
195
1,077
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/ASCIICheck.java
ASCIICheck
f1
class ASCIICheck { static char[] chars = "http://javaone.com/keynote_large.jpg".toCharArray(); @Benchmark public void f0_vec(Blackhole bh) { boolean ascii = true; { int i = 0; while (i + 4 <= chars.length) { char c0 = chars[i]; char c1 = chars[i + 1]; char c2 = chars[i + 2]; char c3 = chars[i + 3]; if (c0 > 0x007F || c1 > 0x007F || c2 > 0x007F || c3 > 0x007F) { ascii = false; break; } i += 4; } if (ascii) { for (; i < chars.length; ++i) { if (chars[i] > 0x007F) { ascii = false; break; } } } } bh.consume(ascii); } @Benchmark public void f1(Blackhole bh) {<FILL_FUNCTION_BODY>} @Benchmark public void f2_vec(Blackhole bh) { boolean ascii = true; { int i = 0; while (i + 4 <= chars.length) { char c0 = chars[i]; char c1 = chars[i + 1]; char c2 = chars[i + 2]; char c3 = chars[i + 3]; if (c0 > 0x007F || c1 > 0x007F || c2 > 0x007F || c3 > 0x007F) { ascii = false; break; } i += 4; } if (ascii) { for (; i < chars.length; ++i) { if (chars[i] > 0x007F) { ascii = false; break; } } } } bh.consume(ascii); } @Benchmark public void f3(Blackhole bh) { boolean ascii = true; for (int i = 0; i < chars.length; ++i) { if (chars[i] > 0x007F) { ascii = false; break; } } bh.consume(ascii); } public static void main(String[] args) throws RunnerException { Options options = new OptionsBuilder() .include(ASCIICheck.class.getName()) .mode(Mode.Throughput) .warmupIterations(3) .timeUnit(TimeUnit.MILLISECONDS) .forks(1) .build(); new Runner(options).run(); } }
boolean ascii = true; for (int i = 0; i < chars.length; ++i) { if (chars[i] > 0x007F) { ascii = false; break; } } bh.consume(ascii);
782
80
862
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/ASCIICheckTest.java
ASCIICheckTest
f0_perf_test
class ASCIICheckTest { static final Blackhole BH = new Blackhole("Today's password is swordfish. I understand instantiating Blackholes directly is dangerous."); public void f0_perf() { ASCIICheck benchmark = new ASCIICheck(); long start = System.currentTimeMillis(); for (int i = 0; i < 1000 * 1000 * 100; ++i) { benchmark.f0_vec(BH); } long millis = System.currentTimeMillis() - start; System.out.println("f0 millis : " + millis); // zulu11.52.13 : // zulu17.32.13 : // zulu8.58.0.13 : } public void f0_perf_test() {<FILL_FUNCTION_BODY>} public void f1_perf() { ASCIICheck benchmark = new ASCIICheck(); long start = System.currentTimeMillis(); for (int i = 0; i < 1000 * 1000 * 100; ++i) { benchmark.f1(BH); } long millis = System.currentTimeMillis() - start; System.out.println("f1 millis : " + millis); // zulu11.52.13 : // zulu17.32.13 : // zulu8.58.0.13 : } public void f1_perf_test() { for (int i = 0; i < 10; i++) { f1_perf(); // } } public static void main(String[] args) throws Exception { ASCIICheckTest benchmark = new ASCIICheckTest(); benchmark.f0_perf_test(); benchmark.f1_perf_test(); } }
for (int i = 0; i < 10; i++) { f0_perf(); // }
504
33
537
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/BytesAsciiCheck.java
BytesAsciiCheck
hasNegatives_8
class BytesAsciiCheck { static byte[] bytes; static { try { InputStream is = EishayParseBinaryArrayMapping.class.getClassLoader().getResourceAsStream("data/eishay.json"); String str = IOUtils.toString(is, "UTF-8"); bytes = str.getBytes(); } catch (Exception e) { e.printStackTrace(); } } @Benchmark public void handler(Blackhole bh) throws Throwable { bh.consume( JDKUtils.METHOD_HANDLE_HAS_NEGATIVE.invoke(bytes, 0, bytes.length) ); } @Benchmark public void lambda(Blackhole bh) throws Throwable { bh.consume( JDKUtils.PREDICATE_IS_ASCII.test(bytes) ); } @Benchmark public void direct(Blackhole bh) throws Throwable { bh.consume(hasNegatives(bytes, 0, bytes.length)); } @Benchmark public void direct8(Blackhole bh) throws Throwable { bh.consume(hasNegatives_8(bytes, 0, bytes.length)); } public static boolean hasNegatives(byte[] ba, int off, int len) { for (int i = off; i < off + len; i++) { if (ba[i] < 0) { return true; } } return false; } public static boolean hasNegatives_8(byte[] bytes, int off, int len) {<FILL_FUNCTION_BODY>} public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() .include(BytesAsciiCheck.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .build(); new Runner(options).run(); } }
int i = off; while (i + 8 <= off + len) { if ((UNSAFE.getLong(bytes, ARRAY_BYTE_BASE_OFFSET + i) & 0x8080808080808080L) != 0) { return true; } i += 8; } for (; i < off + len; i++) { if (bytes[i] < 0) { return true; } } return false;
540
136
676
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/CSVBank.java
CSVBank
cainiao
class CSVBank { static final String file = "csv/banklist.csv"; static byte[] byteArray; static { try (InputStream is = EishayParseBinary.class.getClassLoader().getResourceAsStream(file)) { String str = IOUtils.toString(is, "UTF-8"); byteArray = str.getBytes(); } catch (IOException e) { throw new RuntimeException(e); } } @Benchmark public void fastjson2(Blackhole BH) { CSVReader .of(new ByteArrayInputStream(byteArray), Bank.class) .readLineObjectAll(BH::consume); } @Benchmark public void univocity(Blackhole BH) { CsvParserSettings settings = new CsvParserSettings(); CsvRoutines processor = new CsvRoutines(settings); settings.getFormat().setLineSeparator("\n"); settings.setNumberOfRowsToSkip(1); processor.iterate(Bank.class, new ByteArrayInputStream(byteArray)) .forEach(BH::consume); } public void cainiao(Blackhole BH) {<FILL_FUNCTION_BODY>} public static class Bank { @Parsed(index = 0) public String bankName; @Parsed(index = 1) public String city; @Parsed(index = 2) public String state; @Parsed(index = 3) public Integer cert; @Parsed(index = 4) public String acquiringInstitution; @Parsed(index = 5) public String closingDate; @Parsed(index = 6) public Integer fund; } public static void main(String[] args) throws RunnerException { Options options = new OptionsBuilder() .include(CSVBank.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .build(); new Runner(options).run(); } }
// com.cainiao.ai.seq.csv.CsvType.of(Bank.class, false) // .csvReader(',') // .read(com.cainiao.ai.seq.InputSource.of(byteArray), 1) // .supply(BH::consume);
557
81
638
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/CSVBankList.java
CSVBankList
readLineValues
class CSVBankList { static final String file = "csv/banklist.csv"; @Benchmark public void rowCount(Blackhole bh) throws IOException { URL resource = Thread.currentThread().getContextClassLoader().getResource(file); if (resource == null) { return; } File file = new File(resource.getFile()); FileInputStream fileIn = new FileInputStream(file); int rowCount = CSVReader.rowCount(fileIn); bh.consume(rowCount); } @Benchmark public void readLines(Blackhole bh) throws IOException { URL resource = Thread.currentThread().getContextClassLoader().getResource(file); if (resource == null) { return; } File file = new File(resource.getFile()); CSVReader parser = CSVReader.of(file); int rowCount = 0; while (true) { String[] line = parser.readLine(); if (line == null) { break; } rowCount++; } bh.consume(rowCount); } @Benchmark public void readLineValues(Blackhole bh) throws IOException {<FILL_FUNCTION_BODY>} }
URL resource = Thread.currentThread().getContextClassLoader().getResource(file); if (resource == null) { return; } File file = new File(resource.getFile()); Type[] types = new Type[] { String.class, String.class, String.class, Integer.class, String.class, Date.class, Integer.class }; CSVReader parser = CSVReader.of(file, types); parser.readHeader(); int rowCount = 0; while (true) { Object[] line = parser.readLineValues(); if (line == null) { break; } rowCount++; } bh.consume(rowCount);
328
182
510
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/CSVBig38M.java
CSVBig38M
rowCount
class CSVBig38M { @Benchmark public void rowCount(Blackhole bh) throws IOException {<FILL_FUNCTION_BODY>} @Benchmark public void readLines(Blackhole bh) throws IOException { URL resource = Thread.currentThread().getContextClassLoader().getResource("organised_Gen.csv"); if (resource == null) { return; } File file = new File(resource.getFile()); CSVReader parser = CSVReader.of(file); int rowCount = 0; while (true) { String[] line = parser.readLine(); if (line == null) { break; } rowCount++; } bh.consume(rowCount); } @Benchmark public void readLineValues(Blackhole bh) throws IOException { URL resource = Thread.currentThread().getContextClassLoader().getResource("organised_Gen.csv"); if (resource == null) { return; } File file = new File(resource.getFile()); Type[] types = new Type[] { Integer.class, Integer.class, Integer.class, String.class, String.class, String.class, BigDecimal.class }; CSVReader parser = CSVReader.of(file, types); int rowCount = 0; while (true) { Object[] line = parser.readLineValues(); if (line == null) { break; } rowCount++; } bh.consume(rowCount); } }
URL resource = Thread.currentThread().getContextClassLoader().getResource("organised_Gen.csv"); if (resource == null) { return; } File file = new File(resource.getFile()); FileInputStream fileIn = new FileInputStream(file); int rowCount = CSVReader.rowCount(fileIn); bh.consume(rowCount);
407
98
505
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/CSVCDCList.java
CSVCDCList
readLineValues
class CSVCDCList { static final String file = "csv/CDC_STATE_System_E-Cigarette_Legislation_-_Tax.csv"; @Benchmark public void rowCount(Blackhole bh) throws IOException { URL resource = Thread.currentThread().getContextClassLoader().getResource(file); if (resource == null) { return; } File file = new File(resource.getFile()); FileInputStream fileIn = new FileInputStream(file); int rowCount = CSVReader.rowCount(fileIn); bh.consume(rowCount); } @Benchmark public void readLines(Blackhole bh) throws IOException { URL resource = Thread.currentThread().getContextClassLoader().getResource(file); if (resource == null) { return; } File file = new File(resource.getFile()); CSVReader parser = CSVReader.of(file); int rowCount = 0; while (true) { String[] line = parser.readLine(); if (line == null) { break; } rowCount++; } bh.consume(rowCount); } @Benchmark public void readLineValues(Blackhole bh) throws IOException {<FILL_FUNCTION_BODY>} }
URL resource = Thread.currentThread().getContextClassLoader().getResource(file); if (resource == null) { return; } File file = new File(resource.getFile()); Type[] types = new Type[] { Integer.class, // YEAR Integer.class, // Quator String.class, // Location String.class, // LocationDesc String.class, // TopicDesc String.class, // MeasureDesc String.class, // DataSource String.class, // ProvisionGroupDesc String.class, // ProvisionDesc String.class, // ProvisionValue String.class, // Citation BigDecimal.class, // ProvisionAltValue String.class, // DataType String.class, // Comments Date.class, // Enacted_Date Date.class, // Effective_Date String.class, // GeoLocation Integer.class, // DisplayOrder String.class, // TopicTypeId String.class, // TopicId String.class, // MeasureId String.class, // ProvisionGroupID Integer.class // ProvisionID }; CSVReader parser = CSVReader.of(file, types); parser.readHeader(); int rowCount = 0; while (true) { Object[] line = parser.readLineValues(); if (line == null) { break; } rowCount++; } bh.consume(rowCount);
345
383
728
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/CSVCOVID19.java
Covid19
main
class Covid19 { @Parsed(index = 0) public String providerName; @Parsed(index = 1) public String address1; @Parsed(index = 2) public String address2; @Parsed(index = 3) public String city; @Parsed(index = 4) public String county; @Parsed(index = 5) public String stateCode; @Parsed(index = 6) public Integer zip; @Parsed(index = 7) public String nationalDrugCode; @Parsed(index = 8) public String orderLabel; @Parsed(index = 9) public Integer coursesAvailable; @Parsed(index = 10) public String geocodedAddress; @Parsed(index = 11) public String npi; @Parsed(index = 12) public String lastReportDate; @Parsed(index = 13) public String providerStatus; @Parsed(index = 14) public String providerNote; } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>
Options options = new OptionsBuilder() .include(CSVCOVID19.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .measurementTime(TimeValue.seconds(30)) .build(); new Runner(options).run();
330
102
432
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/CSVCOVID19List.java
CSVCOVID19List
readLineValues
class CSVCOVID19List { static final String file = "csv/COVID-19_Public_Therapeutic_Locator.csv"; @Benchmark public void rowCount(Blackhole bh) throws IOException { URL resource = Thread.currentThread().getContextClassLoader().getResource(file); if (resource == null) { return; } File file = new File(resource.getFile()); FileInputStream fileIn = new FileInputStream(file); int rowCount = CSVReader.rowCount(fileIn); bh.consume(rowCount); } @Benchmark public void readLines(Blackhole bh) throws IOException { URL resource = Thread.currentThread().getContextClassLoader().getResource(file); if (resource == null) { return; } File file = new File(resource.getFile()); CSVReader parser = CSVReader.of(file); int rowCount = 0; while (true) { String[] line = parser.readLine(); if (line == null) { break; } rowCount++; } bh.consume(rowCount); } @Benchmark public void readLineValues(Blackhole bh) throws IOException {<FILL_FUNCTION_BODY>} }
URL resource = Thread.currentThread().getContextClassLoader().getResource(file); if (resource == null) { return; } File file = new File(resource.getFile()); Type[] types = new Type[] { String.class, // Provider Name String.class, // Address1 String.class, // Address2 String.class, // City String.class, // County String.class, // State Code Integer.class, // Zip String.class, // National Drug Code String.class, // Order Label Integer.class, // Courses Available String.class, // Geocoded Address String.class, // NPI Date.class, // Last Report Date String.class, // Provider Status String.class, // Provider Note }; CSVReader parser = CSVReader.of(file, types); parser.readHeader(); int rowCount = 0; while (true) { Object[] line = parser.readLineValues(); if (line == null) { break; } rowCount++; } bh.consume(rowCount);
343
298
641
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/CSVPerson.java
CSVPerson
cainiao
class CSVPerson { static final String file = "csv/person.csv"; static byte[] byteArray; static { try (InputStream is = EishayParseBinary.class.getClassLoader().getResourceAsStream(file)) { String str = IOUtils.toString(is, "UTF-8"); byteArray = str.getBytes(); } catch (IOException e) { throw new RuntimeException(e); } } @Benchmark public void fastjson2(Blackhole BH) { CSVReader .of(new ByteArrayInputStream(byteArray), StandardCharsets.UTF_8, Person.class) .readLineObjectAll(BH::consume); } @Benchmark public void univocity(Blackhole BH) { CsvParserSettings settings = new CsvParserSettings(); CsvRoutines processor = new CsvRoutines(settings); settings.getFormat().setLineSeparator("\n"); settings.setNumberOfRowsToSkip(1); processor.iterate(Person.class, new ByteArrayInputStream(byteArray)) .forEach(BH::consume); } public void cainiao(Blackhole BH) {<FILL_FUNCTION_BODY>} @Data public static class Person { @Parsed(index = 0) public String name; @Parsed(index = 1) public Double weight; @Parsed(index = 2) public Integer age; @Parsed(index = 3) public String gender; @Parsed(index = 4) public Integer height; @Parsed(index = 5) public String address; @Parsed(index = 6) public Integer id; @Parsed(index = 7) public Boolean single; } public static void main(String[] args) throws RunnerException { Options options = new OptionsBuilder() .include(CSVPerson.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .build(); new Runner(options).run(); } }
// com.cainiao.ai.seq.csv.CsvType.of(Person.class, false) // .csvReader(',') // .read(com.cainiao.ai.seq.InputSource.of(byteArray), 1) // .supply(BH::consume);
571
80
651
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/CSVReaderCOVID19.java
CSVReaderCOVID19
main
class CSVReaderCOVID19 { static final String file = "csv/COVID-19_Public_Therapeutic_Locator.csv"; static byte[] byteArray; static { try (InputStream is = EishayParseBinary.class.getClassLoader().getResourceAsStream(file)) { String str = IOUtils.toString(is, "UTF-8"); byteArray = str.getBytes(); } catch (IOException e) { throw new RuntimeException(e); } } @Benchmark public void fastjson2(Blackhole BH) throws IOException { CSVReader.of(new ByteArrayInputStream(byteArray)) .readLineObjectAll(BH::consume); } @Benchmark public void csvReader(Blackhole BH) throws IOException { CsvReader csvReader = new CsvReader(new InputStreamReader(new ByteArrayInputStream(byteArray))); while (true) { if (!csvReader.readRecord()) { break; } String[] line = csvReader.getValues(); BH.consume(line); } } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(CSVReaderCOVID19.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .measurementTime(TimeValue.seconds(30)) .build(); new Runner(options).run();
318
103
421
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/CartItemDO2Benchmark.java
CartItemDO2Benchmark
newCartsItem
class CartItemDO2Benchmark { private static volatile List<CartItemDO2> list; // 使用 volatile 修饰确保可见性 private static List<CartItemDO2> newCartsItem() {<FILL_FUNCTION_BODY>} @Benchmark public byte[] testCartItem() throws Exception { return JSONB.toBytes( newCartsItem(), JSONB.symbolTable("myId"), JSONWriter.Feature.BeanToArray ); } }
if (list != null) { return list; } synchronized (CartItemDO2Benchmark.class) { if (list == null) { list = new ArrayList<>(); for (long i = 90000000000L; i < 90000000000L + 1000; i++) { CartItemDO2 cartItemDO2 = new CartItemDO2(); cartItemDO2.setUserId(i); cartItemDO2.setAttributes(new HashMap<>()); cartItemDO2.setCartId(i * 100); cartItemDO2.setCityCode(i * 12); cartItemDO2.setItemId(i * 3); cartItemDO2.setMainType(11); cartItemDO2.setQuantity(900); cartItemDO2.setSkuId(i * 5); cartItemDO2.setSubType(i * 6); cartItemDO2.setTpId(i * 7); cartItemDO2.setTrackId(String.valueOf(i * 8)); list.add(cartItemDO2); } } } return list;
128
320
448
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/CartTree.java
CartTree
main
class CartTree { static String str; static byte[] jsonbBytes; static ObjectMapper mapper = new ObjectMapper(); public CartTree() { try { InputStream is = CartTree.class.getClassLoader().getResourceAsStream("data/cart.json"); str = IOUtils.toString(is, "UTF-8"); jsonbBytes = JSONB.toBytes( JSON.parseObject(str, Map.class), JSONWriter.Feature.WriteNameAsSymbol ); } catch (Exception ex) { ex.printStackTrace(); } } @Benchmark public void fastjson1(Blackhole bh) { bh.consume( com.alibaba.fastjson.JSON.parseObject(str, Map.class) ); } @Benchmark public void fastjson2(Blackhole bh) { bh.consume( JSON.parseObject(str) ); } @Benchmark public void wastjson(Blackhole bh) { bh.consume( io.github.wycst.wast.json.JSON.parseObject(str, Map.class) ); } @Benchmark public void fastjson2_jsonb(Blackhole bh) { bh.consume( JSONB.parseObject(jsonbBytes, Map.class) ); } @Benchmark public void jackson(Blackhole bh) throws Exception { bh.consume( mapper.readValue(str, Map.class) ); } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(CartTree.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .build(); new Runner(options).run();
446
83
529
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/DecodeASCIIBenchmarkJDK8.java
DecodeASCIIBenchmarkJDK8
main
class DecodeASCIIBenchmarkJDK8 { static byte[] utf8Bytes = new byte[128]; static int utf8BytesLength; static long valueFieldOffset; static { try { Field valueField = String.class.getDeclaredField("value"); valueFieldOffset = UNSAFE.objectFieldOffset(valueField); } catch (Throwable e) { e.printStackTrace(); } byte[] bytes = "01234567890ABCDEFGHIJKLMNOPQRSTUVWZYZabcdefghijklmnopqrstuvwzyz".getBytes(StandardCharsets.UTF_8); System.arraycopy(bytes, 0, utf8Bytes, 0, bytes.length); utf8BytesLength = bytes.length; } @Benchmark public String unsafeEncodeUTF8() throws Exception { char[] chars = new char[utf8BytesLength]; for (int i = 0; i < utf8BytesLength; i++) { chars[i] = (char) utf8Bytes[i]; } return STRING_CREATOR_JDK8.apply(chars, Boolean.TRUE); } @Benchmark public String newStringUTF8() throws Exception { return new String(utf8Bytes, 0, utf8BytesLength, StandardCharsets.UTF_8); } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(DecodeASCIIBenchmarkJDK8.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .forks(1) .build(); new Runner(options).run();
392
81
473
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/DecodeUTF8BenchmarkJDK17.java
DecodeUTF8BenchmarkJDK17
getLookup
class DecodeUTF8BenchmarkJDK17 { static byte[] utf8Bytes = "01234567890ABCDEFGHIJKLMNOPQRSTUVWZYZabcdefghijklmnopqrstuvwzyz" .getBytes(StandardCharsets.UTF_8); static long valueFieldOffset; static BiFunction<byte[], Charset, String> stringCreator; static { try { Field valueField = String.class.getDeclaredField("value"); valueFieldOffset = UNSAFE.objectFieldOffset(valueField); stringCreator = getStringCreatorJDK17(); } catch (Throwable e) { e.printStackTrace(); } } public static BiFunction<byte[], Charset, String> getStringCreatorJDK17() throws Throwable { // GraalVM not support // Android not support MethodHandles.Lookup lookup = getLookup(); MethodHandles.Lookup caller = lookup.in(String.class); MethodHandle handle = caller.findStatic( String.class, "newStringNoRepl1", MethodType.methodType(String.class, byte[].class, Charset.class) ); CallSite callSite = LambdaMetafactory.metafactory( caller, "apply", MethodType.methodType(BiFunction.class), handle.type().generic(), handle, handle.type() ); return (BiFunction<byte[], Charset, String>) callSite.getTarget().invokeExact(); } private static MethodHandles.Lookup getLookup() throws Exception {<FILL_FUNCTION_BODY>} @Benchmark public String unsafeEncodeUTF8_17() throws Exception { byte[] buf = new byte[utf8Bytes.length * 2]; int len = IOUtils.decodeUTF8(utf8Bytes, 0, utf8Bytes.length, buf); byte[] chars = Arrays.copyOf(buf, len); return stringCreator.apply(chars, StandardCharsets.US_ASCII); } @Benchmark public String newStringUTF8_17() throws Exception { return new String(utf8Bytes); } public static void main(String[] args) throws RunnerException { Options options = new OptionsBuilder() .include(DecodeUTF8BenchmarkJDK17.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .forks(1) .build(); new Runner(options).run(); } }
// GraalVM not support // Android not support MethodHandles.Lookup lookup; if (JVM_VERSION >= 17) { Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class.getDeclaredConstructor(Class.class, Class.class, int.class); constructor.setAccessible(true); lookup = constructor.newInstance( String.class, null, -1 // Lookup.TRUSTED ); } else { Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class.getDeclaredConstructor(Class.class, int.class); constructor.setAccessible(true); lookup = constructor.newInstance( String.class, -1 // Lookup.TRUSTED ); } return lookup;
683
211
894
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/DoubleArray20.java
DoubleArray20
main
class DoubleArray20 { static String str; static ObjectMapper mapper = new ObjectMapper(); static { try { InputStream is = EishayParseTreeString.class.getClassLoader().getResourceAsStream("data/double_array_20.json"); str = IOUtils.toString(is, "UTF-8"); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void fastjson2(Blackhole bh) { bh.consume(JSON.parseObject(str, double[].class)); // zulu11.52.13 : // zulu17.32.13 : // zulu8.58.0.13 : 236.517 } @Benchmark public void fastjson2_tree(Blackhole bh) { bh.consume(JSON.parse(str, JSONReader.Feature.UseBigDecimalForDoubles)); // zulu11.52.13 : // zulu17.32.13 : // zulu8.58.0.13 : } @Benchmark public void jackson(Blackhole bh) throws Exception { bh.consume(mapper.readValue(str, double[].class)); // zulu11.52.13 : // zulu17.32.13 : // zulu8.58.0.13 : 309.855 } @Benchmark public void wastjson(Blackhole bh) throws Exception { bh.consume( io.github.wycst.wast.json.JSON.parseObject(str, double[].class) ); // zulu11.52.13 : // zulu17.32.13 : // zulu8.58.0.13 : } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(DoubleArray20.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .forks(1) .warmupIterations(3) .build(); new Runner(options).run();
536
85
621
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/EncodeUTF8Benchmark.java
EncodeUTF8Benchmark
main
class EncodeUTF8Benchmark { static String STR = "01234567890ABCDEFGHIJKLMNOPQRSTUVWZYZabcdefghijklmnopqrstuvwzyz一二三四五六七八九十"; static byte[] out; static long valueFieldOffset; static { out = new byte[STR.length() * 3]; try { Field valueField = String.class.getDeclaredField("value"); valueFieldOffset = UNSAFE.objectFieldOffset(valueField); } catch (NoSuchFieldException e) { e.printStackTrace(); } } @Benchmark public int unsafeEncodeUTF8() throws Exception { char[] chars = (char[]) UNSAFE.getObject(STR, valueFieldOffset); return IOUtils.encodeUTF8(chars, 0, chars.length, out, 0); } @Benchmark public byte[] getBytesUTF8() throws Exception { byte[] bytes = STR.getBytes(StandardCharsets.UTF_8); System.arraycopy(bytes, 0, out, 0, bytes.length); return out; } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(EncodeUTF8Benchmark.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .forks(1) .build(); new Runner(options).run();
346
77
423
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/HomepageTree.java
HomepageTree
main
class HomepageTree { static String str; static byte[] jsonbBytes; static ObjectMapper mapper = new ObjectMapper(); public HomepageTree() { try { InputStream is = HomepageTree.class.getClassLoader().getResourceAsStream("data/homepage.json"); str = IOUtils.toString(is, "UTF-8"); jsonbBytes = JSONB.toBytes( JSON.parseObject(str, Map.class), JSONWriter.Feature.WriteNameAsSymbol ); } catch (Exception ex) { ex.printStackTrace(); } } @Benchmark public void fastjson1(Blackhole bh) { bh.consume( com.alibaba.fastjson.JSON.parseObject(str, Map.class) ); } @Benchmark public void fastjson2(Blackhole bh) { bh.consume( JSON.parseObject(str, Map.class) ); } @Benchmark public void fastjson2_jsonb(Blackhole bh) { bh.consume( JSONB.parseObject(jsonbBytes, Map.class) ); } @Benchmark public void jackson(Blackhole bh) throws Exception { bh.consume( mapper.readValue(str, Map.class) ); } @Benchmark public void wastjson(Blackhole bh) { bh.consume( io.github.wycst.wast.json.JSON.parseObject(str, Map.class) ); } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(HomepageTree.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .build(); new Runner(options).run();
454
84
538
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/Issue210.java
Bean
main
class Bean { private String password; public Bean() { } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>
new Issue210().beanSet(); // Options options = new OptionsBuilder() // .include(Issue210.class.getName()) // .mode(Mode.Throughput) // .timeUnit(TimeUnit.MILLISECONDS) // .forks(1) // .build(); // new Runner(options).run();
93
94
187
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/Issue609.java
Issue609
main
class Issue609 { private static final List<Student> objList; private static final List<String> strList; private static final String source; static { objList = new ArrayList<>(100000); strList = new ArrayList<>(100000); for (int i = 0; i < 100000; i++) { Student student = new Student("学生姓名" + i, i % 10, "黑龙江省哈尔滨市南方区哈尔滨大街267号" + i); objList.add(student); strList.add(JSON.toJSONString(student)); } source = JSON.toJSONString(objList); } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} @Benchmark @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) public void fastJSON1ObjSeThroughput(Blackhole bh) { for (Student student : objList) { bh.consume(JSON.toJSONString(student)); } } @Benchmark @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) public void fastJSON1ObjDeThroughput(Blackhole bh) { for (String student : strList) { bh.consume(JSON.parseObject(student, Student.class)); } } @Benchmark @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) public void fastJSON2ObjSeThroughput(Blackhole bh) { for (Student student : objList) { bh.consume( com.alibaba.fastjson2.JSON.toJSONString(student) ); } } @Benchmark @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) public void fastJSON2ObjDeThroughput(Blackhole bh) { for (String student : strList) { bh.consume(com.alibaba.fastjson2.JSON.parseObject(student, Student.class)); } } @Benchmark @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) public void fastJSON1ArraySeThroughput(Blackhole bh) { bh.consume( JSON.toJSONString(objList) ); } @Benchmark @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) public void fastJSON1ArrayDeThroughput(Blackhole bh) { bh.consume( JSON.parseArray(source, Student.class) ); } @Benchmark @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) public void fastJSON2ArraySeThroughput(Blackhole bh) { bh.consume( com.alibaba.fastjson2.JSON.toJSONString(objList, JSONWriter.Feature.ReferenceDetection) ); } @Benchmark @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) public void fastJSON2ArrayDeThroughput(Blackhole bh) { bh.consume( com.alibaba.fastjson2.JSON.parseArray(source, Student.class) ); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) public void fastJSON1ObjSeTime(Blackhole bh) { for (Student student : objList) { bh.consume( JSON.toJSONString(student) ); } } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) public void fastJSON1ObjDeTime(Blackhole bh) { for (String student : strList) { bh.consume( JSON.parseObject(student, Student.class) ); } } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) public void fastJSON2ObjSeTime(Blackhole bh) { for (Student student : objList) { bh.consume( com.alibaba.fastjson2.JSON.toJSONString(student) ); } } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) public void fastJSON2ObjDeTime(Blackhole bh) { for (String student : strList) { bh.consume(com.alibaba.fastjson2.JSON.parseObject(student, Student.class)); } } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) public void fastJSON1ArraySeTime(Blackhole bh) { bh.consume(JSON.toJSONString(objList)); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) public void fastJSON1ArrayDeTime(Blackhole bh) { bh.consume( JSON.parseArray(source, Student.class) ); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) public void fastJSON2ArraySeTime(Blackhole bh) { bh.consume(com.alibaba.fastjson2.JSON.toJSONString(objList, JSONWriter.Feature.ReferenceDetection)); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) public void fastJSON2ArrayDeTime(Blackhole bh) { bh.consume(com.alibaba.fastjson2.JSON.parseArray(source, Student.class)); } private static class Student { private String name; private int age; private String address; public Student() { } public Student(String name, int age, String address) { this.name = name; this.age = age; this.address = address; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } } }
Options opt = new OptionsBuilder() .include(Issue609.class.getName()) .warmupIterations(3) .measurementIterations(5) .forks(1) .jvmArgsAppend("-Xms128m", "-Xmx128m") .build(); new Runner(opt).run();
1,873
96
1,969
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/JSONReaderNewAndClose.java
JSONReaderNewAndClose
fastjson2
class JSONReaderNewAndClose { public static void fastjson2() {<FILL_FUNCTION_BODY>} public static void fastjson2_0() { JSONWriter writer = JSONWriter.of(); BH.consume(writer); writer.close(); } public static void main(String[] args) throws Exception { fastjson2_0(); fastjson2(); } }
for (int j = 0; j < 5; j++) { long start = System.currentTimeMillis(); for (int i = 0; i < 100_000_000; ++i) { fastjson2_0(); } long millis = System.currentTimeMillis() - start; System.out.println("fastjson2 millis : " + millis); // zulu8.58.0.13 : 1234 // zulu11.52.13 : 1123 // zulu17.32.13 : 1073 }
107
166
273
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/LambdaGenerator.java
LambdaGenerator
createSetterInt
class LambdaGenerator { static final AtomicInteger counter = new AtomicInteger(); public static <T> ObjIntConsumer<T> createSetterInt(Class<T> objectClass, String methodName) throws Throwable {<FILL_FUNCTION_BODY>} }
ClassWriter cw = new ClassWriter(null); final String JAVA_LANG_OBJECT = "java/lang/Object"; String[] interfaces = {"java/util/function/ObjIntConsumer"}; String lambdaClassName = "SetInt$Lambda$" + counter.incrementAndGet(); // if (JDKUtils.JVM_VERSION > 16) { // String pkgName = objectClass.getPackage().getName(); // pkgName = pkgName.replace('.', '/'); // lambdaClassName = pkgName + '/' + lambdaClassName; // } cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER, lambdaClassName, JAVA_LANG_OBJECT, interfaces); final int THIS = 0; { MethodWriter mw = cw.visitMethod( Opcodes.ACC_PUBLIC, "<init>", "()V", 64 ); mw.visitVarInsn(Opcodes.ALOAD, THIS); mw.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); mw.visitInsn(Opcodes.RETURN); mw.visitMaxs(3, 3); } MethodWriter mw = cw.visitMethod( Opcodes.ACC_PUBLIC, "accept", "(Ljava/lang/Object;I)V", 64 ); String TYPE_OBJECT = ASMUtils.type(objectClass); int OBJECT = 1, VALUE = 2; mw.visitVarInsn(Opcodes.ALOAD, OBJECT); mw.visitTypeInsn(Opcodes.CHECKCAST, TYPE_OBJECT); mw.visitVarInsn(Opcodes.ILOAD, VALUE); Class returnType = Void.TYPE; String methodDesc; if (returnType == Void.TYPE) { methodDesc = "(I)V"; } else { methodDesc = "(I)" + ASMUtils.desc(returnType); } mw.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_OBJECT, methodName, methodDesc, false); if (returnType != Void.TYPE) { mw.visitInsn(Opcodes.POP); } mw.visitInsn(Opcodes.RETURN); mw.visitMaxs(2, 2); byte[] code = cw.toByteArray(); Class functionClass = DynamicClassLoader.getInstance().defineClassPublic(lambdaClassName, code, 0, code.length); Constructor ctr = functionClass.getDeclaredConstructor(); Object inst = ctr.newInstance(); ConstantCallSite callSite = new ConstantCallSite(MethodHandles.constant(ObjIntConsumer.class, inst)); return (ObjIntConsumer<T>) callSite.getTarget().invokeExact();
70
827
897
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/LargeFile26MTest.java
LargeFile26MTest
fastjson1_perf
class LargeFile26MTest { static String str; static ObjectMapper mapper = new ObjectMapper(); static final int COUNT = 10; static { try ( InputStream fis = LargeFile26MTest.class.getClassLoader().getResourceAsStream("data/large-file.json.zip"); BufferedInputStream bis = new BufferedInputStream(fis); ZipInputStream zipIn = new ZipInputStream(bis) ) { zipIn.getNextEntry(); str = IOUtils.toString(zipIn, "UTF-8"); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void fastjson1(Blackhole bh) { bh.consume(com.alibaba.fastjson.JSON.parseObject(str, ArrayList.class)); } @Benchmark public void fastjson2(Blackhole bh) { bh.consume(JSON.parseObject(str, ArrayList.class)); } @Benchmark public void jackson(Blackhole bh) throws Exception { bh.consume(mapper.readValue(str, ArrayList.class)); } // @Test public void fastjson1_perf_test() { for (int i = 0; i < 10; i++) { fastjson1_perf(); } } // @Test public void fastjson2_perf_test() { for (int i = 0; i < 10; i++) { fastjson2_perf(); } } public void jackson_perf_test() throws Exception { for (int i = 0; i < 10; i++) { jackson_perf(); } } public static void fastjson2_perf() { long start = System.currentTimeMillis(); for (int i = 0; i < COUNT; ++i) { JSON.parseObject(str, ArrayList.class); } long millis = System.currentTimeMillis() - start; System.out.println("fastjson2 millis : " + millis); // zulu17.32.13 : 446 // zulu11.52.13 : 506 // zulu8.58.0.13 : 492 } public static void jackson_perf() throws Exception { long start = System.currentTimeMillis(); for (int i = 0; i < COUNT; ++i) { mapper.readValue(str, ArrayList.class); } long millis = System.currentTimeMillis() - start; System.out.println("jackson millis : " + millis); // zulu17.32.13 : 502 // zulu11.52.13 : 562 // zulu8.58.0.13 : 498 } public static void fastjson1_perf() {<FILL_FUNCTION_BODY>} public static void main(String[] args) throws Exception { // new LargeFileTest().fastjson2_perf_test(); // new LargeFileTest().fastjson1_perf_test(); // new LargeFileTest().jackson_perf_test(); Options options = new OptionsBuilder() .include(LargeFile26MTest.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .forks(1) .build(); new Runner(options).run(); } }
long start = System.currentTimeMillis(); for (int i = 0; i < COUNT; ++i) { com.alibaba.fastjson.JSON.parseObject(str, ArrayList.class); } long millis = System.currentTimeMillis() - start; System.out.println("fastjson1 millis : " + millis); // zulu17.32.13 : // zulu11.52.13 : // zulu8.58.0.13 : 589
935
139
1,074
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/LargeFile2MTest.java
LargeFile2MTest
perfTest
class LargeFile2MTest { static String str; static ObjectMapper mapper = new ObjectMapper(); static final int COUNT = 100; static { try ( InputStream fis = LargeFile2MTest.class.getClassLoader().getResourceAsStream("data/large-file-2m.json.zip"); BufferedInputStream bis = new BufferedInputStream(fis); ZipInputStream zipIn = new ZipInputStream(bis) ) { zipIn.getNextEntry(); str = IOUtils.toString(zipIn, "UTF-8"); zipIn.closeEntry(); } catch (IOException ex) { ex.printStackTrace(); } } @Benchmark public void fastjson1(Blackhole bh) { bh.consume(com.alibaba.fastjson.JSON.parseObject(str)); } @Benchmark public void fastjson2(Blackhole bh) { bh.consume(JSON.parseObject(str)); } @Benchmark public void jackson(Blackhole bh) throws Exception { bh.consume(mapper.readValue(str, HashMap.class)); } public void perfTest(Runnable task) {<FILL_FUNCTION_BODY>} public void fastjson1_perf_test() { perfTest(() -> com.alibaba.fastjson.JSON.parseObject(str)); } public void fastjson2_perf_test() { perfTest(() -> JSON.parseObject(str)); } public void jackson_perf_test() throws Exception { perfTest(() -> { try { mapper.readValue(str, HashMap.class); } catch (IOException e) { e.printStackTrace(); } }); } public static void main(String[] args) throws Exception { new LargeFile2MTest().fastjson2_perf_test(); // new LargeFile2MTest().fastjson1_perf_test(); // new LargeFile2MTest().jackson_perf_test(); // Options options = new OptionsBuilder() // .include(LargeFile2MTest.class.getName()) // .mode(Mode.Throughput) // .timeUnit(TimeUnit.MILLISECONDS) // .forks(1) // .build(); // new Runner(options).run(); } }
long start = System.currentTimeMillis(); for (int i = 0; i < COUNT; ++i) { task.run(); } long millis = System.currentTimeMillis() - start; System.out.println("millis : " + millis); // zulu17.32.13 : 1299 1136 // zulu11.52.13 : 1187 1145 // zulu8.58.0.13 : 1154
629
141
770
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/LargeFile3MTest.java
LargeFile3MTest
jackson_perf
class LargeFile3MTest { static String str; static ObjectMapper mapper = new ObjectMapper(); static final int COUNT = 100; static { try ( InputStream fis = LargeFile3MTest.class.getClassLoader().getResourceAsStream("data/large-file-3m.json.zip"); BufferedInputStream bis = new BufferedInputStream(fis); ZipInputStream zipIn = new ZipInputStream(bis) ) { zipIn.getNextEntry(); str = IOUtils.toString(zipIn, "UTF-8"); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void fastjson1(Blackhole bh) { bh.consume(com.alibaba.fastjson.JSON.parseObject(str)); } @Benchmark public void fastjson2(Blackhole bh) { bh.consume(JSON.parseObject(str)); } @Benchmark public void jackson(Blackhole bh) throws Exception { bh.consume(mapper.readValue(str, HashMap.class)); } // @Test public void fastjson1_perf_test() { for (int i = 0; i < 10; i++) { fastjson1_perf(); } } // @Test public void fastjson2_perf_test() { for (int i = 0; i < 10; i++) { fastjson2_perf(); } } public void jackson_perf_test() throws Exception { for (int i = 0; i < 10; i++) { jackson_perf(); } } public static void fastjson2_perf() { long start = System.currentTimeMillis(); for (int i = 0; i < COUNT; ++i) { JSON.parseObject(str); } long millis = System.currentTimeMillis() - start; System.out.println("fastjson2 millis : " + millis); // zulu17.32.13 : 557 // zulu11.52.13 : 658 // zulu8.58.0.13 : 536 } public static void jackson_perf() throws Exception {<FILL_FUNCTION_BODY>} public static void fastjson1_perf() { long start = System.currentTimeMillis(); for (int i = 0; i < COUNT; ++i) { com.alibaba.fastjson.JSON.parseObject(str); } long millis = System.currentTimeMillis() - start; System.out.println("fastjson1 millis : " + millis); // zulu17.32.13 : // zulu11.52.13 : // zulu8.58.0.13 : 589 } public static void main(String[] args) throws Exception { // new LargeFile3MTest().fastjson2_perf_test(); // new LargeFile3MTest().fastjson1_perf_test(); // new LargeFile3MTest().jackson_perf_test(); Options options = new OptionsBuilder() .include(LargeFile3MTest.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .forks(1) .build(); new Runner(options).run(); } }
long start = System.currentTimeMillis(); for (int i = 0; i < COUNT; ++i) { mapper.readValue(str, HashMap.class); } long millis = System.currentTimeMillis() - start; System.out.println("jackson millis : " + millis); // zulu17.32.13 : // zulu11.52.13 : // zulu8.58.0.13 :
928
127
1,055
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/Name8.java
Name8
main
class Name8 { static String str; static final ObjectMapper mapper = new ObjectMapper(); static final Gson gson = new Gson(); static { try { InputStream is = EishayParseTreeString.class.getClassLoader().getResourceAsStream("data/name8.json"); str = IOUtils.toString(is, "UTF-8"); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void fastjson1(Blackhole bh) { bh.consume(com.alibaba.fastjson.JSON.parseObject(str)); } @Benchmark public void fastjson2(Blackhole bh) { bh.consume(JSON.parseObject(str)); } @Benchmark public void jackson(Blackhole bh) throws Exception { bh.consume(mapper.readValue(str, HashMap.class)); } // @Benchmark public void wastjson(Blackhole bh) throws Exception { bh.consume( io.github.wycst.wast.json.JSON.parse(str) ); } @Benchmark public void gson(Blackhole bh) throws Exception { bh.consume( gson.fromJson(str, HashMap.class) ); } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(EishayParseTreeString.class.getName()) .exclude(EishayParseTreeStringPretty.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run();
392
115
507
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/SpaceCheckBenchmark.java
SpaceCheckBenchmark
spaceOr
class SpaceCheckBenchmark { static String str; static char[] chars; static final long SPACE = (1L << ' ') | (1L << '\n') | (1L << '\r') | (1L << '\f') | (1L << '\t') | (1L << '\b'); static { try { InputStream is = EishayParseStringPretty.class.getClassLoader().getResourceAsStream("data/eishay.json"); str = IOUtils.toString(is, "UTF-8"); chars = str.toCharArray(); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void spaceBitAnd(Blackhole bh) { int spaceCount = 0; for (int i = 0; i < chars.length; i++) { char ch = chars[i]; boolean space = ch <= ' ' && ((1L << ch) & SPACE) != 0; if (space) { spaceCount++; } } bh.consume(spaceCount); } @Benchmark public void spaceOr(Blackhole bh) {<FILL_FUNCTION_BODY>} @Benchmark public void spaceOrPreCheck(Blackhole bh) { int spaceCount = 0; for (int i = 0; i < chars.length; i++) { char ch = chars[i]; boolean space = ch <= ' ' && (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\f' || ch == '\t' || ch == '\b' ); if (space) { spaceCount++; } } bh.consume(spaceCount); } @Benchmark public void CharacterIsWhitespace(Blackhole bh) { int spaceCount = 0; for (int i = 0; i < chars.length; i++) { char ch = chars[i]; boolean space = Character.isWhitespace(ch); if (space) { spaceCount++; } } bh.consume(spaceCount); } @Benchmark public void spaceSwitch(Blackhole bh) { int spaceCount = 0; for (int i = 0; i < chars.length; i++) { char ch = chars[i]; boolean space; switch (ch) { case ' ': case '\n': case '\r': case '\t': case '\b': case '\f': space = true; break; default: space = false; break; } if (space) { spaceCount++; } } bh.consume(spaceCount); } public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() .include(SpaceCheckBenchmark.class.getName()) .mode(Mode.Throughput) .warmupIterations(1) .timeUnit(TimeUnit.MILLISECONDS) .forks(1) .build(); new Runner(options).run(); } }
int spaceCount = 0; for (int i = 0; i < chars.length; i++) { char ch = chars[i]; boolean space = ch == ' ' || ch == '\n' || ch == '\r' || ch == '\f' || ch == '\t' || ch == '\b'; if (space) { spaceCount++; } } bh.consume(spaceCount);
848
120
968
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/SpaceCheckWorestBenchmark.java
SpaceCheckWorestBenchmark
CharacterIsWhitespace
class SpaceCheckWorestBenchmark { static char[] chars; static final long SPACE = (1L << ' ') | (1L << '\n') | (1L << '\r') | (1L << '\f') | (1L << '\t') | (1L << '\b'); static { chars = new char[1024]; Arrays.fill(chars, '\b'); } @Benchmark public void spaceBitAnd(Blackhole bh) { int spaceCount = 0; for (int i = 0; i < chars.length; i++) { char ch = chars[i]; boolean space = ch <= ' ' && ((1L << ch) & SPACE) != 0; if (space) { spaceCount++; } } bh.consume(spaceCount); } @Benchmark public void spaceOr(Blackhole bh) { int spaceCount = 0; for (int i = 0; i < chars.length; i++) { char ch = chars[i]; boolean space = ch == ' ' || ch == '\n' || ch == '\r' || ch == '\f' || ch == '\t' || ch == '\b'; if (space) { spaceCount++; } } bh.consume(spaceCount); } @Benchmark public void spaceOrPreCheck(Blackhole bh) { int spaceCount = 0; for (int i = 0; i < chars.length; i++) { char ch = chars[i]; boolean space = ch <= ' ' && (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\f' || ch == '\t' || ch == '\b' ); if (space) { spaceCount++; } } bh.consume(spaceCount); } @Benchmark public void spaceSwitch(Blackhole bh) { int spaceCount = 0; for (int i = 0; i < chars.length; i++) { char ch = chars[i]; boolean space; switch (ch) { case ' ': case '\n': case '\r': case '\t': case '\b': case '\f': space = true; break; default: space = false; break; } if (space) { spaceCount++; } } bh.consume(spaceCount); } @Benchmark public void CharacterIsWhitespace(Blackhole bh) {<FILL_FUNCTION_BODY>} public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() .include(SpaceCheckWorestBenchmark.class.getName()) .mode(Mode.Throughput) .warmupIterations(1) .timeUnit(TimeUnit.MILLISECONDS) .forks(1) .build(); new Runner(options).run(); } }
int spaceCount = 0; for (int i = 0; i < chars.length; i++) { char ch = chars[i]; boolean space = Character.isWhitespace(ch); if (space) { spaceCount++; } } bh.consume(spaceCount);
824
85
909
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/StringCreateBenchmark.java
StringCreateBenchmark
getStringCreator
class StringCreateBenchmark { static final BiFunction<char[], Boolean, String> STRING_CREATOR = getStringCreator(); static final char[] chars = new char[128]; static long valueOffset; static { try { Field field = String.class.getDeclaredField("value"); field.setAccessible(true); valueOffset = UNSAFE.objectFieldOffset(field); } catch (NoSuchFieldException e) { e.printStackTrace(); } } public static BiFunction<char[], Boolean, String> getStringCreator() {<FILL_FUNCTION_BODY>} @Benchmark public String creator() { return STRING_CREATOR.apply(chars, Boolean.TRUE); } @Benchmark public String newString() { return new String(chars); } @Benchmark public String unsafe() throws Exception { String str = (String) UNSAFE.allocateInstance(String.class); UNSAFE.putObject(str, valueOffset, chars); return str; } public void creator_benchmark() { long start = System.currentTimeMillis(); for (int i = 0; i < 1000_000_000; i++) { creator(); } long millis = System.currentTimeMillis() - start; System.out.println("creator : " + millis); } public void new_benchmark() throws Exception { long start = System.currentTimeMillis(); for (int i = 0; i < 1000_000; i++) { unsafe(); } long millis = System.currentTimeMillis() - start; System.out.println("new : " + millis); } // @Test public void test_benchmark() throws Exception { for (int i = 0; i < 10; i++) { new_benchmark(); } } public static void main(String[] args) throws RunnerException { Options options = new OptionsBuilder() .include(StringCreateBenchmark.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .forks(1) .build(); new Runner(options).run(); } }
try { MethodHandles.Lookup caller = MethodHandles.lookup().in(String.class); Field modes = MethodHandles.Lookup.class.getDeclaredField("allowedModes"); modes.setAccessible(true); modes.setInt(caller, -1); // -1 == Lookup.TRUSTED // create handle for shared String constructor MethodHandle handle = caller.findConstructor( String.class, MethodType.methodType(void.class, char[].class, boolean.class) ); CallSite callSite = LambdaMetafactory.metafactory( caller, "apply", MethodType.methodType(BiFunction.class), handle.type().generic(), handle, handle.type() ); return (BiFunction) callSite.getTarget().invokeExact(); } catch (Throwable e) { throw new RuntimeException(e); }
623
238
861
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/StringGetValueBenchmark.java
StringGetValueBenchmark
reflect
class StringGetValueBenchmark { static String STR = "01234567890ABCDEFGHIJKLMNOPQRSTUVWZYZabcdefghijklmnopqrstuvwzyz一二三四五六七八九十"; static final char[] chars = new char[128]; static Field valueField; static long valueFieldOffset; static { try { valueField = String.class.getDeclaredField("value"); valueField.setAccessible(true); valueFieldOffset = UNSAFE.objectFieldOffset(valueField); } catch (NoSuchFieldException e) { e.printStackTrace(); } } // // @Benchmark // public void charAt() { // for (int i = 0; i < STR.length(); ++i) { // char ch = STR.charAt(i); // } // } // // @Benchmark // public void toCharArray() throws Exception { // char[] chars = STR.toCharArray(); // for (int i = 0; i < chars.length; i++) { // char ch = chars[i]; // } // } @Benchmark public char[] reflect() throws Exception {<FILL_FUNCTION_BODY>} @Benchmark public char[] unsafe() throws Exception { return (char[]) UNSAFE.getObject(STR, valueFieldOffset); // for (int i = 0; i < chars.length; i++) { // char ch = chars[i]; // } } public static void main(String[] args) throws RunnerException { Options options = new OptionsBuilder() .include(StringGetValueBenchmark.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .forks(1) .build(); new Runner(options).run(); } }
return (char[]) valueField.get(STR); // for (int i = 0; i < chars.length; i++) { // char ch = chars[i]; // }
520
53
573
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/TaobaoH5ApiTree.java
TaobaoH5ApiTree
main
class TaobaoH5ApiTree { static String str; static ObjectMapper mapper = new ObjectMapper(); public TaobaoH5ApiTree() { try { InputStream is = TaobaoH5ApiTree.class.getClassLoader().getResourceAsStream("data/taobao_h5api.json"); str = IOUtils.toString(is, "UTF-8"); } catch (Exception ex) { ex.printStackTrace(); } } @Benchmark public void fastjson1(Blackhole bh) { bh.consume( com.alibaba.fastjson.JSON.parseObject(str, Map.class) ); } @Benchmark public void fastjson2(Blackhole bh) { bh.consume( JSON.parseObject(str) ); } @Benchmark public void jackson(Blackhole bh) throws Exception { bh.consume( mapper.readValue(str, Map.class) ); } @Benchmark public void wastjson(Blackhole bh) throws Exception { bh.consume( io.github.wycst.wast.json.JSON.parseObject(str, Map.class) ); } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(TaobaoH5ApiTree.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .build(); new Runner(options).run();
366
89
455
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/along/AlongParseBinaryArrayMapping.java
AlongParseBinaryArrayMapping
main
class AlongParseBinaryArrayMapping { static Fury fury; static SkillFire_S2C_Msg object; static byte[] fastjson2JSONBBytes; static byte[] furyBytes; static { try { InputStream is = AlongParseBinaryArrayMapping.class.getClassLoader().getResourceAsStream("data/along.json"); String str = IOUtils.toString(is, "UTF-8"); object = JSONReader.of(str).read(SkillFire_S2C_Msg.class); fury = Fury.builder().withLanguage(Language.JAVA) .withRefTracking(false) .requireClassRegistration(false) .withNumberCompressed(true) .build(); fury.register(SkillCategory.class); fury.register(SkillFire_S2C_Msg.class); fury.register(HarmDTO.class); fastjson2JSONBBytes = JSONB.toBytes(object, JSONWriter.Feature.BeanToArray); furyBytes = fury.serializeJavaObject(object); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void jsonb(Blackhole bh) { bh.consume(JSONB.parseObject(fastjson2JSONBBytes, SkillFire_S2C_Msg.class, FieldBased, SupportArrayToBean)); } @Benchmark public void fury(Blackhole bh) { bh.consume(fury.deserializeJavaObject(furyBytes, SkillFire_S2C_Msg.class)); } public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(AlongParseBinaryArrayMapping.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run();
450
96
546
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/along/AlongWriteBinaryArrayMapping.java
AlongWriteBinaryArrayMapping
main
class AlongWriteBinaryArrayMapping { static SkillFire_S2C_Msg object; static Fury fury; static { try { InputStream is = AlongWriteBinaryArrayMapping.class.getClassLoader().getResourceAsStream("data/along.json"); String str = IOUtils.toString(is, "UTF-8"); object = JSONReader.of(str) .read(SkillFire_S2C_Msg.class); fury = Fury.builder() .withLanguage(Language.JAVA) .withRefTracking(false) .requireClassRegistration(false) .withNumberCompressed(true) .build(); } catch (Throwable ex) { ex.printStackTrace(); } } public int jsonbSize() { return JSONB.toBytes(object, JSONWriter.Feature.BeanToArray).length; } @Benchmark public void jsonb(Blackhole bh) { bh.consume(JSONB.toBytes(object, JSONWriter.Feature.BeanToArray, JSONWriter.Feature.FieldBased)); } @Benchmark public void fury(Blackhole bh) { bh.consume(fury.serialize(object)); } public int furySize() { return fury.serialize(object).length; } // @Benchmark public void json(Blackhole bh) { bh.consume(JSON.toJSONBytes(object, JSONWriter.Feature.BeanToArray, JSONWriter.Feature.FieldBased)); } // @Benchmark public void jsonStr(Blackhole bh) { bh.consume(JSON.toJSONString(object, JSONWriter.Feature.BeanToArray, JSONWriter.Feature.FieldBased)); } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(AlongWriteBinaryArrayMapping.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run();
495
96
591
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/Eishay.java
Eishay
main
class Eishay { public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(Eishay.class.getName()) .include(EishayFuryCompatibleParse.class.getName()) .include(EishayFuryCompatibleWrite.class.getName()) .exclude(EishayParseStringNoneCache.class.getName()) .exclude(EishayWriteStringNoneCache.class.getName()) .exclude(EishayWriteStringTree1x.class.getName()) .exclude(EishayFuryParse.class.getName()) .exclude(EishayFuryWrite.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run();
36
218
254
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayFury.java
EishayFury
main
class EishayFury { public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(EishayFury.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run();
36
95
131
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayFuryCompatibleParse.java
EishayFuryCompatibleParse
main
class EishayFuryCompatibleParse { static MediaContent mc; static JSONReader.Feature[] features = { JSONReader.Feature.SupportAutoType, JSONReader.Feature.IgnoreNoneSerializable, JSONReader.Feature.UseDefaultConstructorAsPossible, JSONReader.Feature.UseNativeObject, JSONReader.Feature.FieldBased }; static JSONReader.Context context = new JSONReader.Context( JSONFactory.getDefaultObjectReaderProvider(), features ); static byte[] jsonbBytes; static byte[] furyCompatibleBytes; static io.fury.ThreadSafeFury furyCompatible = io.fury.Fury.builder() .withLanguage(io.fury.config.Language.JAVA) .withRefTracking(true) .requireClassRegistration(false) .withCompatibleMode(io.fury.config.CompatibleMode.COMPATIBLE) .buildThreadSafeFury(); static { try { InputStream is = EishayFuryCompatibleParse.class.getClassLoader().getResourceAsStream("data/eishay.json"); String str = IOUtils.toString(is, "UTF-8"); mc = JSONReader.of(str) .read(MediaContent.class); jsonbBytes = JSONB.toBytes(mc, EishayFuryCompatibleWrite.features); furyCompatibleBytes = furyCompatible.serialize(mc); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void jsonb(Blackhole bh) { Object object = JSONB.parseObject(jsonbBytes, Object.class, context); bh.consume(object); } @Benchmark public void fury(Blackhole bh) { Object object = furyCompatible.deserialize(furyCompatibleBytes); bh.consume(object); } public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(EishayFuryCompatibleParse.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run();
528
98
626
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayFuryCompatibleWrite.java
EishayFuryCompatibleWrite
main
class EishayFuryCompatibleWrite { static MediaContent mc; static JSONWriter.Feature[] features = { JSONWriter.Feature.WriteClassName, JSONWriter.Feature.IgnoreNoneSerializable, JSONWriter.Feature.FieldBased, JSONWriter.Feature.ReferenceDetection, JSONWriter.Feature.WriteNulls, JSONWriter.Feature.NotWriteDefaultValue, JSONWriter.Feature.NotWriteHashMapArrayListClassName }; static JSONWriter.Context context = new JSONWriter.Context( JSONFactory.getDefaultObjectWriterProvider(), features ); static ThreadSafeFury furyCompatible = Fury.builder() .withLanguage(io.fury.config.Language.JAVA) .withRefTracking(true) .requireClassRegistration(false) .withCompatibleMode(io.fury.config.CompatibleMode.COMPATIBLE) .buildThreadSafeFury(); static { try { InputStream is = EishayFuryCompatibleWrite.class.getClassLoader().getResourceAsStream("data/eishay.json"); String str = IOUtils.toString(is, "UTF-8"); mc = JSONReader.of(str) .read(MediaContent.class); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void jsonb(Blackhole bh) { byte[] bytes = JSONB.toBytes(mc, context); bh.consume(bytes); } public int jsonbSize() { return JSONB.toBytes(mc, context).length; } @Benchmark public void fury(Blackhole bh) { byte[] bytes = furyCompatible.serialize(mc); bh.consume(bytes); } public int furySize() { // return furyCompatible.serialize(mc).length; return 0; } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(EishayFuryCompatibleWrite.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run();
533
98
631
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayFuryParse.java
EishayFuryParse
main
class EishayFuryParse { static MediaContent mc; static JSONReader.Feature[] features = { JSONReader.Feature.SupportAutoType, JSONReader.Feature.IgnoreNoneSerializable, JSONReader.Feature.UseDefaultConstructorAsPossible, JSONReader.Feature.UseNativeObject, JSONReader.Feature.FieldBased, JSONReader.Feature.SupportArrayToBean }; static byte[] jsonbBytes; static byte[] furyBytes; static io.fury.ThreadSafeFury fury = io.fury.Fury.builder() .withLanguage(io.fury.config.Language.JAVA) .requireClassRegistration(false) .withRefTracking(true) .buildThreadSafeFury(); static { try { InputStream is = EishayFuryParse.class.getClassLoader().getResourceAsStream("data/eishay.json"); String str = IOUtils.toString(is, "UTF-8"); mc = JSONReader.of(str) .read(MediaContent.class); jsonbBytes = JSONB.toBytes( mc, EishayFuryWrite.features ); furyBytes = fury.serializeJavaObject(mc); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void jsonb(Blackhole bh) { Object object = JSONB.parseObject(jsonbBytes, Object.class, features); bh.consume(object); } @Benchmark public void fury(Blackhole bh) { Object object = fury.deserialize(furyBytes); bh.consume(object); } public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(EishayFuryParse.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run();
477
96
573
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayFuryParseNoneCache.java
EishayFuryParseNoneCache
fastjson2JSONB
class EishayFuryParseNoneCache { static final int COUNT = 10_000; static final Class[] classes = new Class[COUNT]; static JSONReader.Feature[] features = { JSONReader.Feature.SupportAutoType, JSONReader.Feature.IgnoreNoneSerializable, JSONReader.Feature.UseDefaultConstructorAsPossible, JSONReader.Feature.UseNativeObject, JSONReader.Feature.FieldBased, JSONReader.Feature.SupportArrayToBean }; static DynamicClassLoader classLoader = DynamicClassLoader.getInstance(); static byte[][] fastjson2JSONBBytes = new byte[COUNT][]; static byte[][] furyBytes = new byte[COUNT][]; static int index; static io.fury.ThreadSafeFury fury = io.fury.Fury.builder() .withLanguage(io.fury.config.Language.JAVA) .withRefTracking(true) .withClassLoader(classLoader) .buildThreadSafeFury(); static { String classZipDataFile = "data/EishayFuryParseNoneCache_classes.bin.zip"; String jsonbZipDataFile = "data/EishayFuryParseNoneCache_data_fastjson.bin.zip"; String furyZipDataFile = "data/EishayFuryParseNoneCache_data_fury.bin.zip"; try { { InputStream fis = EishayFuryParseNoneCache.class.getClassLoader().getResourceAsStream(classZipDataFile); ZipInputStream zipIn = new ZipInputStream(fis); zipIn.getNextEntry(); ObjectInputStream is = new ObjectInputStream(zipIn); Map<String, byte[]> codeMap = (Map<String, byte[]>) is.readObject(); Map<String, Class> classMap = new HashMap<>(codeMap.size()); String prefix = "com.alibaba.fastjson2.benchmark.eishay"; codeMap.forEach((name, code) -> { int index = Integer.parseInt(name.substring(prefix.length(), name.indexOf('.', prefix.length()))); if (index > COUNT) { return; } Class<?> clazz = classLoader.loadClass(name, code, 0, code.length); classMap.put(name, clazz); }); for (int i = 0; i < COUNT; i++) { String packageName = prefix + i; classLoader.definePackage(packageName); String className = packageName + ".MediaContent"; Class mediaClass = classMap.get(className); classes[i] = mediaClass; } IOUtils.close(zipIn); IOUtils.close(is); IOUtils.close(fis); } { InputStream fis = EishayFuryParseNoneCache.class.getClassLoader().getResourceAsStream(jsonbZipDataFile); ZipInputStream zipIn = new ZipInputStream(fis); zipIn.getNextEntry(); ObjectInputStream is = new ObjectInputStream(zipIn); fastjson2JSONBBytes = (byte[][]) is.readObject(); IOUtils.close(zipIn); IOUtils.close(is); IOUtils.close(fis); } { InputStream fis = EishayFuryParseNoneCache.class.getClassLoader().getResourceAsStream(furyZipDataFile); ZipInputStream zipIn = new ZipInputStream(fis); zipIn.getNextEntry(); ObjectInputStream is = new ObjectInputStream(zipIn); furyBytes = (byte[][]) is.readObject(); IOUtils.close(zipIn); IOUtils.close(is); IOUtils.close(fis); } } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void fastjson2JSONB(Blackhole bh) {<FILL_FUNCTION_BODY>} @Benchmark public void fury(Blackhole bh) { Thread.currentThread().setContextClassLoader(classLoader); byte[] bytes = furyBytes[index++]; bh.consume(fury.deserialize(bytes)); } public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() .include(EishayFuryParseNoneCache.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(1) .forks(1) .threads(16) .build(); new Runner(options).run(); } }
Thread.currentThread().setContextClassLoader(classLoader); byte[] bytes = fastjson2JSONBBytes[index++]; bh.consume( JSONB.parseObject(bytes, Object.class, features) );
1,200
61
1,261
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayFuryWrite.java
EishayFuryWrite
main
class EishayFuryWrite { static MediaContent object; static io.fury.ThreadSafeFury fury = io.fury.Fury.builder() .withLanguage(io.fury.config.Language.JAVA) .requireClassRegistration(false) .withRefTracking(true) .buildThreadSafeFury(); static JSONWriter.Feature[] features = { JSONWriter.Feature.WriteClassName, JSONWriter.Feature.IgnoreNoneSerializable, JSONWriter.Feature.FieldBased, JSONWriter.Feature.ReferenceDetection, JSONWriter.Feature.WriteNulls, JSONWriter.Feature.NotWriteDefaultValue, JSONWriter.Feature.NotWriteHashMapArrayListClassName, JSONWriter.Feature.BeanToArray }; static JSONWriter.Context context = new JSONWriter.Context( JSONFactory.getDefaultObjectWriterProvider(), features ); static { try { InputStream is = EishayFuryWrite.class.getClassLoader().getResourceAsStream("data/eishay.json"); String str = IOUtils.toString(is, "UTF-8"); object = JSONReader.of(str) .read(MediaContent.class); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void jsonb(Blackhole bh) { byte[] bytes = JSONB.toBytes(object, context); bh.consume(bytes); } @Benchmark public void fury(Blackhole bh) { byte[] bytes = fury.serialize(object); bh.consume(bytes); } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(EishayFuryWrite.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run();
457
96
553
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayFuryWriteNoneCache.java
EishayFuryWriteNoneCache
fury
class EishayFuryWriteNoneCache { static final Class[] classes = new Class[10_000]; static final Object[] objects = new Object[classes.length]; static int index; static io.fury.ThreadSafeFury fury = io.fury.Fury.builder() .withLanguage(io.fury.config.Language.JAVA) .withRefTracking(true) .buildThreadSafeFury(); static JSONWriter.Feature[] features = { JSONWriter.Feature.WriteClassName, JSONWriter.Feature.IgnoreNoneSerializable, JSONWriter.Feature.FieldBased, JSONWriter.Feature.ReferenceDetection, JSONWriter.Feature.WriteNulls, JSONWriter.Feature.NotWriteDefaultValue, JSONWriter.Feature.NotWriteHashMapArrayListClassName, JSONWriter.Feature.BeanToArray }; static JSONWriter.Context context = new JSONWriter.Context( JSONFactory.getDefaultObjectWriterProvider(), features ); static { try { InputStream is = EishayFuryWriteNoneCache.class.getClassLoader().getResourceAsStream("data/eishay.json"); String str = IOUtils.toString(is, "UTF-8"); DynamicClassLoader classLoader = DynamicClassLoader.getInstance(); EishayClassGen gen = new EishayClassGen(); for (int i = 0; i < classes.length; i++) { Class objectClass = gen.genMedia(classLoader, "com/alibaba/fastjson2/benchmark/eishay" + i); classes[i] = objectClass; objects[i] = JSONReader.of(str).read(objectClass); } } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void fastjson2JSONB(Blackhole bh) { Object object = objects[(index++) % objects.length]; bh.consume( JSONB.toBytes(object, context) ); } @Benchmark public void fury(Blackhole bh) {<FILL_FUNCTION_BODY>} public static void main(String[] args) throws RunnerException { Options options = new OptionsBuilder() .include(EishayFuryWriteNoneCache.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run(); } }
Object object = objects[(index++) % objects.length]; byte[] bytes = fury.serialize(object); bh.consume(bytes);
667
42
709
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayParse.java
EishayParse
main
class EishayParse { public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(EishayParse.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run();
37
94
131
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayParseBinary.java
EishayParseBinary
jsonbValid
class EishayParseBinary { static MediaContent mc; static byte[] fastjson2UTF8Bytes; static byte[] fastjson2JSONBBytes; static byte[] hessianBytes; static byte[] javaSerializeBytes; private static final ThreadLocal<Kryo> kryos = new ThreadLocal<Kryo>() { protected Kryo initialValue() { Kryo kryo = new Kryo(); kryo.register(MediaContent.class); kryo.register(ArrayList.class); kryo.register(Image.class); kryo.register(Image.Size.class); kryo.register(Media.class); kryo.register(Media.Player.class); return kryo; } }; static byte[] kryoBytes; static { try { InputStream is = EishayParseBinary.class.getClassLoader().getResourceAsStream("data/eishay.json"); String str = IOUtils.toString(is, "UTF-8"); mc = JSONReader.of(str) .read(MediaContent.class); fastjson2UTF8Bytes = JSON.toJSONBytes(mc); fastjson2JSONBBytes = JSONB.toBytes(mc); { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Hessian2Output hessian2Output = new Hessian2Output(byteArrayOutputStream); hessian2Output.writeObject(mc); hessian2Output.flush(); hessianBytes = byteArrayOutputStream.toByteArray(); } { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(mc); objectOutputStream.flush(); javaSerializeBytes = byteArrayOutputStream.toByteArray(); } Kryo kryo = new Kryo(); kryo.register(MediaContent.class); kryo.register(ArrayList.class); kryo.register(Image.class); kryo.register(Image.Size.class); kryo.register(Media.class); kryo.register(Media.Player.class); Output output = new Output(1024, -1); kryo.writeObject(output, mc); kryoBytes = output.toBytes(); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void fastjson2UTF8Bytes(Blackhole bh) { bh.consume( JSON.parseObject(fastjson2UTF8Bytes, MediaContent.class) ); } @Benchmark public void jsonb(Blackhole bh) { bh.consume( JSONB.parseObject(fastjson2JSONBBytes, MediaContent.class) ); } // @Benchmark public void jsonbValid(Blackhole bh) {<FILL_FUNCTION_BODY>} @Benchmark public void javaSerialize(Blackhole bh) throws Exception { ByteArrayInputStream bytesIn = new ByteArrayInputStream(javaSerializeBytes); ObjectInputStream objectIn = new ObjectInputStream(bytesIn); bh.consume(objectIn.readObject()); } @Benchmark public void hessian(Blackhole bh) throws Exception { ByteArrayInputStream bytesIn = new ByteArrayInputStream(hessianBytes); Hessian2Input hessian2Input = new Hessian2Input(bytesIn); bh.consume(hessian2Input.readObject()); } public void kryo(Blackhole bh) throws Exception { Input input = new Input(kryoBytes); MediaContent object = kryos.get().readObject(input, MediaContent.class); bh.consume(object); } public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() .include(EishayParseBinary.class.getName()) .exclude(EishayParseBinaryAutoType.class.getName()) .exclude(EishayParseBinaryArrayMapping.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run(); } }
JSONReader jsonReader = JSONReader.ofJSONB(fastjson2JSONBBytes); jsonReader.skipValue(); bh.consume( jsonReader.isEnd() ); jsonReader.close();
1,147
58
1,205
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayParseBinaryArrayMapping.java
EishayParseBinaryArrayMapping
main
class EishayParseBinaryArrayMapping { static final Fury fury = Fury.builder().withLanguage(Language.JAVA) .withRefTracking(false) .requireClassRegistration(false) .withNumberCompressed(true) .build(); static MediaContent mediaContent; static byte[] fastjson2JSONBBytes; static byte[] kryoBytes; static byte[] protobufBytes; static byte[] furyBytes; private static final ThreadLocal<Kryo> kryos = ThreadLocal.withInitial(() -> { Kryo kryo = new Kryo(); kryo.register(MediaContent.class); kryo.register(ArrayList.class); kryo.register(Image.class); kryo.register(Image.Size.class); kryo.register(Media.class); kryo.register(Media.Player.class); return kryo; }); static { try { InputStream is = EishayParseBinaryArrayMapping.class.getClassLoader().getResourceAsStream("data/eishay.json"); String str = IOUtils.toString(is, "UTF-8"); mediaContent = JSONReader.of(str) .read(MediaContent.class); fastjson2JSONBBytes = JSONB.toBytes(mediaContent, JSONWriter.Feature.BeanToArray); Kryo kryo = new Kryo(); kryo.register(MediaContent.class); kryo.register(ArrayList.class); kryo.register(Image.class); kryo.register(Image.Size.class); kryo.register(Media.class); kryo.register(Media.Player.class); Output output = new Output(1024, -1); kryo.writeObject(output, mediaContent); kryoBytes = output.toBytes(); protobufBytes = MediaContentTransform.forward(mediaContent).toByteArray(); furyBytes = MediaContentTransform.forward(mediaContent).toByteArray(); } catch (Throwable ex) { ex.printStackTrace(); } } // @Benchmark public void fury(Blackhole bh) { bh.consume( fury.deserializeJavaObject(furyBytes, MediaContent.class) ); } @Benchmark public void jsonb(Blackhole bh) { bh.consume( JSONB.parseObject(fastjson2JSONBBytes, MediaContent.class, JSONReader.Feature.SupportArrayToBean) ); } @Benchmark public void protobuf(Blackhole bh) throws Exception { MediaContentHolder.MediaContent protobufObject = MediaContentHolder.MediaContent.parseFrom(protobufBytes); MediaContent object = MediaContentTransform.reverse(protobufObject); bh.consume(object); } @Benchmark public void kryo(Blackhole bh) throws Exception { Input input = new Input(kryoBytes); bh.consume( kryos.get().readObject(input, MediaContent.class) ); } public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(EishayParseBinaryArrayMapping.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run();
844
97
941
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayParseBinaryAutoType.java
EishayParseBinaryAutoType
javaSerialize
class EishayParseBinaryAutoType { static final SymbolTable symbolTable = JSONB.symbolTable( "com.alibaba.fastjson2.benchmark.eishay.vo.MediaContent", "media", "images", "height", "size", "title", "uri", "width", "bitrate", "duration", "format", "persons", "player" ); static MediaContent mc; static byte[] fastjson2JSONBBytes; static byte[] fastjson2JSONBBytes_arrayMapping; static byte[] fastjson2JSONBBytes_symbols; static byte[] hessianBytes; static byte[] javaSerializeBytes; static JSONReader.AutoTypeBeforeHandler autoTypeFilter = JSONReader.autoTypeFilter(true, Media.class, MediaContent.class, Image.class); static { try { InputStream is = EishayParseBinaryAutoType.class.getClassLoader().getResourceAsStream("data/eishay.json"); String str = IOUtils.toString(is, "UTF-8"); mc = JSONReader.of(str) .read(MediaContent.class); fastjson2JSONBBytes = JSONB.toBytes(mc, JSONWriter.Feature.WriteClassName, JSONWriter.Feature.IgnoreNoneSerializable, JSONWriter.Feature.FieldBased, JSONWriter.Feature.ReferenceDetection, JSONWriter.Feature.WriteNulls, JSONWriter.Feature.NotWriteDefaultValue, JSONWriter.Feature.NotWriteHashMapArrayListClassName, JSONWriter.Feature.WriteNameAsSymbol); fastjson2JSONBBytes_arrayMapping = JSONB.toBytes(mc, JSONWriter.Feature.WriteClassName, JSONWriter.Feature.IgnoreNoneSerializable, JSONWriter.Feature.FieldBased, JSONWriter.Feature.ReferenceDetection, JSONWriter.Feature.WriteNulls, JSONWriter.Feature.NotWriteDefaultValue, JSONWriter.Feature.NotWriteHashMapArrayListClassName, JSONWriter.Feature.BeanToArray ); fastjson2JSONBBytes_symbols = JSONB.toBytes( mc, symbolTable, JSONWriter.Feature.WriteClassName, JSONWriter.Feature.IgnoreNoneSerializable, JSONWriter.Feature.FieldBased, JSONWriter.Feature.ReferenceDetection, JSONWriter.Feature.WriteNulls, JSONWriter.Feature.NotWriteDefaultValue, JSONWriter.Feature.NotWriteHashMapArrayListClassName, JSONWriter.Feature.WriteNameAsSymbol ); { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Hessian2Output hessian2Output = new Hessian2Output(byteArrayOutputStream); hessian2Output.writeObject(mc); hessian2Output.flush(); hessianBytes = byteArrayOutputStream.toByteArray(); } { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(mc); objectOutputStream.flush(); javaSerializeBytes = byteArrayOutputStream.toByteArray(); } } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void fastjson2JSONB(Blackhole bh) { bh.consume( JSONB.parseObject( fastjson2JSONBBytes, Object.class, JSONReader.Feature.SupportAutoType, JSONReader.Feature.IgnoreNoneSerializable, JSONReader.Feature.UseDefaultConstructorAsPossible, JSONReader.Feature.UseNativeObject, JSONReader.Feature.FieldBased) ); } // @Benchmark public void fastjson2JSONB_autoTypeFilter(Blackhole bh) { bh.consume( JSONB.parseObject( fastjson2JSONBBytes, Object.class, autoTypeFilter, JSONReader.Feature.IgnoreNoneSerializable, JSONReader.Feature.UseDefaultConstructorAsPossible, JSONReader.Feature.UseNativeObject, JSONReader.Feature.FieldBased) ); } public void fastjson2JSONB_symbols(Blackhole bh) { bh.consume( JSONB.parseObject( fastjson2JSONBBytes_symbols, Object.class, symbolTable, JSONReader.Feature.SupportAutoType, JSONReader.Feature.IgnoreNoneSerializable, JSONReader.Feature.UseDefaultConstructorAsPossible, JSONReader.Feature.UseNativeObject, JSONReader.Feature.FieldBased) ); } @Benchmark public void javaSerialize(Blackhole bh) throws Exception {<FILL_FUNCTION_BODY>} @Benchmark public void hessian(Blackhole bh) throws Exception { ByteArrayInputStream bytesIn = new ByteArrayInputStream(hessianBytes); Hessian2Input hessian2Input = new Hessian2Input(bytesIn); bh.consume(hessian2Input.readObject()); } public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() .include(EishayParseBinaryAutoType.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run(); } }
ByteArrayInputStream bytesIn = new ByteArrayInputStream(javaSerializeBytes); ObjectInputStream objectIn = new ObjectInputStream(bytesIn); bh.consume(objectIn.readObject());
1,419
49
1,468
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayParseString.java
EishayParseString
main
class EishayParseString { static String str; static final ObjectMapper mapper = new ObjectMapper(); static final Gson gson = new Gson(); static final ObjectReaderProvider provider = new ObjectReaderProvider(); static { try { InputStream is = EishayParseString.class.getClassLoader().getResourceAsStream("data/eishay_compact.json"); str = IOUtils.toString(is, "UTF-8"); JSON.parseObject(str, MediaContent.class); provider.register(MediaContent.class, MediaContentMixin.objectReader); provider.register(Image.class, ImageMixin.objectReader); provider.register(Media.class, MediaMixin.objectReader); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void fastjson1(Blackhole bh) { bh.consume(com.alibaba.fastjson.JSON.parseObject(str, MediaContent.class)); } @Benchmark public void fastjson2(Blackhole bh) { bh.consume(JSON.parseObject(str, MediaContent.class)); } // @Benchmark public void fastjson2Mixin(Blackhole bh) { bh.consume(JSON.parseObject(str, MediaContent.class, JSONFactory.createReadContext(provider))); } @Benchmark public void jackson(Blackhole bh) throws Exception { bh.consume(mapper.readValue(str, MediaContent.class)); } // @Benchmark public void wastjson(Blackhole bh) throws Exception { bh.consume( io.github.wycst.wast.json.JSON.parseObject(str, MediaContent.class) ); } @Benchmark public void gson(Blackhole bh) throws Exception { bh.consume( gson.fromJson(str, MediaContent.class) ); } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(EishayParseString.class.getName()) .exclude(EishayParseStringPretty.class.getName()) .exclude(EishayParseStringNoneCache.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run();
550
131
681
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayParseStringNoneCache.java
EishayParseStringNoneCache
fastjson2
class EishayParseStringNoneCache { static String str; // static final ObjectMapper mapper = new ObjectMapper(); // static final Gson gson = new Gson(); static { try { InputStream is = EishayParseStringNoneCache.class.getClassLoader().getResourceAsStream("data/eishay_compact.json"); str = IOUtils.toString(is, "UTF-8"); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void fastjson1(Blackhole bh) { ParserConfig config = new ParserConfig(); bh.consume(com.alibaba.fastjson.JSON.parseObject(str, MediaContent.class, config)); } @Benchmark public void fastjson2(Blackhole bh) {<FILL_FUNCTION_BODY>} @Benchmark public void jackson(Blackhole bh) throws Exception { ObjectMapper mapper = new ObjectMapper(); bh.consume(mapper.readValue(str, HashMap.class)); } // @Benchmark public void wastjson(Blackhole bh) throws Exception { bh.consume( io.github.wycst.wast.json.JSON.parse(str) ); } @Benchmark public void gson(Blackhole bh) throws Exception { Gson gson = new Gson(); bh.consume( gson.fromJson(str, HashMap.class) ); } public static void main(String[] args) throws RunnerException { Options options = new OptionsBuilder() .include(EishayParseStringNoneCache.class.getName()) .exclude(EishayParseTreeStringPretty.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run(); } }
ObjectReaderProvider provider = new ObjectReaderProvider(); JSONReader.Context readContext = JSONFactory.createReadContext(provider); bh.consume(JSON.parseObject(str, MediaContent.class, readContext));
541
56
597
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayParseStringPretty.java
EishayParseStringPretty
main
class EishayParseStringPretty { static String str; static final ObjectMapper mapper = new ObjectMapper(); static final Gson gson = new Gson(); static { try { InputStream is = EishayParseStringPretty.class.getClassLoader().getResourceAsStream("data/eishay.json"); str = IOUtils.toString(is, "UTF-8"); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void fastjson1(Blackhole bh) { bh.consume(com.alibaba.fastjson.JSON.parseObject(str, MediaContent.class)); } @Benchmark public void fastjson2(Blackhole bh) { bh.consume(JSON.parseObject(str, MediaContent.class)); } @Benchmark public void jackson(Blackhole bh) throws Exception { bh.consume(mapper.readValue(str, MediaContent.class)); } @Benchmark public void gson(Blackhole bh) throws Exception { bh.consume( gson.fromJson(str, MediaContent.class) ); } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(EishayParseStringPretty.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run();
349
97
446
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayParseTreeString.java
EishayParseTreeString
main
class EishayParseTreeString { static String str; static final ObjectMapper mapper = new ObjectMapper(); static final Gson gson = new Gson(); static { try { InputStream is = EishayParseTreeString.class.getClassLoader().getResourceAsStream("data/eishay_compact.json"); str = IOUtils.toString(is, "UTF-8"); JSON.parseObject(str, MediaContent.class); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void fastjson1(Blackhole bh) { bh.consume(com.alibaba.fastjson.JSON.parseObject(str)); } @Benchmark public void fastjson2(Blackhole bh) { bh.consume(JSON.parseObject(str)); } @Benchmark public void jackson(Blackhole bh) throws Exception { bh.consume(mapper.readValue(str, HashMap.class)); } // @Benchmark public void wastjson(Blackhole bh) throws Exception { bh.consume( io.github.wycst.wast.json.JSON.parse(str) ); } @Benchmark public void gson(Blackhole bh) throws Exception { bh.consume( gson.fromJson(str, HashMap.class) ); } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(EishayParseTreeString.class.getName()) .exclude(EishayParseTreeStringPretty.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run();
412
115
527
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayParseTreeStringPretty.java
EishayParseTreeStringPretty
main
class EishayParseTreeStringPretty { static String str; static final ObjectMapper mapper = new ObjectMapper(); static final Gson gson = new Gson(); static { try { InputStream is = EishayParseTreeStringPretty.class.getClassLoader().getResourceAsStream("data/eishay.json"); str = IOUtils.toString(is, "UTF-8"); JSON.parseObject(str, MediaContent.class); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void fastjson1(Blackhole bh) { bh.consume(com.alibaba.fastjson.JSON.parseObject(str)); } @Benchmark public void fastjson2(Blackhole bh) { bh.consume(JSON.parseObject(str)); } @Benchmark public void jackson(Blackhole bh) throws Exception { bh.consume(mapper.readValue(str, HashMap.class)); } @Benchmark public void gson(Blackhole bh) throws Exception { bh.consume( gson.fromJson(str, HashMap.class) ); } // @Benchmark public void wastjson(Blackhole bh) throws Exception { bh.consume( io.github.wycst.wast.json.JSON.parse(str) ); } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(EishayParseTreeStringPretty.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run();
414
98
512
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayParseTreeUTF8Bytes.java
EishayParseTreeUTF8Bytes
main
class EishayParseTreeUTF8Bytes { static byte[] utf8Bytes; static final ObjectMapper mapper = new ObjectMapper(); static final Gson gson = new Gson(); static { try { InputStream is = EishayParseTreeUTF8Bytes.class.getClassLoader().getResourceAsStream("data/eishay_compact.json"); utf8Bytes = IOUtils.toString(is, "UTF-8").getBytes(StandardCharsets.UTF_8); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void fastjson1(Blackhole bh) { bh.consume(com.alibaba.fastjson.JSON.parse(utf8Bytes)); } @Benchmark public void fastjson2(Blackhole bh) { bh.consume(JSON.parseObject(utf8Bytes)); } @Benchmark public void jackson(Blackhole bh) throws Exception { bh.consume(mapper.readValue(utf8Bytes, HashMap.class)); } @Benchmark public void gson(Blackhole bh) throws Exception { bh.consume(gson .fromJson( new String(utf8Bytes, 0, utf8Bytes.length, StandardCharsets.UTF_8), HashMap.class) ); } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(EishayParseTreeUTF8Bytes.class.getName()) .exclude(EishayParseTreeUTF8BytesPretty.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run();
390
119
509
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayParseTreeUTF8BytesPretty.java
EishayParseTreeUTF8BytesPretty
gson
class EishayParseTreeUTF8BytesPretty { static byte[] utf8Bytes; static final ObjectMapper mapper = new ObjectMapper(); static final Gson gson = new Gson(); static { try { InputStream is = EishayParseTreeUTF8BytesPretty.class.getClassLoader().getResourceAsStream("data/eishay.json"); utf8Bytes = IOUtils.toString(is, "UTF-8").getBytes(StandardCharsets.UTF_8); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void fastjson1(Blackhole bh) { bh.consume(com.alibaba.fastjson.JSON.parse(utf8Bytes)); } @Benchmark public void fastjson2(Blackhole bh) { bh.consume(JSON.parseObject(utf8Bytes)); } @Benchmark public void jackson(Blackhole bh) throws Exception { bh.consume(mapper.readValue(utf8Bytes, HashMap.class)); } @Benchmark public void gson(Blackhole bh) throws Exception {<FILL_FUNCTION_BODY>} public static void main(String[] args) throws RunnerException { Options options = new OptionsBuilder() .include(EishayParseTreeUTF8BytesPretty.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run(); } }
bh.consume(gson .fromJson( new String(utf8Bytes, 0, utf8Bytes.length, StandardCharsets.UTF_8), HashMap.class) );
437
55
492
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayParseUTF8Bytes.java
EishayParseUTF8Bytes
gson
class EishayParseUTF8Bytes { static byte[] utf8Bytes; static final ObjectMapper mapper = new ObjectMapper(); static final Gson gson = new Gson(); static final DslJson<Object> dslJson = new DslJson<>(Settings.withRuntime().includeServiceLoader()); static { try { InputStream is = EishayParseUTF8Bytes.class.getClassLoader().getResourceAsStream("data/eishay_compact.json"); utf8Bytes = IOUtils.toString(is, "UTF-8").getBytes(StandardCharsets.UTF_8); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void fastjson1(Blackhole bh) { bh.consume(com.alibaba.fastjson.JSON.parseObject(utf8Bytes, MediaContent.class)); } @Benchmark public void fastjson2(Blackhole bh) { bh.consume(JSON.parseObject(utf8Bytes, MediaContent.class)); } // @Benchmark public void dsljson(Blackhole bh) throws IOException { bh.consume(dslJson.deserialize(MediaContent.class, utf8Bytes, utf8Bytes.length)); } @Benchmark public void jackson(Blackhole bh) throws Exception { bh.consume(mapper.readValue(utf8Bytes, MediaContent.class)); } @Benchmark public void gson(Blackhole bh) throws Exception {<FILL_FUNCTION_BODY>} public static void main(String[] args) throws RunnerException { Options options = new OptionsBuilder() .include(EishayParseUTF8Bytes.class.getName()) .exclude(EishayParseUTF8BytesPretty.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run(); } }
bh.consume(gson .fromJson( new String(utf8Bytes, 0, utf8Bytes.length, StandardCharsets.UTF_8), MediaContent.class) );
547
55
602
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayParseUTF8BytesPretty.java
EishayParseUTF8BytesPretty
gson
class EishayParseUTF8BytesPretty { static byte[] utf8Bytes; static final ObjectMapper mapper = new ObjectMapper(); static final Gson gson = new Gson(); static { try { InputStream is = EishayParseUTF8BytesPretty.class.getClassLoader().getResourceAsStream("data/eishay.json"); utf8Bytes = IOUtils.toString(is, "UTF-8").getBytes(StandardCharsets.UTF_8); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void fastjson1(Blackhole bh) { bh.consume(com.alibaba.fastjson.JSON.parseObject(utf8Bytes, MediaContent.class)); } @Benchmark public void fastjson2(Blackhole bh) { bh.consume(JSON.parseObject(utf8Bytes, MediaContent.class)); } @Benchmark public void jackson(Blackhole bh) throws Exception { bh.consume(mapper.readValue(utf8Bytes, MediaContent.class)); } @Benchmark public void gson(Blackhole bh) throws Exception {<FILL_FUNCTION_BODY>} public static void main(String[] args) throws RunnerException { Options options = new OptionsBuilder() .include(EishayParseUTF8BytesPretty.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run(); } }
bh.consume(gson .fromJson( new String(utf8Bytes, 0, utf8Bytes.length, StandardCharsets.UTF_8), HashMap.class) );
445
55
500
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayWrite.java
EishayWrite
main
class EishayWrite { public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(EishayWrite.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run();
37
94
131
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayWriteBinary.java
EishayWriteBinary
hessian
class EishayWriteBinary { static MediaContent mc; static ObjectMapper msgpackMapper = new ObjectMapper(new MessagePackFactory()); static { try { InputStream is = EishayWriteBinary.class.getClassLoader().getResourceAsStream("data/eishay.json"); String str = IOUtils.toString(is, "UTF-8"); mc = JSONReader.of(str) .read(MediaContent.class); } catch (Throwable ex) { ex.printStackTrace(); } } // @Benchmark public void fastjson2UTF8Bytes(Blackhole bh) { bh.consume(JSON.toJSONBytes(mc)); } public int jsonbSize() { return JSONB.toBytes(mc).length; } @Benchmark public void jsonb(Blackhole bh) { bh.consume(JSONB.toBytes(mc)); } // @Benchmark public void javaSerialize(Blackhole bh) throws Exception { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(mc); objectOutputStream.flush(); bh.consume(byteArrayOutputStream.toByteArray()); } // @Benchmark public void hessian(Blackhole bh) throws Exception {<FILL_FUNCTION_BODY>} @Benchmark public void msgpack(Blackhole bh) throws Exception { bh.consume(msgpackMapper.writeValueAsBytes(mc)); } public int msgpackSize() throws Exception { return msgpackMapper.writeValueAsBytes(mc).length; } @Benchmark public void protobuf(Blackhole bh) throws Exception { bh.consume( MediaContentTransform.forward(mc) .toByteArray() ); } public int protobufSize() throws Exception { return MediaContentTransform.forward(mc) .toByteArray().length; } public static void main(String[] args) throws RunnerException { Options options = new OptionsBuilder() .include(EishayWriteBinary.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run(); } }
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Hessian2Output hessian2Output = new Hessian2Output(byteArrayOutputStream); hessian2Output.writeObject(mc); hessian2Output.flush(); bh.consume(byteArrayOutputStream.toByteArray());
648
80
728
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayWriteBinaryArrayMapping.java
EishayWriteBinaryArrayMapping
main
class EishayWriteBinaryArrayMapping { static final Fury fury = Fury.builder().withLanguage(Language.JAVA) .withRefTracking(false) .requireClassRegistration(false) .withNumberCompressed(true) .build(); static MediaContent mediaContent; private static final ThreadLocal<Kryo> kryos = ThreadLocal.withInitial(() -> { Kryo kryo = new Kryo(); kryo.register(MediaContent.class); kryo.register(ArrayList.class); kryo.register(Image.class); kryo.register(Image.Size.class); kryo.register(Media.class); kryo.register(Media.Player.class); return kryo; }); private static final ThreadLocal<Output> outputs = ThreadLocal.withInitial(() -> new Output(1024, -1)); static { try { InputStream is = EishayWriteBinaryArrayMapping.class.getClassLoader().getResourceAsStream("data/eishay.json"); String str = IOUtils.toString(is, "UTF-8"); mediaContent = JSONReader.of(str) .read(MediaContent.class); Kryo kryo = new Kryo(); kryo.register(MediaContent.class); kryo.register(ArrayList.class); kryo.register(Image.class); kryo.register(Image.Size.class); kryo.register(Media.class); kryo.register(Media.Player.class); } catch (Throwable ex) { ex.printStackTrace(); } } public int furySize() { return fury.serialize(mediaContent).length; } // @Benchmark public void fury(Blackhole bh) { bh.consume( fury.serialize(mediaContent) ); } public int jsonbSize() { return JSONB.toBytes(mediaContent, JSONWriter.Feature.BeanToArray).length; } @Benchmark public void jsonb(Blackhole bh) { bh.consume( JSONB.toBytes(mediaContent, JSONWriter.Feature.BeanToArray) ); } public int kryoSize() { Output output = outputs.get(); output.reset(); kryos.get().writeObject(output, mediaContent); return output.toBytes().length; } @Benchmark public void kryo(Blackhole bh) throws Exception { Output output = outputs.get(); output.reset(); kryos.get().writeObject(output, mediaContent); bh.consume(output.toBytes()); } public int protobufSize() { return MediaContentTransform.forward(mediaContent).toByteArray().length; } @Benchmark public void protobuf(Blackhole bh) throws Exception { byte[] bytes = MediaContentTransform.forward(mediaContent).toByteArray(); bh.consume(bytes); } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(EishayWriteBinaryArrayMapping.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run();
836
97
933
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayWriteBinaryAutoType.java
EishayWriteBinaryAutoType
javaSerialize
class EishayWriteBinaryAutoType { static MediaContent mc; static SymbolTable symbolTable = JSONB.symbolTable( "com.alibaba.fastjson2.benchmark.eishay.vo.MediaContent", "media", "images", "height", "size", "title", "uri", "width", "bitrate", "duration", "format", "persons", "player" ); static { try { InputStream is = EishayWriteBinaryAutoType.class.getClassLoader().getResourceAsStream("data/eishay.json"); String str = IOUtils.toString(is, "UTF-8"); mc = JSONReader.of(str) .read(MediaContent.class); } catch (Throwable ex) { ex.printStackTrace(); } } // @Benchmark public void fastjson2UTF8Bytes(Blackhole bh) { bh.consume(JSON.toJSONBytes(mc, JSONWriter.Feature.WriteClassName)); } @Benchmark public void fastjson2JSONB(Blackhole bh) { bh.consume( JSONB.toBytes( mc, JSONWriter.Feature.WriteClassName, JSONWriter.Feature.IgnoreNoneSerializable, JSONWriter.Feature.FieldBased, JSONWriter.Feature.ReferenceDetection, JSONWriter.Feature.WriteNulls, JSONWriter.Feature.NotWriteDefaultValue, JSONWriter.Feature.NotWriteHashMapArrayListClassName, JSONWriter.Feature.WriteNameAsSymbol) ); } public void fastjson2JSONB_symbols(Blackhole bh) { bh.consume( JSONB.toBytes( mc, symbolTable, JSONWriter.Feature.WriteClassName, JSONWriter.Feature.IgnoreNoneSerializable, JSONWriter.Feature.FieldBased, JSONWriter.Feature.ReferenceDetection, JSONWriter.Feature.WriteNulls, JSONWriter.Feature.NotWriteDefaultValue, JSONWriter.Feature.NotWriteHashMapArrayListClassName, JSONWriter.Feature.WriteNameAsSymbol) ); } @Benchmark public void javaSerialize(Blackhole bh) throws Exception {<FILL_FUNCTION_BODY>} @Benchmark public void hessian(Blackhole bh) throws Exception { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Hessian2Output hessian2Output = new Hessian2Output(byteArrayOutputStream); hessian2Output.writeObject(mc); hessian2Output.flush(); bh.consume(byteArrayOutputStream.toByteArray()); } public static void main(String[] args) throws RunnerException { Options options = new OptionsBuilder() .include(EishayWriteBinaryAutoType.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run(); } }
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(mc); objectOutputStream.flush(); bh.consume(byteArrayOutputStream.toByteArray());
824
65
889
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayWriteString.java
EishayWriteString
main
class EishayWriteString { static MediaContent mc; static final ObjectMapper mapper = new ObjectMapper(); static final Gson gson = new Gson(); static ObjectWriterProvider provider = new ObjectWriterProvider(); static { try { InputStream is = EishayWriteString.class.getClassLoader().getResourceAsStream("data/eishay.json"); String str = IOUtils.toString(is, "UTF-8"); mc = JSONReader.of(str) .read(MediaContent.class); provider.register(MediaContent.class, MediaContentMixin.objectWriter); provider.register(Media.class, MediaMixin.objectWriter); provider.register(Image.class, ImageMixin.objectWriter); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void fastjson1(Blackhole bh) { bh.consume(com.alibaba.fastjson.JSON.toJSONString(mc)); } @Benchmark public void fastjson2(Blackhole bh) { bh.consume(JSON.toJSONString(mc)); } public void fastjson2Mixin(Blackhole bh) { bh.consume( JSON.toJSONString(mc, JSONFactory.createWriteContext(provider)) ); } @Benchmark public void jackson(Blackhole bh) throws Exception { bh.consume(mapper.writeValueAsString(mc)); } // @Benchmark public void wastjson(Blackhole bh) throws Exception { bh.consume( io.github.wycst.wast.json.JSON.toJsonString(mc) ); } @Benchmark public void gson(Blackhole bh) throws Exception { bh.consume( gson.toJson(mc) ); } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(EishayWriteString.class.getName()) .exclude(EishayWriteStringNoneCache.class.getName()) .exclude(EishayWriteStringTree.class.getName()) .exclude(EishayWriteStringTree1x.class.getName()) .mode(Mode.Throughput) .warmupIterations(3) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run();
533
160
693
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayWriteStringNoneCache.java
EishayWriteStringNoneCache
main
class EishayWriteStringNoneCache { static MediaContent mc; static { try { InputStream is = EishayWriteString.class.getClassLoader().getResourceAsStream("data/eishay.json"); String str = IOUtils.toString(is, "UTF-8"); ObjectReaderProvider provider = new ObjectReaderProvider(ObjectReaderCreator.INSTANCE); JSONReader.Context readContext = JSONFactory.createReadContext(provider); mc = JSON.parseObject(str, MediaContent.class, readContext); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void fastjson1(Blackhole bh) { SerializeConfig config = new SerializeConfig(); bh.consume(com.alibaba.fastjson.JSON.toJSONString(mc, config)); } @Benchmark public void fastjson2(Blackhole bh) { ObjectWriterProvider provider = new ObjectWriterProvider(); bh.consume(JSON.toJSONString(mc, JSONFactory.createWriteContext(provider))); } @Benchmark public void fastjson2Mixin(Blackhole bh) { ObjectWriterProvider provider = new ObjectWriterProvider(); provider.register(MediaContent.class, MediaContentMixin.objectWriter); provider.register(Media.class, MediaMixin.objectWriter); provider.register(Image.class, ImageMixin.objectWriter); bh.consume(JSON.toJSONString(mc, JSONFactory.createWriteContext(provider))); } @Benchmark public void jackson(Blackhole bh) throws Exception { ObjectMapper mapper = new ObjectMapper(); bh.consume(mapper.writeValueAsString(mc)); } // @Benchmark public void wastjson(Blackhole bh) throws Exception { bh.consume( io.github.wycst.wast.json.JSON.toJsonString(mc) ); } @Benchmark public void gson(Blackhole bh) throws Exception { Gson gson = new Gson(); bh.consume( gson.toJson(mc) ); } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(EishayWriteStringNoneCache.class.getName()) .mode(Mode.Throughput) .warmupIterations(3) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run();
601
108
709
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayWriteStringTree.java
EishayWriteStringTree
main
class EishayWriteStringTree { static JSONObject mc; static final ObjectMapper mapper = new ObjectMapper(); static final Gson gson = new Gson(); static { try { InputStream is = EishayWriteStringTree.class.getClassLoader().getResourceAsStream("data/eishay.json"); String str = IOUtils.toString(is, "UTF-8"); mc = (JSONObject) JSONReader.of(str) .readAny(); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void fastjson1(Blackhole bh) { bh.consume(com.alibaba.fastjson.JSON.toJSONString(mc)); } @Benchmark public void fastjson2(Blackhole bh) { bh.consume(JSON.toJSONString(mc)); } public void fastjson2_ReferenceDetection(Blackhole bh) { bh.consume(JSON.toJSONString(mc, JSONWriter.Feature.ReferenceDetection)); } // @Benchmark public void fastjson2_jsonb(Blackhole bh) { bh.consume(JSONB.toBytes(mc)); } @Benchmark public void jackson(Blackhole bh) throws Exception { bh.consume(mapper.writeValueAsString(mc)); } // @Benchmark public void wastjson(Blackhole bh) throws Exception { bh.consume( io.github.wycst.wast.json.JSON.toJsonString(mc) ); } @Benchmark public void gson(Blackhole bh) throws Exception { bh.consume( gson.toJson(mc) ); } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(EishayWriteStringTree.class.getName()) .exclude(EishayWriteStringTree1x.class.getName()) .mode(Mode.Throughput) .warmupIterations(3) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run();
509
126
635
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayWriteStringTree1x.java
EishayWriteStringTree1x
main
class EishayWriteStringTree1x { static com.alibaba.fastjson.JSONObject mc; static final ObjectMapper mapper = new ObjectMapper(); static final Gson gson = new Gson(); static { try { InputStream is = EishayWriteStringTree1x.class.getClassLoader().getResourceAsStream("data/eishay.json"); String str = IOUtils.toString(is, "UTF-8"); mc = com.alibaba.fastjson.JSON.parseObject(str); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void fastjson1(Blackhole bh) { bh.consume(com.alibaba.fastjson.JSON.toJSONString(mc)); } @Benchmark public void fastjson2(Blackhole bh) { bh.consume(JSON.toJSONString(mc)); } public void fastjson2_ReferenceDetection(Blackhole bh) { bh.consume(JSON.toJSONString(mc, JSONWriter.Feature.ReferenceDetection)); } // @Benchmark public void fastjson2_jsonb(Blackhole bh) { bh.consume(JSONB.toBytes(mc)); } @Benchmark public void jackson(Blackhole bh) throws Exception { bh.consume(mapper.writeValueAsString(mc)); } // @Benchmark public void wastjson(Blackhole bh) throws Exception { bh.consume( io.github.wycst.wast.json.JSON.toJsonString(mc) ); } @Benchmark public void gson(Blackhole bh) throws Exception { bh.consume( gson.toJson(mc) ); } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(EishayWriteStringTree1x.class.getName()) .mode(Mode.Throughput) .warmupIterations(3) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run();
521
109
630
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayWriteUTF8Bytes.java
EishayWriteUTF8Bytes
main
class EishayWriteUTF8Bytes { static MediaContent mc; static final ObjectMapper mapper = new ObjectMapper(); static final Gson gson = new Gson(); static { try { InputStream is = EishayWriteUTF8Bytes.class.getClassLoader().getResourceAsStream("data/eishay.json"); String str = IOUtils.toString(is, "UTF-8"); mc = JSONReader.of(str) .read(MediaContent.class); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void fastjson1(Blackhole bh) { bh.consume(com.alibaba.fastjson.JSON.toJSONBytes(mc)); } @Benchmark public void fastjson2(Blackhole bh) { bh.consume(JSON.toJSONBytes(mc)); } @Benchmark public void jackson(Blackhole bh) throws Exception { bh.consume(mapper.writeValueAsBytes(mc)); } @Benchmark public void gson(Blackhole bh) throws Exception { bh.consume(gson .toJson(mc) .getBytes(StandardCharsets.UTF_8) ); } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(EishayWriteUTF8Bytes.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run();
372
97
469
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/EishayWriteUTF8BytesTree.java
EishayWriteUTF8BytesTree
main
class EishayWriteUTF8BytesTree { static JSONObject mc; static final ObjectMapper mapper = new ObjectMapper(); static { try { InputStream is = EishayWriteUTF8BytesTree.class.getClassLoader().getResourceAsStream("data/eishay.json"); String str = IOUtils.toString(is, "UTF-8"); mc = (JSONObject) JSONReader.of(str) .readAny(); } catch (Throwable ex) { ex.printStackTrace(); } } @Benchmark public void fastjson2(Blackhole bh) { bh.consume(JSON.toJSONBytes(mc)); } public void fastjson2_ReferenceDetection(Blackhole bh) { bh.consume(JSON.toJSONString(mc, JSONWriter.Feature.ReferenceDetection)); } // @Benchmark public void fastjson2_jsonb(Blackhole bh) { bh.consume(JSONB.toBytes(mc)); } @Benchmark public void jackson(Blackhole bh) throws Exception { bh.consume(mapper.writeValueAsBytes(mc)); } // @Benchmark public void wastjson(Blackhole bh) throws Exception { bh.consume( io.github.wycst.wast.json.JSON.toJsonBytes(mc) ); } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(EishayWriteUTF8BytesTree.class.getName()) .mode(Mode.Throughput) .warmupIterations(3) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .threads(16) .build(); new Runner(options).run();
405
109
514
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/vo/Image.java
Image
equals
class Image implements java.io.Serializable { private static final long serialVersionUID = 1L; public enum Size { SMALL, LARGE } private int height; private Size size; private String title; // Can be null private String uri; private int width; public Image() { } public Image(String uri, String title, int width, int height, Size size) { this.height = height; this.title = title; this.uri = uri; this.width = width; this.size = size; } public void setUri(String uri) { this.uri = uri; } public void setTitle(String title) { this.title = title; } public void setWidth(int width) { this.width = width; } public void setHeight(int height) { this.height = height; } public void setSize(Size size) { this.size = size; } public String getUri() { return uri; } public String getTitle() { return title; } public int getWidth() { return width; } public int getHeight() { return height; } public Size getSize() { return size; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(height, size, title, uri, width); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Image image = (Image) o; return height == image.height && width == image.width && size == image.size && Objects.equals(title, image.title) && Objects.equals(uri, image.uri);
416
101
517
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/vo/Media.java
Media
equals
class Media implements java.io.Serializable { public enum Player { JAVA, FLASH } private int bitrate; private long duration; private String format; private int height; private List<String> persons; private Player player; private long size; private String title; private String uri; private int width; private String copyright; public Media() { } public Media( String uri, String title, int width, int height, String format, long duration, long size, int bitrate, List<String> persons, Player player, String copyright ) { this.uri = uri; this.title = title; this.width = width; this.height = height; this.format = format; this.duration = duration; this.size = size; this.bitrate = bitrate; this.persons = persons; this.player = player; this.copyright = copyright; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } public long getDuration() { return duration; } public void setDuration(long duration) { this.duration = duration; } public long getSize() { return size; } public void setSize(long size) { this.size = size; } public int getBitrate() { return bitrate; } public void setBitrate(int bitrate) { this.bitrate = bitrate; } public List<String> getPersons() { return persons; } public void setPersons(List<String> persons) { this.persons = persons; } public Player getPlayer() { return player; } public void setPlayer(Player player) { this.player = player; } public String getCopyright() { return copyright; } public void setCopyright(String copyright) { this.copyright = copyright; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(bitrate, duration, format, height, persons, player, size, title, uri, width, copyright); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Media media = (Media) o; return bitrate == media.bitrate && duration == media.duration && height == media.height && size == media.size && width == media.width && Objects.equals(format, media.format) && Objects.equals(persons, media.persons) && player == media.player && Objects.equals(title, media.title) && Objects.equals(uri, media.uri) && Objects.equals(copyright, media.copyright);
806
161
967
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/eishay/vo/MediaContent.java
MediaContent
toString
class MediaContent implements java.io.Serializable { private Media media; private List<Image> images; public MediaContent() { } public MediaContent(Media media, List<Image> images) { this.media = media; this.images = images; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MediaContent that = (MediaContent) o; if (images != null ? !images.equals(that.images) : that.images != null) { return false; } if (media != null ? !media.equals(that.media) : that.media != null) { return false; } return true; } @Override public int hashCode() { int result = media != null ? media.hashCode() : 0; result = 31 * result + (images != null ? images.hashCode() : 0); return result; } @Override public String toString() {<FILL_FUNCTION_BODY>} public void setMedia(Media media) { this.media = media; } public void setImages(List<Image> images) { this.images = images; } public Media getMedia() { return media; } public List<Image> getImages() { return images; } }
StringBuilder sb = new StringBuilder(); sb.append("[MediaContent: "); sb.append("media=").append(media); sb.append(", images=").append(images); sb.append("]"); return sb.toString();
405
66
471
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/fastcode/AsciiToChars.java
AsciiToChars
toAsciiCharArray
class AsciiToChars { static final Function<byte[], char[]> TO_CHARS; static final MethodHandle INFLATE; static { Function<byte[], char[]> toChars = null; MethodHandle inflate = null; if (JDKUtils.JVM_VERSION > 9) { try { Class<?> latin1Class = Class.forName("java.lang.StringLatin1"); MethodHandles.Lookup lookup = JDKUtils.trustedLookup(latin1Class); MethodHandle handle = lookup.findStatic( latin1Class, "toChars", MethodType.methodType(char[].class, byte[].class) ); CallSite callSite = LambdaMetafactory.metafactory( lookup, "apply", methodType(Function.class), methodType(Object.class, Object.class), handle, methodType(char[].class, byte[].class) ); toChars = (Function<byte[], char[]>) callSite.getTarget().invokeExact(); inflate = lookup.findStatic( latin1Class, "inflate", MethodType.methodType(void.class, byte[].class, int.class, char[].class, int.class, int.class) ); } catch (Throwable ignored) { // ignored } } if (toChars == null) { toChars = AsciiToChars::toAsciiCharArray; } TO_CHARS = toChars; INFLATE = inflate; } @Benchmark public void for_cast(Blackhole bh) throws Throwable { for (int i = 0; i < bytesArray.length; i++) { byte[] bytes = bytesArray[i]; char[] chars = toAsciiCharArray(bytes); bh.consume(chars); } } @Benchmark public void lambda_cast(Blackhole bh) throws Throwable { for (int i = 0; i < bytesArray.length; i++) { byte[] bytes = bytesArray[i]; char[] chars = TO_CHARS.apply(bytes); bh.consume(chars); } } @Benchmark public void mh_inflate(Blackhole bh) throws Throwable { if (INFLATE == null) { return; } for (int i = 0; i < bytesArray.length; i++) { byte[] bytes = bytesArray[i]; char[] chars = new char[bytes.length]; INFLATE.invokeExact(bytes, 0, chars, 0, bytes.length); bh.consume(chars); } } public static char[] toAsciiCharArray(byte[] bytes) {<FILL_FUNCTION_BODY>} static final byte[][] bytesArray; static { String[] strings = { "567988.735", "-811227.824", "17415.508", "668069.440", "77259.887", "733032.058", "44402.415", "99328.975", "759431.827", "651998.851" }; byte[][] array2 = new byte[strings.length][]; for (int i = 0; i < strings.length; i++) { array2[i] = strings[i].getBytes(); } bytesArray = array2; } public static void main(String[] args) throws RunnerException { Options options = new OptionsBuilder() .include(AsciiToChars.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(1) .forks(1) .build(); new Runner(options).run(); } }
char[] charArray = new char[bytes.length]; for (int i = 0; i < bytes.length; i++) { charArray[i] = (char) bytes[i]; } return charArray;
1,090
60
1,150
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/fastcode/BigDecimalWrite.java
BigDecimalWrite
init
class BigDecimalWrite { static final ObjectMapper mapperPlain; static final ObjectMapper mapper; static { mapperPlain = new ObjectMapper(); mapperPlain.configure(SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN, true); mapper = new ObjectMapper(); } @Benchmark public void fastjson2(Blackhole bh) throws Throwable { bh.consume(JSON.toJSONString(decimals)); } @Benchmark public void fastjson2Plain(Blackhole bh) throws Throwable { bh.consume(JSON.toJSONString(decimals, JSONWriter.Feature.WriteBigDecimalAsPlain)); } @Benchmark public void jackson(Blackhole bh) throws Throwable { bh.consume(mapper.writeValueAsString(decimals)); } @Benchmark public void jacksonPlain(Blackhole bh) throws Throwable { bh.consume(mapperPlain.writeValueAsString(decimals)); } public static void main(String[] args) throws RunnerException { Options options = new OptionsBuilder() .include(BigDecimalWrite.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(1) .forks(1) .build(); new Runner(options).run(); } static final BigDecimal[] decimals; static String[] strings = { "567988.735", "-811227.824", "17415.508", "668069.440", "77259.887", "733032.058", "44402.415", "99328.975", "759431.827", "651998.851", "595127.733", "872747.476", "976748.491", "63991.314", "436269.240", "509959.652", "648017.400", "86751.384", "800272.803", "639564.823", "88635.267", "409446.022", "228804.504", "640130.935", "941728.712", "668647.192", "746452.938", "88000.517", "175690.681", "442989.476", "714895.680", "271997.015", "784747.089", "357574.796", "497020.456", "361937.673", "731252.665", "328984.250", "402177.572", "511251.084", "290164.359", "844655.633", "238646.400", "209082.573", "800429.012", "612647.616", "434125.300", "308113.583", "481771.315", "394124.322", "818335.777", "339450.066", "334937.770", "304400.447", "533111.800", "743212.248", "328471.243", "193255.426", "892754.606", "951287.847", "272599.471", "262161.834", "290162.866", "320829.094", "412294.692", "521239.528", "841545.834", "252217.529", "271679.523", "291849.519", "563712.454", "374797.778", "467001.597", "760154.498", "426363.937", "706653.732", "578078.926", "460563.960", "158475.411", "655223.901", "263773.087", "169458.408", "324783.323", "331908.388", "64351.359", "262647.243", "573084.414", "55618.851", "742849.227", "726686.140", "468504.798", "983562.626", "754044.022", "239351.762", "72823.402", "517170.424", "759187.394", "624425.622", "742522.595", "713384.831" }; static { decimals = new BigDecimal[strings.length]; init(); } public static void init() {<FILL_FUNCTION_BODY>} }
for (int i = 0; i < strings.length; i++) { decimals[i] = new BigDecimal(strings[i]); }
1,855
43
1,898
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/fastcode/DateFormat10.java
DateFormat10
main
class DateFormat10 { static final String pattern = "yyyy-MM-dd"; static DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); static Date date = new Date(1673323068000L); static final String str = "2023-01-10"; // @Benchmark public void javaTimeDateFormatter(Blackhole bh) throws Throwable { LocalDateTime ldt = date.toInstant().atZone(DateUtils.DEFAULT_ZONE_ID).toLocalDateTime(); String str = formatter.format(ldt); bh.consume(str); } // @Benchmark public void fastjson_format(Blackhole bh) throws Throwable { bh.consume(DateUtils.format(date, pattern)); } // @Benchmark public void fastjson_formatYMD10(Blackhole bh) throws Throwable { bh.consume(DateUtils.formatYMD10(date.getTime(), DateUtils.DEFAULT_ZONE_ID)); } @Benchmark public void simpleFormat(Blackhole bh) throws Throwable { bh.consume(new SimpleDateFormat(pattern).format(date)); } @Benchmark public void simpleFormatX(Blackhole bh) throws Throwable { bh.consume(new SimpleDateFormatX(pattern).format(date)); } @Benchmark public void simpleParse(Blackhole bh) throws Throwable { bh.consume(new SimpleDateFormat(pattern).parse(str)); } @Benchmark public void simpleParseX(Blackhole bh) throws Throwable { bh.consume(new SimpleDateFormatX(pattern).parse(str)); } public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>} }
Options options = new OptionsBuilder() .include(DateFormat10.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(1) .forks(1) .build(); new Runner(options).run();
499
85
584
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/fastcode/DateFormat19.java
DateFormat19
simpleDateFormatThreadLocal
class DateFormat19 { static final String pattern = "yyyy-MM-dd HH:mm:ss"; static DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); static Date date = new Date(1340424794000L); static FastDateFormat fastDateFormat = FastDateFormat.getInstance(pattern); static String str = new SimpleDateFormat(pattern).format(date); static ThreadLocal<SimpleDateFormat> SIMPLE_DATE_FORMAT_LOCAL = ThreadLocal.withInitial( () -> new SimpleDateFormat(pattern) ); // @Benchmark public void javaTimeFormatter(Blackhole bh) throws Throwable { ZoneId zonedId = DateUtils.DEFAULT_ZONE_ID; Instant instant = date.toInstant(); LocalDateTime ldt = LocalDateTime.ofInstant(instant, zonedId); String str = formatter.format(ldt); bh.consume(str); } // @Benchmark public void commonsFastFormat(Blackhole bh) throws Throwable { String str = fastDateFormat.format(date); bh.consume(str); } // @Benchmark public void simpleDateFormat(Blackhole bh) throws Throwable { SimpleDateFormat format = new SimpleDateFormat(pattern); String str = format.format(date); bh.consume(str); } // @Benchmark public void simpleDateFormatThreadLocal(Blackhole bh) throws Throwable {<FILL_FUNCTION_BODY>} // @Benchmark public void fastjsonFormat(Blackhole bh) throws Throwable { bh.consume(DateUtils.format(date, pattern)); } // @Benchmark public void formatYMDHMS19(Blackhole bh) throws Throwable { bh.consume(DateUtils.formatYMDHMS19(date)); } // @Benchmark public void fastjsonFormat2(Blackhole bh) throws Throwable { bh.consume(DateUtils.format(date.getTime())); } @Benchmark public void simpleFormat(Blackhole bh) throws Throwable { bh.consume(new SimpleDateFormat(pattern).format(date)); } @Benchmark public void simpleFormatX(Blackhole bh) throws Throwable { bh.consume(new SimpleDateFormatX(pattern).format(date)); } @Benchmark public void simpleParse(Blackhole bh) throws Throwable { bh.consume(new SimpleDateFormat(pattern).parse(str)); } @Benchmark public void simpleParseX(Blackhole bh) throws Throwable { bh.consume(new SimpleDateFormatX(pattern).parse(str)); } public static void main(String[] args) throws RunnerException { Options options = new OptionsBuilder() .include(DateFormat19.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(1) .forks(1) .build(); new Runner(options).run(); } }
SimpleDateFormat format = SIMPLE_DATE_FORMAT_LOCAL.get(); String str = format.format(date); bh.consume(str);
849
44
893
<no_super_class>
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/fastcode/DateParse19.java
DateParse19
simpleDateFormat
class DateParse19 { static final String pattern = "yyyy-MM-dd HH:mm:ss"; static String input = "2012-06-23 12:13:14"; static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); static final FastDateFormat FAST_DATE_FORMAT = FastDateFormat.getInstance(pattern); static ThreadLocal<SimpleDateFormat> SIMPLE_DATE_FORMAT_LOCAL = ThreadLocal.withInitial( () -> new SimpleDateFormat(pattern) ); @Benchmark public void javaTimeFormatter(Blackhole bh) throws Throwable { LocalDateTime ldt = LocalDateTime.parse(input, formatter); ZoneId zoneId = DateUtils.DEFAULT_ZONE_ID; ZonedDateTime zdt = ldt.atZone(zoneId); Instant instant = zdt.toInstant(); Date date = Date.from(instant); bh.consume(date); } // @Benchmark public void javaTimeDateTimeFormatter1(Blackhole bh) throws Throwable { LocalDateTime ldt = LocalDateTime.parse(input, formatter); ZoneId zoneId = DateUtils.DEFAULT_ZONE_ID; long millis = DateUtils.millis(ldt, zoneId); Date date = new Date(millis); bh.consume(date); } // @Benchmark public void parseDateSmart(Blackhole bh) throws Throwable { Date date = DateUtils.parseDate(input); bh.consume(date); } @Benchmark public void parseDateYMDHMS19(Blackhole bh) throws Throwable { Date date = DateUtils.parseDateYMDHMS19(input); bh.consume(date); } // @Benchmark public void parseDate(Blackhole bh) throws Throwable { Date date = DateUtils.parseDate(input, pattern); bh.consume(date); } @Benchmark public void simpleDateFormat(Blackhole bh) throws Throwable {<FILL_FUNCTION_BODY>} @Benchmark public void simpleDateFormatThreadLocal(Blackhole bh) throws Throwable { SimpleDateFormat format = SIMPLE_DATE_FORMAT_LOCAL.get(); Date date = format.parse(input); bh.consume(date); } @Benchmark public void commonLangFastDateFormat(Blackhole bh) throws Throwable { Date date = FAST_DATE_FORMAT.parse(input); bh.consume(date); } public static void main(String[] args) throws RunnerException { Options options = new OptionsBuilder() .include(DateParse19.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(1) .forks(1) .build(); new Runner(options).run(); } }
SimpleDateFormat format = new SimpleDateFormat(pattern); Date date = format.parse(input); bh.consume(date);
796
38
834
<no_super_class>