Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In
Continue with Google
Continue with Facebook
or use


Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here
Continue with Google
Continue with Facebook
or use


Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.


Have an account? Sign In Now

Sorry, you do not have a permission to ask a question, You must login to ask question.

Continue with Google
Continue with Facebook
or use


Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Stack Ask

Stack Ask Logo Stack Ask Logo

Stack Ask Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 5906
Next
In Process
tvd12
  • 0
tvd12Enlightened
Asked: May 19, 20222022-05-19T14:19:46+00:00 2022-05-19T14:19:46+00:00In: Java

Ví dụ về EvenLoopGroup

  • 0

EventLoopGroup sẽ cho phép chúng ta quản lý các EvenLoop và phân bổ các Event vào các EvenLoop sao cho đồng đều và đảm bảo 1 event sẽ được thực thi trên 1 thread duy nhất để tránh lỗi concurrent:

public interface EzyEventLoopEvent {

    boolean call();

    default void onFinished() {}

    default void onRemoved() {}
}
design-pattern
  • 1 1 Answer
  • 26 Views
  • 0 Followers
  • 0
Answer
Share
  • Facebook
  • Report

1 Answer

  • Voted
  • Oldest
  • Recent
  1. tvd12 Enlightened
    2022-05-19T14:20:00+00:00Added an answer on May 19, 2022 at 2:20 pm
    public class EzyEventLoopGroup {
    
        private final EzyRoundRobin eventLoops;
        private final Map eventLoopByEvent;
    
        public static final int DEFAULT_MAX_SLEEP_TIME = 3;
    
        public EzyEventLoopGroup(int numberOfThreads) {
            this(
                numberOfThreads,
                EzyNettyThreadFactory.create("ezy-event-loop")
            );
        }
    
        public EzyEventLoopGroup(
            int numberOfThreads,
            ThreadFactory threadFactory
        ) {
            this(
                DEFAULT_MAX_SLEEP_TIME,
                numberOfThreads,
                threadFactory
            );
        }
    
        public EzyEventLoopGroup(
            int maxSleepTime,
            int numberOfThreads,
            ThreadFactory threadFactory
        ) {
            eventLoopByEvent = new ConcurrentHashMap();
            eventLoops = new EzyRoundRobin(
                () -> new EventLoop(maxSleepTime, threadFactory),
                numberOfThreads
            );
            for (int i = 0; i < numberOfThreads; ++i) {
                eventLoops.get().start();
            }
        }
    
        public void addEvent(EzyEventLoopEvent event) {
            final EventLoop eventLoop = eventLoops.get();
            eventLoopByEvent.put(
                event instanceof ScheduledEvent
                    ? ((ScheduledEvent) event).event
                    : event,
                eventLoop
            );
            eventLoop.addEvent(event);
        }
    
        public void addScheduleEvent(
            EzyEventLoopEvent event,
            long period
        ) {
            addScheduleEvent(event, 0, period);
        }
    
        public void addScheduleEvent(
            EzyEventLoopEvent event,
            long delayTime,
            long period
        ) {
            addEvent(new ScheduledEvent(event, delayTime, period));
        }
    
        public void addOneTimeEvent(
            Runnable event,
            long delayTime
        ) {
            final EzyEventLoopEvent wrapper = new EzyEventLoopEvent() {
                @Override
                public boolean call() {
                    event.run();
                    return false;
                }
    
                @Override
                public void onFinished() {
                    eventLoopByEvent.remove(this);
                }
            };
            addEvent(
                new ScheduledEvent(
                    wrapper,
                    delayTime,
                    delayTime
                )
            );
        }
    
        public void removeEvent(EzyEventLoopEvent event) {
            final EventLoop eventLoop = eventLoopByEvent.remove(event);
            if (eventLoop != null) {
                eventLoop.removeEvent(event);
            }
        }
    
        public void shutdown() {
            eventLoops.forEach(EventLoop::shutdownAndGet);
        }
    
        public List shutdownAndGet() {
            final List unfinishedEvents = new ArrayList();
            eventLoops.forEach(it ->
                unfinishedEvents.addAll(it.shutdownAndGet())
            );
            return unfinishedEvents;
        }
    
        private static final class EventLoop extends EzyLoggable {
    
            private final int maxSleepTime;
            private final AtomicBoolean active;
            private final AtomicBoolean stopped;
            private final EzyFuture shutdownFuture;
            private final ThreadFactory threadFactory;
            private final List removeEvents;
            private final Map events;
    
            private EventLoop(
                int maxSleepTime,
                ThreadFactory threadFactory
            ) {
                this.maxSleepTime = maxSleepTime;
                this.threadFactory = threadFactory;
                this.active = new AtomicBoolean();
                this.stopped = new AtomicBoolean();
                this.events = new ConcurrentHashMap();
                this.removeEvents = new ArrayList();
                this.shutdownFuture = new EzyFutureTask();
            }
    
            public void addEvent(EzyEventLoopEvent event) {
                if (!active.get()) {
                    throw new IllegalStateException("event loop has stopped");
                }
                events.put(
                    event instanceof ScheduledEvent
                        ? ((ScheduledEvent) event).event
                        : event,
                    event
                );
            }
    
            public void removeEvent(EzyEventLoopEvent event) {
                synchronized (removeEvents) {
                    removeEvents.add(event);
                }
            }
    
            private void doRemoveEvent(EzyEventLoopEvent event) {
                events.remove(
                    event instanceof ScheduledEvent
                        ? ((ScheduledEvent) event).event
                        : event
                );
                processWithLogException(event::onRemoved, true);
            }
    
            public void start() {
                threadFactory.newThread(this::doStart)
                    .start();
            }
    
            private void doStart() {
                active.set(true);
                final List eventBuffers = new ArrayList();
                while (active.get()) {
                    final long startTime = System.currentTimeMillis();
                    eventBuffers.addAll(events.values());
                    for (EzyEventLoopEvent event : eventBuffers) {
                        try {
                            if (event instanceof ScheduledEvent) {
                                final ScheduledEvent scheduledEvent = (ScheduledEvent) event;
                                if (scheduledEvent.isNotFireTime()) {
                                    continue;
                                }
                            }
                            if (!event.call()) {
                                synchronized (removeEvents) {
                                    removeEvents.add(event);
                                }
                                event.onFinished();
                            }
                        } catch (Throwable e) {
                            logger.error("fatal error on event loop with event: {}", event, e);
                        }
                    }
                    eventBuffers.clear();
                    synchronized (removeEvents) {
                        for (EzyEventLoopEvent event : removeEvents) {
                            doRemoveEvent(event);
                        }
                        removeEvents.clear();
                    }
                    final long elapsedTime = System.currentTimeMillis() - startTime;
                    final long sleepTime = maxSleepTime - elapsedTime;
                    if (sleepTime > 0) {
                        try {
                            //noinspection BusyWait
                            Thread.sleep(sleepTime);
                        } catch (InterruptedException e) {
                            break;
                        }
                    }
                }
                synchronized (this) {
                    stopped.set(true);
                    shutdownFuture.setResult(true);
                }
            }
    
            public List shutdownAndGet() {
                active.set(false);
                synchronized (this) {
                    if (stopped.get()) {
                        shutdownFuture.setResult(true);
                    }
                }
                processSilently(shutdownFuture::get);
                return new ArrayList(events.values());
            }
        }
    
        private static final class ScheduledEvent implements EzyEventLoopEvent {
            private final long period;
            private final EzyEventLoopEvent event;
            private final AtomicLong nextFireTime = new AtomicLong();
    
            private ScheduledEvent(
                EzyEventLoopEvent event,
                long delayTime,
                long period
            ) {
                this.period = period;
                this.event = event;
                this.nextFireTime.set(
                    System.currentTimeMillis() + (delayTime <= 0 ? 0 : period)
                );
            }
    
            public boolean isNotFireTime() {
                return System.currentTimeMillis() < nextFireTime.get();
            }
    
            @Override
            public boolean call() {
                this.nextFireTime.addAndGet(period);
                return event.call();
            }
    
            @Override
            public void onFinished() {
                event.onFinished();
            }
    
            @Override
            public void onRemoved() {
                event.onRemoved();
            }
        }
    }
    
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

You must login to add an answer.

Continue with Google
Continue with Facebook
or use


Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 581
  • Answers 1k
  • Best Answers 63
  • Users 299
  • Popular
  • Answers
  • monkey

    [Deep Learning] Làm thế nào để xác định được cái ...

    • 16 Answers
  • Tú Trần Anh

    [Ezyfox Server] Unity game client không gửi được command khi ...

    • 12 Answers
  • monkey

    [Go] khi nào go func được gọi?

    • 10 Answers
  • Nguyễn Thái Sơn
    Nguyễn Thái Sơn added an answer em cảm ơn, vậy mỗi câu truy vấn luôn có… June 24, 2022 at 4:31 pm
  • tvd12
    tvd12 added an answer Việc chuyển này cũng có nhiều khó khăn là nó… June 24, 2022 at 3:08 pm
  • tvd12
    tvd12 added an answer 1. Vì socket là giữ kết nối nên em sẽ… June 24, 2022 at 3:02 pm

Related Questions

  • Nguyễn Thái Sơn

    về ezydata

    • 2 Answers
  • Nguyễn Thái Sơn

    [BadQuestion]thư viện ameria của Line

    • 1 Answer
  • Hiệp Đoàn

    Xây dựng hệ thống video call, livestream...

    • 3 Answers

Top Members

tvd12

tvd12

  • 65 Questions
  • 1k Points
Enlightened
monkey

monkey

  • 91 Questions
  • 620 Points
Enlightened
Nguyễn Thái Sơn

Nguyễn Thái Sơn

  • 148 Questions
  • 229 Points
Professional

Trending Tags

.net core abstract class analytics android ansible anti-flooding apache poi api async asyncawait atomicboolean backend backend nestjs bash script batch bean big project binding bitcoin blockchain blog boot-nodes branch british buffered build bundle c# cache caching callback career career path cast centos chat cloud cloud reliability commit company content-disposition contract cors cosmos css database datasource datastructure decentralized exchange deep learning design-pattern devops dex distraction programing docker download draw.io du học dữ liệu lớn eclip editor employee english erc20 erc721 eth ethereum ethereum login extensions exyfox ezyfox ezyfox-boot ezyfox-server ezyfoxserver ezyhttp facebook fe flutter freetank french front-end frontend fullstack fulltextsearch future game game-box game-room game-server get git go golang google grapql grpc guide hazelcast hibernate hibernateconfig html http https index indexing integration-test intellij interface interview io ipfs isolate issue it java javacore java core javascript java spring javaw java web job jpa js json jsp & servlet jvm jwt kafka keep promise kerberos keycloak kotlin language languague library load-balancing log log4j log4j-core login lưu trữ machine learning macos math maven merge messaging metamask microservice model mongo msgpack multiple tenant multithread multithreading mysql n naming naming convention netcore netty nft nft game nio nodejs non-blocking io opensource optimize orm pagination pancakeswap panic pgpool phỏng vấn pointer postgresql pre programming promise push message android python python unicode question queue rabbitmq reactive reactjs reactjs download recyclerview redis request resource rest roadmap ropssten ropsten rust rxjava schedule search security server shift jis singleton sjis slack smart contract socket soft delete sosanh spring spring-boot-test spring-jpa spring aop spring boot springboot spring data jpa spring redis spring security springsecurity springwebflux mysql sql sql server sse stackask storage stream structure trong spring boot system environment variables thread threadjava thymeleaf totp tracking location unit test unity upload file vector view volatile vue vue cli web3 web3 client webpack websocket windows 11 winforms work zookeeper

Footer

Stack Ask

Stack Ask is where Developers Ask & Answers. It will help you resolve any questions and connect you with other people.

About Us

  • Meet The Team
  • About Us
  • Contact Us

Legal Stuff

  • Terms of Service
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2021 Stack Ask. All Rights Reserved
Powered by youngmonkeys.org