Coder Social home page Coder Social logo

chronicle-threads's Introduction

Chronicle Threads

This Library

This library provides high performance event loop implementations and utility functions to help with threading and concurrency.

Concurrency is hard, and event loops provide an abstraction to make dealing with concurrency easier. Context switching between threads is expensive and best practice in a low latency system is to keep your latency-sensitive operations executing on a small number of "fast" threads and the event loop abstraction fits well with this approach.

For best latency these fast threads will be busy-spinning i.e. consuming a whole core, and the core running the fast thread is isolated from the OS and other applications.

This library contains a number of event loop implementations and additional features, all implemented with a view to minimising latency and avoiding garbage in the fast path.

Event Handlers and Event Loops

An event loop can have multiple event handlers installed on it and the event loop will repeatedly execute these event handlers. Each event handler is guaranteed to be called on only one thread. Event handlers are expected to perform a chunk of work quickly and return without blocking, although the EventGroup does provide a mechanism to support blocking event handlers - see HandlerPriority.

Figure 1 illustrates a diagram of an event loop that serves several event handlers sequentially.

1000
Figure 1. Event Loop and Event Handlers

Event Handlers

In this section we explore common event handler use cases

Implement event handler

An event handler can be created by implementing the EventHandler interface and overriding its action() method so that it executes the required work. The action() method returns a boolean value signifying whether some work was done by the action() - an example is an event handler that tries to poll from a Chronicle Queue - the return value of the action() should indicate if the read succeeded and a message was processed.

Note
The event loop considers this return value by using a heuristic: if the action() did some work, it is likely to do some more work next time, and so we should call it again as soon as we can. If it did not do some work, it is less likely to do work next time, so it may appropriate to yield or pause before calling again - see Pausers.

As a rule of thumb, an action handler should do a limited amount of work then return. If it knows for sure that there is remaining work to be done at the point of return then it should return true.

public final class ExampleEventHandler implements EventHandler {
    @Override
    public boolean action() throws InvalidEventHandlerException {
        // do work
        return didWork;
    }
}

Adding to event loop

call the addHandler method of the event loop. See also Start event loop

el.addHandler(eh0);

Removing an event handler from an eventLoop

When an event handler wants to remove itself from the event loop, its action() method should throw InvalidEventHandlerException. The InvalidEventHandlerException.reusable() method returns a reusable, pre-created, InvalidEventHandlerException that is unmodifiable and contains no stack trace. The below event handler uninstalls itself after being called 30 times.

public final class UninstallingEventHandler implements EventHandler {
    private int actionCount = 0;

    @Override
    public boolean action() throws InvalidEventHandlerException {
        if (++actionCount > 30)
            throw InvalidEventHandlerException.reusable();
        // do work
        return didWork;
    }
}

Event Loops

Chronicle Threads contains a number of event loop implementations. These are aggregated together in the EventGroup, and the general recommendation is to make use of this, although the other implementations of EventLoop can of course by used, or the user can implement their own. The EventGroup also automatically enables Performance Monitoring.

Creating event loop

event group is created by calling the using the EventGroupBuilder. Basic example shown below:

EventLoop eg = EventGroupBuilder.builder()
                .withPauser(Pauser.busy())
                .withName("my-eg")
                .build()

Start event loop

the EventLoop.start() method starts the event loop. Event handlers can be added before and after starting the event loop but will not be executed until start() has been called.

el.start();

Stop event loop

Calling the stop() method will stop the event loop executing handlers and blocks until all handlers have finished executing. Calling close() on an event loop first calls stop and will then call close on all event handlers. Once an event loop has been stopped it is not expected that it can be restarted.

For more details on lifecycle please see javadoc of EventLoop and EventHandler.

Handler priority

Event handlers have a HandlerPriority (the default is MEDIUM) and when an EventHandler is installed on an EventGroup, the HandlerPriority determines which of its child event loops the EventHandler is installed on. The second use of HandlerPriority is to enable each (child) event loop to determine how often each EventHandler is called e.g. HandlerPriority.HIGH handlers are executed more than HandlerPriority.MEDIUM handlers.

Pausers

Chronicle Threads provides a number of implementations of the Pauser and it is straightforward for the user to implement their own if need be. The Pauser allows the developer to choose an appropriate trade-off between latency vs CPU consumption for when an EventLoop is running events which exhibit "bursty" behaviour.

The recommended way to use Pauser - and this is how Chronicle Thread’s event loop implementations use it:

    while (running) {
        // pollForWork returns true if work was done
        if (pollForWork())
            pauser.reset();
        else
            pauser.pause();
    }

The Pauser implementation can choose to yield, pause (with back off if required).

Back off pausers

In the context of the heuristic in Implement event handler above - if an EventHandler does no work, then it may well not need to do any work for a while, as events often occur in bursts in the real world. In this case it makes sense for the Pauser to keep track of how many times it has been called, and progressively implement longer pauses every time its pause() is called. This behaviour allows a back off pauser to strike a reasonable balance between handling bursts of events quickly, but backing off and reducing CPU consumption in case of gap in incoming events.

A good example of a back off Pauser is the LongPauser which will busy-loop for minBusy events (allowing the event loop to respond quickly if a new event arrives immediately), then will yield for minCount times before it sleeping for minTime increasing up to maxTime.

TimingPauser

TimingPauser interface extends the Pauser interface and behaves the same, but if the

void pause(long timeout, TimeUnit timeUnit) throws TimeoutException;

method is called, the TimingPauser will keep track of accumulated pause times and throw a TimeoutException if the specified timeout is exceeded. LongPauser, TimedBusy and TimingPauser are of type TimingPauser.

PauserMode

PauserMode contains factory methods for Pauser implementations. Because Pauser is not an enum, and implementations are not Marshallable, PauserMode can be used in yaml config files.

There are PauserMode for all Pauser factory methods.

Table 1. Available PauserModes

Mode

Description

Benefits

Downside

Can be monitored

Requires CPU isolation

busy

Busy-loops

Minimises jitter

Uses max CPU, no monitoring support

timedBusy

Same as busy but also implements TimingPauser

Minimises jitter

Uses max CPU, no monitoring support

yielding

Very briefly busy-loops then yields

Low jitter, stateless and thus can be shared

Uses high CPU

balanced

Back off pauser - implemented with LongPauser

Good balance of busy waiting and back off

Uses less CPU, but more jitter

milli

Sleeps for one millisecond, no back off

Low CPU use

Up to 1 ms jitter

sleepy

Less aggressive version of balanced

Minimal CPU

High jitter

The busy pauser minimises jitter for best performance. However, it means that an entire core is consumed and care should be taken to ensure that there are enough cores for each busy thread. If not, the machine will perform worse.

The graph below illustrates how each different type of PauserMode backs off over time:

700
Figure 2. Pauser Mode Performance

Performance Monitoring

Event Loop Monitoring (AKA Loop Block Monitoring) is a very useful feature. This is implemented by a handler which is installed on the MonitorEventLoop by the EventGroup. The ThreadMonitorHarness handler monitors fast event loop threads to make sure event handler latency remains within acceptable bounds. The ThreadMonitorHarness monitors latency by measuring the time the action method of the application event handlers takes to run. Whenever the method runs beyond an acceptable latency limit, ThreadMonitorHarness prints a stack trace for the event loop thread. This output can be processed with tools to help identify hotspots in your program.

Set the monitor event interval with system property MONITOR_INTERVAL_MS.

Disable the monitor by setting the system property:

disableLoopBlockMonitor=true

You can use any stack trace information to improve the design for efficiency.

Recommendations:

  • Impose an interval of Xms for every event loop, and gradually decrease as blockages are found and fixed.

  • Consider adding Jvm.safepoint calls to help identify hotspots in the code.

chronicle-threads's People

Contributors

alamar avatar benbonavia avatar danielshaya avatar dekmm avatar dpisklov avatar epickrram avatar glukos avatar hft-team-city avatar j4sm1ne96 avatar jerryshea avatar kailash-katharine avatar lburgazzoli avatar martyix avatar minborg avatar nicktindall avatar peter-lawrey avatar robaustin avatar scottkidder avatar tgd avatar tomshercliff avatar vach-chronicle avatar yevgenp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

chronicle-threads's Issues

Inconsistent EventHandler::action invocation order

A) The API does not specify which guarantees (if any) are made to the order in which EventHandler::action is invoked across added handlers.

EventHandler objects added to a VanillaEventHandler are handled inconsistently with respect to the order in which they were added.

add action
1 1
1,2 2,1
1,2,3 3,2,1
1,2,3,4 4,3,2,1
1,2,3,4,5 1,2,3,4,5
1,.., N, N>4 1, ..., N

Improve EventHandler termination performance

It is possible to create a subclass of InvalidEventHandlerException that only exists as a singleton (e.g. SingletonInvalidEventHandlerException) and that is statically created. EventHandlers that only use the InvalidEventHandlerException as a means of removing itself from the EventLoop could use the static Exception for pure removal with no underlying exception to signal. This will improve loop performance and reduce jittering.

Exceptional performance...

Event handler scheme may cause starvation for newly added handlers

The VanillaEventLoop::runLoop method basically computes a reduction of all the handlers' status and stores the result in the local variable busy. New handlers are only admitted when the reduced busy is false. In other words, as long as there is at least one handler that is busy, no new handlers are accepted.

This means that if there are long term operations (such as bootstrapping a queue subscriber), new handlers are effectively prevented from attaching in a reasonable time.

There might be other implementations of EventLoop that have the same issue. Concurrency issues must probably be considered before just admitting new handlers.

Remove a Handler which throws an Exception

The EventLoop used to only remove a handler after an InvalidEventHandlerException was thrown.

Now it will remove the handler on any exception, logging a warning.
InvalidEventHandlerException will remove the handler silently as it did before.

Faster shutdown of blocking tasks

Some threads that are executing LockSupport.parkNanos take a while to respond to net.openhft.chronicle.threads.Threads#shutdown(java.util.concurrent.ExecutorService)

Have added a call to unpark them to speed up their shutdown.

Can't add EventHandlers to EventLoops after close

As part of this, deprecate net.openhft.chronicle.core.threads.EventLoop method

void addHandler(boolean dontAttemptToRunImmediatelyInCurrentThread, @NotNull EventHandler handler)

as it does not make sense to run an EventHandler in the current thread, and especially not if the event loop has not been started, or been closed.

Add an EventLoop status report

It would be nice to provide some kind of "top" command where information on various properties associated with EventLoops, pausers, priorities etc. could be easily viewed and understood.

This is something that could be very useful when running almost any library that is using Threads.

TID.     TYPE              %CPU        Pauser
16422 VanillaEventLoop     100.0       BusyPauser

List of event handlers

17552 VanillaEventLoop     1.3%        LongPauser

List of event handlers

The table above is just an outline and may not be possible or even desirable as exemplified.

MediumEventLoop is printing the wrong text

A very minor issue: says "Event Group" but should say "MediumEventLoop".

2020-04-21T15:04:25.355 main/replication-acceptor-2 AcceptorEventHandler localhost80901, port=55169java.lang.IllegalStateException: Event Group has been interrupted
	at net.openhft.chronicle.threads.MediumEventLoop.checkInterrupted(MediumEventLoop.java:176)
	at net.openhft.chronicle.threads.MediumEventLoop.addHandler(MediumEventLoop.java:156)
	at net.openhft.chronicle.network.AcceptorEventHandler.action(AcceptorEventHandler.java:97)
	at net.openhft.chronicle.threads.BlockingEventLoop$Runner.run(BlockingEventLoop.java:172)
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
	at java.util.concurrent.FutureTask.run(FutureTask.java:266)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at java.lang.Thread.run(Thread.java:748)

Add a way of improving EventHandler immutability

It would be useful to add a lifecycle method EventHandle::loopStarting that allows thread-specific properties to be initialized prior to any invocation of EventHandler::action. The method is invoked by the event loop thread. This would provide at least three benefits:

A) Some properties must not be concurrent (e.g. ThreadLoacal, volatile or AtomicX) as the loopStarting() is guaranteed to be invoked by the event loop thread.
B) The time-critical EventHandler::action, that is potentially called a gazillion times, could now be ridded from code that is only executed once.
C) Would provide a more logical and distinct separation of concerns.

Example from the wild (TcpHandler):


private volatile Thread actionThread;

...

    @Override
    public boolean action() throws InvalidEventHandlerException {

        ...

        // Unnecessary volatile read each invocation
        if (actionThread == null)
            actionThread = Thread.currentThread();


LoopBlockMonitor does not support monitoryIntervalMs of 1

2016-11-25T00:34:49,749 [main/event-loop-monitor] [WARN |threads.MonitorEventLoop] -
java.lang.ArithmeticException: / by zero
at net.openhft.chronicle.threads.EventGroup$LoopBlockMonitor.action(EventGroup.java:226) ~[chronicle-threads-1.7.3-SNAPSHOT.jar:?]
at net.openhft.chronicle.threads.MonitorEventLoop.runHandlers(MonitorEventLoop.java:120) ~[chronicle-threads-1.7.3-SNAPSHOT.jar:?]
at net.openhft.chronicle.threads.MonitorEventLoop.run(MonitorEventLoop.java:99) ~[chronicle-threads-1.7.3-SNAPSHOT.jar:?]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[?:1.8.0_101]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[?:1.8.0_101]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [?:1.8.0_101]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [?:1.8.0_101]
at java.lang.Thread.run(Thread.java:745) [?:1.8.0_101]

Looks like this line (226):

long blockingInterval = blockingTimeMS / (monitoryIntervalMs / 2);

Fixed ConcurrentModificationException on shutdown

[main] DEBUG net.openhft.chronicle.threads.Threads - 
java.util.ConcurrentModificationException
	at java.util.HashMap$HashIterator.nextNode(HashMap.java:1445)
	at java.util.HashMap$KeyIterator.next(HashMap.java:1469)
	at java.util.AbstractCollection.toArray(AbstractCollection.java:141)
	at java.util.ArrayList.<init>(ArrayList.java:178)
	at net.openhft.chronicle.threads.Threads.forEachThread(Threads.java:187)
	at net.openhft.chronicle.threads.Threads.interrupt(Threads.java:164)
	at net.openhft.chronicle.threads.Threads.shutdown(Threads.java:132)
	at net.openhft.chronicle.threads.BlockingEventLoop.close(BlockingEventLoop.java:146)
	at net.openhft.chronicle.core.io.Closeable.closeQuietly(Closeable.java:42)
	at net.openhft.chronicle.core.io.Closeable.closeQuietly(Closeable.java:38)
	at net.openhft.chronicle.core.io.Closeable.closeQuietly(Closeable.java:30)
	at net.openhft.chronicle.threads.EventGroup.close(EventGroup.java:353)
	at net.openhft.chronicle.core.io.Closeable.closeQuietly(Closeable.java:42)
	at software.chronicle.enterprise.map.cluster.MapClusterContext.close(MapClusterContext.java:102)
	at net.openhft.chronicle.core.io.Closeable.closeQuietly(Closeable.java:42)
	at net.openhft.chronicle.core.io.Closeable.closeQuietly(Closeable.java:38)
	at net.openhft.chronicle.core.io.Closeable.closeQuietly(Closeable.java:30)
	at software.chronicle.enterprise.map.ReplicatedMap.close(ReplicatedMap.java:234)
	at software.chronicle.fix.router.integration.IntegrationRouterTest.test(IntegrationRouterTest.java:178)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Improved documentation and code cleanups

The "threads" library is in need of documentation and code cleanups:

  • What is the life-cycle of an EventHandler/EventLoop?
  • When are methods invoked?
  • By which threads are methods invoked?
  • When does an EventHandled become eligible for scheduling?
  • Is the loopFinished() guaranteed to be invoked exactly one time?
  • What happens if loopFinished() throws an Exception?
  • What is the purpose of EventHandler::eventLoop?
  • When and why is a potential Close method invoked?
  • Is the Close guaranteed to be invoked exactly one time?
  • What happens if close throws an Exception?
  • Can an EventHandler be added a plurality of times to an EventLoop?
  • Can an EventHandler be added a plurality of times simultaneously to an EventLoop?
  • Can an EventHandler be added to a plurality of EventLoops?
  • Can EventLoop::addHandler block the calling thread and if so, for how long? (presently, indefinitely under some conditions)
  • When can an EventHandler be added to/removed from an EventLoop?
  • What is the individual order (if any) of EventHandlers within an EventLoop?
  • Are there any guarantees on fairness amongst EventHandlers?
  • Is the order of invocation on retained EventHandlers time-invariant ? (it is not today)
  • Why is the base interface named VanillaEventHandler when it is not an implementing class?
  • What is the contract when observing an EventHandler/EventLoop using another thread?

Also, test coverage should be improved, especially as most other modules rely heavily on the threads module.

Use of the vanillaEventLoop's addNewHandler method

source code:
private void addNewHandler(@NotNull EventHandler handler) {
HandlerPriority t1 = handler.priority();
switch (t1 == null ? HandlerPriority.MEDIUM : t1) {
case HIGH:
if (!highHandlers.contains(handler))
highHandlers.add(handler);
break;

        case REPLICATION:
        case CONCURRENT:
        case MEDIUM:
            if (!mediumHandlers.contains(handler)) {
                mediumHandlers.add(handler);
                mediumHandlersArray = mediumHandlers.toArray(NO_EVENT_HANDLERS);
            }
            break;

        case TIMER:
            if (!timerHandlers.contains(handler))
                timerHandlers.add(handler);
            break;

        case DAEMON:
            if (!daemonHandlers.contains(handler))
                daemonHandlers.add(handler);
            break;

        default:
            throw new IllegalArgumentException("Cannot add a " + handler.priority() + " task to a busy waiting thread");
    }
    handler.eventLoop(parent);
}

After adding a new handler, the following code:
handler.eventLoop(parent)
Don't know what purpose this code is based on? Can my dear friend inform this?

eventLoop is the default empty method in EventHandler, chronicle-thread does not override the eventLoop method: how does the use of handler.eventLoop(parent) be implemented?
Can my dear friend help answer it?

I really like your code on github, @peter-lawrey , and I'm always looking at you, hoping to get your point!

the Questions about "was not accepted before close"

Define 300 tasks to be added to EventGroup. The task type is CONCURRENT. After executing close, the task is discarded directly. Warning message: "Handler in newHandlerQueue was not accepted before close net.openhft.chronicle.threads"!

Cause Analysis:
When the task is added to VanillaEventLoop and EventGroup.close() is executed, the task in newHandlerQueue is discarded directly. This is not logical!
Tasks added before close should be executed!
Isn't it waiting for the task in newHandlerQueue to complete and shutting down VanillaEventLoop?

If it is the current logic, I think its use scenario is almost non-existent. If the scenario is limited, where does the high performance performance not be realized?

Optimized IsolatedEventLoop

In VanillaEventLoop we read status variables, iterate over a number of Lists and do some logic while in the inner loop whilst doing numerous volatile reads. This opens up for potential improvements:

A) Reduce the number of. volatile reads (ideally less than 1 volatile read on average per loop)

B) Pre-compile the order in which handlers are invoked

It should be noted that adding a handler is likely a relatively infrequent operation compared to actually invoking handlers. A and B are orthogonal solutions which could or could not be implemented in any particular solution.

A) Volatile read elimination

We could have ArrayLists and arrays instead of CopyOnWriteList and boolean close instead of AtomicBoolean provided that only the loop itself updates said variables.

B) Precompile

So, I was thinking about implementing an IsolatedEventLoop that "flattens" the logic so it just contains raw invocations of the handlers. This is done by unrolling logics and loops and producing an array (or perhaps even single aggregate Runnable) that depends on the currently added handlers (instances, priorities, etc).

Let's say we are adding handler h1, h2, h3, h4 to a IsolatedEventLoop. Let's further assume that h3 has HandlerPriority.HIGH and the others have HandlerPriority.MEDIUM. Upon adding h4, the CompilingEventLoop unrolls the operations:

            if (highHandlers.isEmpty()) {
                busy = runMediumLoopOnly();
            } else {
                busy = runHighAndMediumTasks();
            }

    private boolean runHighAndMediumTasks() {
        boolean busy = false;
        for (int i = 0; i < 4; i++) {
            loopStartMS = Time.currentTimeMillis();
            busy |= runAllHighHandlers();
            busy |= runOneQuarterMediumHandler(i);
        }
        return busy;
    }

    @HotMethod
    private boolean runAllHighHandlers() {
        boolean busy = false;
        for (int i = 0; i < highHandlers.size(); i++) {
            final EventHandler handler = highHandlers.get(i);
            try {
                boolean action = handler.action();
                busy |= action;
            } catch (InvalidEventHandlerException e) {
                removeHandler(handler, highHandlers);

            } catch (Throwable e) {
                Jvm.warn().on(getClass(), e);
            }
        }
        return busy;
    }

    @HotMethod
    private boolean runOneQuarterMediumHandler(int i) {
        boolean busy = false;
        final EventHandler[] mediumHandlersArray = this.mediumHandlersArray;
        for (int j = i; j < mediumHandlersArray.length; j += 4) {
            final EventHandler handler = mediumHandlersArray[j];
            try {
                busy |= handler.action();
            } catch (InvalidEventHandlerException e) {
                removeHandler(handler, mediumHandlers);
                this.mediumHandlersArray = mediumHandlers.toArray(NO_EVENT_HANDLERS);

            } catch (Throwable e) {
                Jvm.warn().on(getClass(), e);
            }
        }
        return busy;
    }

to basically:

        boolean busy = false;

       
        busy |= h3.action();
        busy |= h1.action();
        busy |= h3.action();
        busy |= h2.action();
        busy |= h3.action();
        busy |= h4.action();

Additional provisions have to be added for handling failing handlers that throw InvalidEventHandlerException but that can relatively easily be handled.

The proposed IsolatedEventLoop could potentially execute faster than a VanillaEventLoop if new handlers are never or seldom added.

/P

Fixed StreamCorrupted relating to nanotime overflow

A client reported a StreamCorrupted error and believes this is related to this issue https://stackoverflow.com/questions/51398967/how-would-comparison-cause-numerical-overflow-when-using-system-nanotime.

This happens when pauser.pause(timeout, timeunit) would throw TimeoutException BEFORE the desired timeout (15 seconds by default), and TableStoreWriterLock would forceUnlock very quickly, causing concurrent writers to corrupt the queue file.

Following code in BusyTimedPauser:

@Override
public void pause(long timeout, TimeUnit timeUnit) throws TimeoutException {
    if (time == Long.MAX_VALUE)
        time = System.nanoTime();
    if (time + timeUnit.toNanos(timeout) < System.nanoTime())
        throw new TimeoutException();
}

Should be changed to something like:

@Override
public void pause(long timeout, TimeUnit timeUnit) throws TimeoutException {
   if (time == Long.MAX_VALUE)
       time = System.nanoTime();
   if (time + timeUnit.toNanos(timeout) - System.nanoTime() < 0)
       throw new TimeoutException();
}

This explains why it happens randomly and is hard to reproduce.

Performance comparison with other threadpools

Hey! I was just wondering if there was a performance comparison between this and other threadpool implementations, e.g. those found in java.util.concurrent.*. I'm just trying to gauge what the advantages and disadvantages of this implementation are.

Thanks!

Found a bug in EventGroup during unit testing?

Test Case:
`
Thread t;
try (final EventLoop eventGroup = new EventGroup(false)) {
eventGroup.start();
t = new Thread(eventGroup::awaitTermination);
t.start();
eventGroup.addHandler(new EventHandler() {
@OverRide
public boolean action() throws InvalidEventHandlerException, InterruptedException {
System.out.println("time="+ System.currentTimeMillis());
return false;
}
public HandlerPriority priority() {
return HandlerPriority.MONITOR;
}

                public void eventLoop(EventLoop eventLoop){
                    System.err.println("time="+ System.currentTimeMillis());
                }
            });
    }

`
It can be found that the action method is called multiple times in a loop. Is this appropriate?
Don't understand what the purpose or role of the action method is? For example, what is its role in this project?

VanillaEventLoop erroneously calls close() if an EventHandler happens to implement Closeable

Upon leaving a VanillaEventLoop, the method EventHandler::loopFinished is invoked as specified in the API.

However, there is nothing in the API contract even remotely suggesting that Closeable::close should be invoked if an EventHandle incidentally happens to implement Closeable.

This might lead to highly undesirable side-effects including attempting to release native memory a plurality of times.

This could be remedied in at least two ways:

A) Add extends Closeable to the interface EventHandler and add appropriate JavaDoc defining if and when the method is invoked.

B) Remove any magic invocation of Closeable::close() from any and all implementations of the EventLoop interface.

Both A and B will have compatibility issues.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.