├── .editorconfig ├── .gitattributes ├── .github ├── dependabot.yaml └── workflows │ └── workflow.yaml ├── .gitignore ├── LICENSE.txt ├── Makefile ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main └── java │ └── lol │ └── hub │ └── tinyeventbus │ ├── Bus.java │ ├── Cancelable.java │ └── Sub.java └── test └── java └── lol └── hub └── tinyeventbus ├── example ├── Example.java └── ReferenceLambdaExample.java └── tests ├── BenchmarkTests.java ├── BooleanEvent.java ├── CancelableEvent.java ├── ClassRegTests.java ├── ConcurrencyTest.java ├── Event.java ├── InstanceTests.java ├── MultiTest.java ├── OrderTest.java ├── RefTest.java ├── StaticTests.java ├── StressTests.java ├── TestEvent.java ├── ToggleEvent.java └── UniqueTest.java /.editorconfig: -------------------------------------------------------------------------------- 1 | # https://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | charset = utf-8 7 | end_of_line = lf 8 | indent_size = 4 9 | indent_style = space 10 | insert_final_newline = true 11 | trim_trailing_whitespace = true 12 | 13 | [*.md] 14 | trim_trailing_whitespace = false 15 | 16 | [*.{json, toml, xml, yml, yaml}] 17 | indent_size = 2 18 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | *.jar binary 3 | -------------------------------------------------------------------------------- /.github/dependabot.yaml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "gradle" 4 | directory: "/" 5 | schedule: 6 | interval: "daily" 7 | assignees: 8 | - "nothub" 9 | - package-ecosystem: "github-actions" 10 | directory: "/" 11 | schedule: 12 | interval: "daily" 13 | assignees: 14 | - "nothub" 15 | -------------------------------------------------------------------------------- /.github/workflows/workflow.yaml: -------------------------------------------------------------------------------- 1 | name: '🚔' 2 | on: push 3 | jobs: 4 | wrapper: 5 | name: 'Wrapper' 6 | runs-on: 'ubuntu-latest' 7 | steps: 8 | - uses: actions/checkout@v4 9 | - uses: gradle/actions/wrapper-validation@v4 10 | verify: 11 | name: 'Java ${{ matrix.java }}' 12 | runs-on: 'ubuntu-latest' 13 | strategy: 14 | matrix: 15 | java: [ 8, 11, 17, 21 ] 16 | fail-fast: true 17 | steps: 18 | - name: 'Claim the land' 19 | run: 'curl --header Accept:text/plain https://ipv4.games/claim?name=hub.lol 2> /dev/null || true' 20 | - uses: actions/checkout@v4 21 | - uses: actions/setup-java@v4 22 | with: 23 | java-version: '${{ matrix.java }}' 24 | distribution: 'temurin' 25 | check-latest: true 26 | cache: 'gradle' 27 | - run: 'make verify' 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !*/ 3 | 4 | !/src/** 5 | 6 | !/Makefile 7 | 8 | !/build.gradle 9 | !/settings.gradle 10 | !/gradle/wrapper/gradle-wrapper.jar 11 | !/gradle/wrapper/gradle-wrapper.properties 12 | !/gradlew 13 | !/gradlew.bat 14 | 15 | !/LICENSE.txt 16 | !/README.md 17 | 18 | !/.editorconfig 19 | !/.gitattributes 20 | !/.gitignore 21 | 22 | !/.github/**/*.yaml 23 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Florian Hübner 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | FLAGS = --console plain --full-stacktrace 2 | 3 | .PHONY: verify 4 | verify: 5 | ./gradlew $(FLAGS) check 6 | 7 | .PHONY: publish 8 | publish: 9 | ./gradlew $(FLAGS) publishToSonatype closeAndReleaseStagingRepository 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TinyEventBus 2 | 3 | [![maven central](https://maven-badges.herokuapp.com/maven-central/lol.hub/TinyEventBus/badge.svg)](https://search.maven.org/artifact/lol.hub/TinyEventBus) 4 | 5 | Tiny and fast pubsub implementation with subscriber priorities and event canceling for Java. 6 | 7 | --- 8 | 9 | ###### usage 10 | 11 | ```java 12 | void run() { 13 | Bus bus = new Bus(); 14 | bus.reg(Sub.of(String.class, System.out::println)); 15 | bus.pub("Hello World!"); 16 | } 17 | ``` 18 | 19 | ```java 20 | class Listenable { 21 | Sub sub = Sub.of(Long.class, l -> Foo.bar(l)); 22 | void run() { 23 | Bus bus = new Bus(); 24 | bus.reg(this); 25 | bus.pub(42L); 26 | } 27 | } 28 | ``` 29 | 30 | For more explanation, check 31 | the [example](https://github.com/nothub/TinyEventBus/blob/master/src/test/java/lol/hub/tinyeventbus/example/Example.java) 32 | . 33 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | import org.gradle.process.internal.ExecException 2 | 3 | plugins { 4 | id 'java-library' 5 | id 'maven-publish' 6 | id 'signing' 7 | id 'io.github.gradle-nexus.publish-plugin' version '1.3.0' 8 | } 9 | 10 | group = 'lol.hub' 11 | version = { -> 12 | def pattern = 'v[0-9]*' 13 | def fallback = 'indev' 14 | def result = new ByteArrayOutputStream() 15 | try { 16 | exec { 17 | commandLine 'git', 'describe', '--tags', '--abbrev=0', '--match', pattern 18 | ignoreExitValue = true 19 | standardOutput = result 20 | // void stderr 21 | errorOutput = new OutputStream() { 22 | @Override 23 | void write(int b) throws IOException {} 24 | } 25 | } 26 | } catch (ExecException ignored) { 27 | ignored.printStackTrace() 28 | println 'No git tag found with format \'' + pattern + '\', using fallback version identifier \'' + fallback + '\'.' 29 | return fallback 30 | } 31 | return result.toString().trim().replaceFirst('v', '') 32 | }() 33 | 34 | repositories { 35 | mavenCentral() 36 | } 37 | 38 | dependencies { 39 | compileOnly group: 'org.jetbrains', name: 'annotations', version: '24.1.0' 40 | testRuntimeOnly group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: '5.11.0' 41 | testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.11.0' 42 | testImplementation group: 'net.jodah', name: 'concurrentunit', version: '0.4.6' 43 | } 44 | 45 | java { 46 | toolchain.languageVersion = JavaLanguageVersion.of(21) 47 | withJavadocJar() 48 | withSourcesJar() 49 | } 50 | 51 | javadoc { 52 | options.addBooleanOption('html5', true) 53 | } 54 | 55 | tasks.withType(JavaCompile).configureEach { 56 | it.options.encoding = 'UTF-8' 57 | } 58 | 59 | test { 60 | useJUnitPlatform() 61 | } 62 | 63 | publishing { 64 | publications { 65 | mavenJava(MavenPublication) { 66 | from components.java 67 | pom { 68 | name = project.name 69 | description = 'Tiny and fast pubsub implementation with subscriber priorities and event canceling for Java.' 70 | licenses { 71 | license { 72 | name = 'MIT License' 73 | url = 'https://raw.githubusercontent.com/nothub/TinyEventBus/master/LICENSE.txt' 74 | } 75 | } 76 | developers { 77 | developer { 78 | name = 'hub' 79 | email = 'code@hub.lol' 80 | } 81 | } 82 | scm { 83 | connection = 'scm:git:git://github.com/nothub/TinyEventBus.git' 84 | developerConnection = 'scm:git:ssh://github.com/nothub/TinyEventBus.git' 85 | url = 'https://github.com/nothub/TinyEventBus' 86 | } 87 | } 88 | } 89 | } 90 | } 91 | 92 | signing { 93 | sign publishing.publications.mavenJava 94 | } 95 | 96 | nexusPublishing { 97 | repositories { 98 | sonatype { 99 | nexusUrl.set(uri("https://s01.oss.sonatype.org/service/local/")) 100 | snapshotRepositoryUrl.set(uri("https://s01.oss.sonatype.org/content/repositories/snapshots/")) 101 | } 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nothub/TinyEventBus/d669e11ef62c50247b8ad211eb1cc04865e9c6fe/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Stop when "xargs" is not available. 209 | if ! command -v xargs >/dev/null 2>&1 210 | then 211 | die "xargs is not available" 212 | fi 213 | 214 | # Use "xargs" to parse quoted args. 215 | # 216 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 217 | # 218 | # In Bash we could simply go: 219 | # 220 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 221 | # set -- "${ARGS[@]}" "$@" 222 | # 223 | # but POSIX shell has neither arrays nor command substitution, so instead we 224 | # post-process each arg (as a line of input to sed) to backslash-escape any 225 | # character that might be a shell metacharacter, then use eval to reverse 226 | # that process (while maintaining the separation between arguments), and wrap 227 | # the whole thing up as a single "set" statement. 228 | # 229 | # This will of course break if any of these variables contains a newline or 230 | # an unmatched quote. 231 | # 232 | 233 | eval "set -- $( 234 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 235 | xargs -n1 | 236 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 237 | tr '\n' ' ' 238 | )" '"$@"' 239 | 240 | exec "$JAVACMD" "$@" 241 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if %ERRORLEVEL% equ 0 goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if %ERRORLEVEL% equ 0 goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | set EXIT_CODE=%ERRORLEVEL% 84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 86 | exit /b %EXIT_CODE% 87 | 88 | :mainEnd 89 | if "%OS%"=="Windows_NT" endlocal 90 | 91 | :omega 92 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'TinyEventBus' 2 | -------------------------------------------------------------------------------- /src/main/java/lol/hub/tinyeventbus/Bus.java: -------------------------------------------------------------------------------- 1 | package lol.hub.tinyeventbus; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | 5 | import java.lang.reflect.Field; 6 | import java.util.Arrays; 7 | import java.util.Map; 8 | import java.util.Objects; 9 | import java.util.Set; 10 | import java.util.concurrent.ConcurrentHashMap; 11 | import java.util.concurrent.ConcurrentSkipListSet; 12 | import java.util.function.Function; 13 | import java.util.stream.Collectors; 14 | 15 | /** 16 | * Central event manager, used to publish events and, register/unregister subscribers. 17 | *
18 | * Any {@link Object} can be used to represent an event. 19 | * Events are identified by their {@link Class} type. 20 | *
21 | * Multiple {@link Sub}s can be registered to listen to one event type. 22 | * The processing order of registered {@link Sub}s is determined by their {@link Sub#priority}. 23 | * 24 | * @author nothub 25 | */ 26 | public class Bus { 27 | 28 | private final Map, ConcurrentSkipListSet>> subs = new ConcurrentHashMap<>(); 29 | 30 | @NotNull 31 | private static Set> getSubFields(Object parent) { 32 | return Arrays.stream(parent.getClass().getDeclaredFields()) 33 | .filter(field -> field.getType().equals(Sub.class)) 34 | .filter(field -> Sub.class.isAssignableFrom(field.getType())) 35 | .map(subFieldConverter(parent)) 36 | .filter(Objects::nonNull) 37 | .collect(Collectors.toSet()); 38 | } 39 | 40 | @NotNull 41 | private static Function> subFieldConverter(Object parent) { 42 | return field -> { 43 | boolean accessible = field.isAccessible(); 44 | field.setAccessible(true); 45 | try { 46 | return (Sub) field.get(parent); 47 | } catch (IllegalAccessException e) { 48 | e.printStackTrace(); 49 | return null; 50 | } finally { 51 | field.setAccessible(accessible); 52 | } 53 | }; 54 | } 55 | 56 | /** 57 | * Publishes an event. 58 | * If the published event implements the {@link Cancelable} interface, 59 | * additional processing can be stopped prematurely by any invoked {@link Sub}. 60 | * 61 | * @param event Event to be published. 62 | */ 63 | public void pub(Object event) { 64 | final ConcurrentSkipListSet> subs = this.subs.get(event.getClass()); 65 | if (subs == null) return; 66 | subs.forEach(sub -> { 67 | if (event instanceof Cancelable && ((Cancelable) event).isCanceled()) return; 68 | sub.accept(event); 69 | }); 70 | } 71 | 72 | /** 73 | * Registers a {@link Sub}. 74 | * 75 | * @param sub {@link Sub} to be registered. 76 | * @see #reg(Object) 77 | */ 78 | public void reg(Sub sub) { 79 | subs.computeIfAbsent(sub.topic, clazz -> new ConcurrentSkipListSet<>()).add(sub); 80 | } 81 | 82 | 83 | /** 84 | * Registers all {@link Sub} field members of the parent {@link Object}. 85 | * 86 | * @param parent Parent object of {@link Sub} field members to be registered. 87 | * @see #reg(Sub) 88 | */ 89 | public void reg(Object parent) { 90 | getSubFields(parent).forEach(this::reg); 91 | } 92 | 93 | 94 | /** 95 | * Unregisters a {@link Sub}. 96 | * 97 | * @param sub Subscriber to be unregistered. 98 | * @see #unreg(Object) 99 | */ 100 | public void unreg(Sub sub) { 101 | final ConcurrentSkipListSet> subs = this.subs.get(sub.topic); 102 | if (subs == null) return; 103 | subs.remove(sub); 104 | } 105 | 106 | 107 | /** 108 | * Unregisters all {@link Sub} field members of the parent {@link Object}. 109 | * 110 | * @param parent Parent object of {@link Sub} field members to be unregistered. 111 | * @see #unreg(Sub) 112 | */ 113 | public void unreg(Object parent) { 114 | getSubFields(parent).forEach(this::unreg); 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /src/main/java/lol/hub/tinyeventbus/Cancelable.java: -------------------------------------------------------------------------------- 1 | package lol.hub.tinyeventbus; 2 | 3 | /** 4 | * Events implementing this interface can be canceled while processed by the {@link Bus}. 5 | * If an Events {@link Cancelable#isCanceled()} method returns true, 6 | * subsequent subscribers listening to this event type will not be invoked. 7 | * 8 | * @author nothub 9 | */ 10 | public interface Cancelable { 11 | 12 | /** 13 | * @return Canceling state of the Event. 14 | */ 15 | boolean isCanceled(); 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/lol/hub/tinyeventbus/Sub.java: -------------------------------------------------------------------------------- 1 | package lol.hub.tinyeventbus; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | 5 | import java.util.function.Consumer; 6 | 7 | /** 8 | * Represents a registerable and unregisterable subscriber to events provided by {@link Bus}. 9 | *
10 | * Can be registered/unregistered directly with {@link Bus#reg(Sub)}/{@link Bus#unreg(Sub)} 11 | * or as field member of an {@link Object} with {@link Bus#reg(Object)}/{@link Bus#unreg(Object)}. 12 | * 13 | * @param Generically defined type of the event {@link Object} to be subscribed to. 14 | * @author nothub 15 | */ 16 | public class Sub implements Comparable> { 17 | 18 | /** 19 | * Priority of processing. 20 | * A {@link Sub} created without a specific priority value will be created with a default value of 0. 21 | * Can be defined in the range of {@link Integer#MAX_VALUE} to {@link Integer#MIN_VALUE}. 22 | */ 23 | public final int priority; 24 | 25 | /** 26 | * Consumer to be invoked when an event is received. 27 | * Accepts an object of the generically defined type as event to be processed. 28 | */ 29 | public final Consumer consumer; 30 | 31 | final Class topic; 32 | 33 | /** 34 | * Creates a {@link Sub} instance with manually defined event type. 35 | * 36 | * @param consumer Consumer to be invoked when an event is received. 37 | * @param priority Priority of processing. 38 | * @param topic Manually defined type of event to be subscribed to. 39 | * @see Sub#of(Class, Consumer, int) 40 | */ 41 | public Sub(Class topic, Consumer consumer, int priority) { 42 | this.priority = priority; 43 | this.consumer = consumer; 44 | this.topic = topic; 45 | } 46 | 47 | /** 48 | * Creates a {@link Sub} instance with manually defined event type. 49 | * 50 | * @param consumer Consumer to be invoked when an event is received. 51 | * @param topic Manually defined type of event to be subscribed to. 52 | * @see Sub#of(Class, Consumer) 53 | */ 54 | public Sub(Class topic, Consumer consumer) { 55 | this(topic, consumer, 0); 56 | } 57 | 58 | /** 59 | * Convenience method to create a {@link Sub} instance. 60 | * 61 | * @param consumer Consumer to be invoked when an event is received. 62 | * @param priority Priority of processing. 63 | * @param topic Manually defined type of event to be subscribed to. 64 | * @param Generically defined type of event to be subscribed to. 65 | * @return Created {@link Sub} instance. 66 | * @see Sub#Sub(Class, Consumer, int) 67 | */ 68 | public static Sub of(Class topic, Consumer consumer, int priority) { 69 | return new Sub<>(topic, consumer, priority); 70 | } 71 | 72 | /** 73 | * Convenience method to create a {@link Sub} instance. 74 | * 75 | * @param consumer Consumer to be invoked when an event is received. 76 | * @param topic Manually defined type of event to be subscribed to. 77 | * @param Generically defined type of event to be subscribed to. 78 | * @return Created {@link Sub} instance. 79 | * @see Sub#Sub(Class, Consumer) 80 | */ 81 | public static Sub of(Class topic, Consumer consumer) { 82 | return new Sub<>(topic, consumer); 83 | } 84 | 85 | void accept(Object event) { 86 | try { 87 | consumer.accept((T) event); 88 | } catch (ClassCastException e) { 89 | e.printStackTrace(); 90 | } 91 | } 92 | 93 | /** 94 | * {@inheritDoc} 95 | *
96 | * Compares this and the provided {@link Sub} as specified in {@link Comparable#compareTo(Object)} 97 | *
98 | * Subscribers are distinguished by comparing the following 3 characteristics in the listed order: 99 | *
    100 | *
  • {@link Sub#priority}
  • 101 | *
  • {@link Sub#consumer} (hashCode)
  • 102 | *
  • {@link Sub} (hashCode)
  • 103 | *
104 | * 105 | * @param sub the {@link Sub} to be compared. 106 | */ 107 | @Override 108 | public int compareTo(@NotNull Sub sub) { 109 | if (sub.priority != priority) { 110 | return Integer.compare(sub.priority, priority); 111 | } 112 | if (sub.consumer.hashCode() != consumer.hashCode()) { 113 | return Integer.compare(sub.consumer.hashCode(), consumer.hashCode()); 114 | } 115 | return Integer.compare(sub.hashCode(), hashCode()); 116 | } 117 | 118 | } 119 | -------------------------------------------------------------------------------- /src/test/java/lol/hub/tinyeventbus/example/Example.java: -------------------------------------------------------------------------------- 1 | package lol.hub.tinyeventbus.example; 2 | 3 | import lol.hub.tinyeventbus.Bus; 4 | import lol.hub.tinyeventbus.Cancelable; 5 | import lol.hub.tinyeventbus.Sub; 6 | 7 | import java.util.function.Consumer; 8 | 9 | class Example { 10 | 11 | // create event consumer 12 | final Consumer eventConsumer = e -> System.out.println(e.str); 13 | // create subscriber 14 | Sub sub = new Sub<>(Event.class, eventConsumer); 15 | // create subscriber with inline consumer 16 | Sub prioSub = new Sub<>(Event.class, e -> { 17 | if (e.str.equals("foobar")) e.canceled = true; 18 | }, 50); // priority is defined as integer 19 | // create subscriber with convenience method 20 | Sub highPrioSub = Sub.of(Event.class, e -> e.str = ":3", 100); // higher priority comes first 21 | 22 | void run() { 23 | 24 | // create bus instance 25 | Bus bus = new Bus(); 26 | 27 | // register subscriber 28 | bus.reg(sub); 29 | // publish event 30 | bus.pub(new Event("Hello World!")); 31 | // prints: Hello World! 32 | 33 | bus.reg(prioSub); 34 | bus.pub(new Event("foobar")); 35 | // event is canceled 36 | 37 | bus.reg(highPrioSub); 38 | bus.pub(new Event("foobar")); 39 | // prints: :3 40 | 41 | } 42 | 43 | static class Event implements Cancelable { 44 | 45 | String str; 46 | boolean canceled; 47 | 48 | Event(String str) { 49 | this.str = str; 50 | } 51 | 52 | @Override 53 | public boolean isCanceled() { 54 | return canceled; 55 | } 56 | 57 | } 58 | 59 | static class Main { 60 | public static void main(String[] args) { 61 | new Example().run(); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/test/java/lol/hub/tinyeventbus/example/ReferenceLambdaExample.java: -------------------------------------------------------------------------------- 1 | package lol.hub.tinyeventbus.example; 2 | 3 | import lol.hub.tinyeventbus.Bus; 4 | import lol.hub.tinyeventbus.Cancelable; 5 | import lol.hub.tinyeventbus.Sub; 6 | 7 | class ReferenceLambdaExample { 8 | 9 | Sub consumer = Sub.of(TestEvent.class, TestEvent::cancel); 10 | 11 | void run() { 12 | 13 | // create bus instance 14 | Bus bus = new Bus(); 15 | 16 | bus.reg(consumer); 17 | final TestEvent evB = new TestEvent(); 18 | bus.pub(evB); 19 | 20 | System.out.println(evB.canceled); 21 | // prints: true 22 | 23 | } 24 | 25 | abstract static class CancelableEvent implements Cancelable { 26 | 27 | boolean canceled; 28 | 29 | CancelableEvent() { 30 | } 31 | 32 | public void cancel() { 33 | this.canceled = true; 34 | } 35 | 36 | @Override 37 | public boolean isCanceled() { 38 | return canceled; 39 | } 40 | 41 | } 42 | 43 | public static class TestEvent extends CancelableEvent { 44 | } 45 | 46 | static class Main { 47 | public static void main(String[] args) { 48 | new ReferenceLambdaExample().run(); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/test/java/lol/hub/tinyeventbus/tests/BenchmarkTests.java: -------------------------------------------------------------------------------- 1 | package lol.hub.tinyeventbus.tests; 2 | 3 | import lol.hub.tinyeventbus.Bus; 4 | import lol.hub.tinyeventbus.Sub; 5 | import org.junit.jupiter.api.Assertions; 6 | import org.junit.jupiter.api.BeforeAll; 7 | import org.junit.jupiter.api.Test; 8 | import org.junit.jupiter.api.parallel.Execution; 9 | import org.junit.jupiter.api.parallel.ExecutionMode; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | import java.util.stream.IntStream; 14 | 15 | @Execution(ExecutionMode.SAME_THREAD) 16 | public class BenchmarkTests { 17 | 18 | private static Bus bus = new Bus(); 19 | private static int hits; 20 | 21 | @BeforeAll 22 | static void beforeAll() { 23 | System.out.println("java runtime: " + System.getProperty("java.runtime.version") + System.lineSeparator()); 24 | } 25 | 26 | void setUp() { 27 | bus = new Bus(); 28 | hits = 0; 29 | System.gc(); 30 | } 31 | 32 | @Test 33 | void test_0_reg() { 34 | reg(1_000); 35 | reg(10_000); 36 | } 37 | 38 | @Test 39 | void test_1_del() { 40 | del(1_000); 41 | del(10_000); 42 | } 43 | 44 | @Test 45 | void test_2_pub() { 46 | pub(1_000, 1_000); 47 | pub(100, 10_000); 48 | pub(10_000, 100); 49 | } 50 | 51 | void reg(int subs) { 52 | 53 | setUp(); 54 | 55 | System.out.println("benchmark: bus.reg"); 56 | 57 | System.out.println("subs: " + subs); 58 | 59 | List> listenerContainers = new ArrayList<>(); 60 | 61 | IntStream.range(0, subs).forEach(i -> listenerContainers.add(new Sub<>(String.class, s -> { 62 | }))); 63 | 64 | final long start = System.nanoTime(); 65 | 66 | IntStream 67 | .range(0, subs) 68 | .forEach(i -> bus.reg(listenerContainers.get(i))); 69 | 70 | final long end = System.nanoTime() - start; 71 | 72 | System.out.printf("%,dns (%,dms)" + System.lineSeparator() + System.lineSeparator(), end, end / 1000000); 73 | 74 | } 75 | 76 | void del(int subs) { 77 | 78 | setUp(); 79 | 80 | System.out.println("benchmark: bus.del"); 81 | 82 | System.out.println("subs: " + subs); 83 | 84 | List> listenerContainers = new ArrayList<>(); 85 | 86 | IntStream.range(0, subs).forEach(i -> listenerContainers.add(new Sub<>(String.class, s -> { 87 | }))); 88 | 89 | IntStream 90 | .range(0, subs) 91 | .forEach(i -> bus.reg(listenerContainers.get(i))); 92 | 93 | final long start = System.nanoTime(); 94 | 95 | IntStream 96 | .range(0, subs) 97 | .forEach(i -> bus.unreg(listenerContainers.get(i))); 98 | 99 | final long end = System.nanoTime() - start; 100 | 101 | System.out.printf("%,dns (%,dms)" + System.lineSeparator() + System.lineSeparator(), end, end / 1000000); 102 | 103 | } 104 | 105 | void pub(int pubs, int subs) { 106 | 107 | setUp(); 108 | 109 | System.out.println("benchmark: bus.pub"); 110 | 111 | System.out.println("pubs: " + pubs); 112 | System.out.println("subs: " + subs); 113 | 114 | List> listenerContainers = new ArrayList<>(); 115 | 116 | IntStream.range(0, subs).forEach(i -> listenerContainers.add(new Sub<>(String.class, s -> hits++))); 117 | 118 | IntStream 119 | .range(0, subs) 120 | .forEach(i -> bus.reg(listenerContainers.get(i))); 121 | 122 | final long start = System.nanoTime(); 123 | 124 | IntStream 125 | .range(0, pubs) 126 | .forEach(i -> bus.pub("")); 127 | 128 | final long end = System.nanoTime() - start; 129 | 130 | Assertions.assertEquals(subs * pubs, hits); 131 | 132 | System.out.printf("%,dns (%,dms)" + System.lineSeparator() + System.lineSeparator(), end, end / 1000000); 133 | 134 | } 135 | 136 | } 137 | -------------------------------------------------------------------------------- /src/test/java/lol/hub/tinyeventbus/tests/BooleanEvent.java: -------------------------------------------------------------------------------- 1 | package lol.hub.tinyeventbus.tests; 2 | 3 | class BooleanEvent extends Event { 4 | 5 | final boolean value; 6 | 7 | BooleanEvent(boolean value) { 8 | this.value = value; 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/test/java/lol/hub/tinyeventbus/tests/CancelableEvent.java: -------------------------------------------------------------------------------- 1 | package lol.hub.tinyeventbus.tests; 2 | 3 | import lol.hub.tinyeventbus.Cancelable; 4 | 5 | abstract class CancelableEvent extends Event implements Cancelable { 6 | 7 | boolean canceled; 8 | 9 | CancelableEvent() { 10 | } 11 | 12 | public void cancel() { 13 | this.canceled = true; 14 | } 15 | 16 | @Override 17 | public boolean isCanceled() { 18 | return canceled; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/lol/hub/tinyeventbus/tests/ClassRegTests.java: -------------------------------------------------------------------------------- 1 | package lol.hub.tinyeventbus.tests; 2 | 3 | import lol.hub.tinyeventbus.Bus; 4 | import lol.hub.tinyeventbus.Sub; 5 | import org.junit.jupiter.api.Assertions; 6 | import org.junit.jupiter.api.BeforeEach; 7 | import org.junit.jupiter.api.Test; 8 | import org.junit.jupiter.api.parallel.Execution; 9 | import org.junit.jupiter.api.parallel.ExecutionMode; 10 | 11 | @SuppressWarnings({"InnerClassMayBeStatic"}) 12 | @Execution(ExecutionMode.SAME_THREAD) 13 | class ClassRegTests { 14 | 15 | private static Bus bus = new Bus(); 16 | private static int hits; 17 | 18 | private Sub subPriv = Sub.of(BooleanEvent.class, e -> hits++); 19 | protected Sub subProt = Sub.of(BooleanEvent.class, e -> hits++); 20 | Sub sub = Sub.of(BooleanEvent.class, e -> hits++); 21 | private static Sub subStaticPriv = Sub.of(BooleanEvent.class, e -> hits++); 22 | protected static Sub subStaticProt = Sub.of(BooleanEvent.class, e -> hits++); 23 | static Sub subStatic = Sub.of(BooleanEvent.class, e -> hits++); 24 | 25 | @BeforeEach 26 | void setUp() { 27 | hits = 0; 28 | } 29 | 30 | @Test 31 | void clazz() { 32 | bus.reg(this); 33 | bus.pub(new BooleanEvent(true)); 34 | Assertions.assertEquals(6, hits); 35 | bus.unreg(this); 36 | bus.pub(new BooleanEvent(true)); 37 | Assertions.assertEquals(6, hits); 38 | } 39 | 40 | @Test 41 | void inner() { 42 | InnerClassPriv innerClassPriv = new InnerClassPriv(); 43 | InnerClassProt innerClassProt = new InnerClassProt(); 44 | InnerClass InnerClass = new InnerClass(); 45 | InnerFinalClass innerFinalClass = new InnerFinalClass(); 46 | InnerStaticClassPriv innerStaticClassPriv = new InnerStaticClassPriv(); 47 | InnerStaticClassProt innerStaticClassProt = new InnerStaticClassProt(); 48 | bus.reg(innerClassPriv); 49 | bus.reg(innerClassProt); 50 | bus.reg(InnerClass); 51 | bus.reg(innerFinalClass); 52 | bus.reg(innerStaticClassPriv); 53 | bus.reg(innerStaticClassProt); 54 | bus.reg(InnerStaticClassPriv2.subPriv); 55 | bus.reg(InnerStaticClassPriv2.subProt); 56 | bus.reg(InnerStaticClassPriv2.sub); 57 | bus.reg(InnerStaticClassProt2.subPriv); 58 | bus.reg(InnerStaticClassProt2.subProt); 59 | bus.reg(InnerStaticClassProt2.sub); 60 | bus.pub(new BooleanEvent(true)); 61 | Assertions.assertEquals(24, hits); 62 | bus.unreg(innerClassPriv); 63 | bus.unreg(innerClassProt); 64 | bus.unreg(InnerClass); 65 | bus.unreg(innerFinalClass); 66 | bus.unreg(innerStaticClassPriv); 67 | bus.unreg(innerStaticClassProt); 68 | bus.unreg(InnerStaticClassPriv2.subPriv); 69 | bus.unreg(InnerStaticClassPriv2.subProt); 70 | bus.unreg(InnerStaticClassPriv2.sub); 71 | bus.unreg(InnerStaticClassProt2.subPriv); 72 | bus.unreg(InnerStaticClassProt2.subProt); 73 | bus.unreg(InnerStaticClassProt2.sub); 74 | bus.pub(new BooleanEvent(true)); 75 | Assertions.assertEquals(24, hits); 76 | } 77 | 78 | private class InnerClassPriv { 79 | private Sub subPriv = Sub.of(BooleanEvent.class, e -> hits++); 80 | protected Sub subProt = Sub.of(BooleanEvent.class, e -> hits++); 81 | Sub sub = Sub.of(BooleanEvent.class, e -> hits++); 82 | } 83 | 84 | protected class InnerClassProt { 85 | private Sub subPriv = Sub.of(BooleanEvent.class, e -> hits++); 86 | protected Sub subProt = Sub.of(BooleanEvent.class, e -> hits++); 87 | Sub sub = Sub.of(BooleanEvent.class, e -> hits++); 88 | } 89 | 90 | class InnerClass { 91 | private Sub subPriv = Sub.of(BooleanEvent.class, e -> hits++); 92 | protected Sub subProt = Sub.of(BooleanEvent.class, e -> hits++); 93 | Sub sub = Sub.of(BooleanEvent.class, e -> hits++); 94 | } 95 | 96 | final class InnerFinalClass { 97 | private Sub subPriv = Sub.of(BooleanEvent.class, e -> hits++); 98 | protected Sub subProt = Sub.of(BooleanEvent.class, e -> hits++); 99 | Sub sub = Sub.of(BooleanEvent.class, e -> hits++); 100 | } 101 | 102 | private static class InnerStaticClassPriv { 103 | private Sub subPriv = Sub.of(BooleanEvent.class, e -> hits++); 104 | protected Sub subProt = Sub.of(BooleanEvent.class, e -> hits++); 105 | Sub sub = Sub.of(BooleanEvent.class, e -> hits++); 106 | } 107 | 108 | protected static class InnerStaticClassProt { 109 | private Sub subPriv = Sub.of(BooleanEvent.class, e -> hits++); 110 | protected Sub subProt = Sub.of(BooleanEvent.class, e -> hits++); 111 | Sub sub = Sub.of(BooleanEvent.class, e -> hits++); 112 | } 113 | 114 | private static class InnerStaticClassPriv2 { 115 | private static final Sub subPriv = Sub.of(BooleanEvent.class, e -> hits++); 116 | protected static Sub subProt = Sub.of(BooleanEvent.class, e -> hits++); 117 | static Sub sub = Sub.of(BooleanEvent.class, e -> hits++); 118 | } 119 | 120 | protected static class InnerStaticClassProt2 { 121 | private static final Sub subPriv = Sub.of(BooleanEvent.class, e -> hits++); 122 | protected static Sub subProt = Sub.of(BooleanEvent.class, e -> hits++); 123 | static Sub sub = Sub.of(BooleanEvent.class, e -> hits++); 124 | } 125 | 126 | } 127 | -------------------------------------------------------------------------------- /src/test/java/lol/hub/tinyeventbus/tests/ConcurrencyTest.java: -------------------------------------------------------------------------------- 1 | package lol.hub.tinyeventbus.tests; 2 | 3 | import lol.hub.tinyeventbus.Bus; 4 | import lol.hub.tinyeventbus.Sub; 5 | import net.jodah.concurrentunit.Waiter; 6 | import org.junit.jupiter.api.Assertions; 7 | import org.junit.jupiter.api.Test; 8 | import org.junit.jupiter.api.parallel.Execution; 9 | import org.junit.jupiter.api.parallel.ExecutionMode; 10 | 11 | import java.util.concurrent.TimeoutException; 12 | import java.util.concurrent.atomic.AtomicBoolean; 13 | import java.util.stream.IntStream; 14 | 15 | @Execution(ExecutionMode.CONCURRENT) 16 | class ConcurrencyTest { 17 | 18 | private final Bus bus = new Bus(); 19 | private final Waiter waiter = new Waiter(); 20 | 21 | private int hitsA = 0; 22 | private int hitsB = 0; 23 | private int hitsC = 0; 24 | private int hitsD = 0; 25 | 26 | private final Sub sub = Sub.of(Integer.class, i -> { 27 | waiter.assertEquals(i, hitsB); 28 | hitsB++; 29 | hitsD++; 30 | waiter.assertTrue(hitsC < hitsD); 31 | waiter.resume(); 32 | }); 33 | 34 | @Test 35 | void test() throws TimeoutException, InterruptedException { 36 | bus.reg(sub); 37 | IntStream.range(0, 1000).forEach(i -> { 38 | bus.pub(hitsA); 39 | hitsA++; 40 | hitsC++; 41 | }); 42 | waiter.await(1000, 1000); 43 | } 44 | 45 | @Test 46 | void spam() { 47 | AtomicBoolean invoked = new AtomicBoolean(false); 48 | bus.reg(Sub.of(Boolean.class, invoked::set)); 49 | IntStream.range(0, 1000).forEach(i -> { 50 | bus.pub(true); 51 | Assertions.assertTrue(invoked.get()); 52 | invoked.set(false); 53 | }); 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /src/test/java/lol/hub/tinyeventbus/tests/Event.java: -------------------------------------------------------------------------------- 1 | package lol.hub.tinyeventbus.tests; 2 | 3 | public abstract class Event { 4 | } 5 | -------------------------------------------------------------------------------- /src/test/java/lol/hub/tinyeventbus/tests/InstanceTests.java: -------------------------------------------------------------------------------- 1 | package lol.hub.tinyeventbus.tests; 2 | 3 | import lol.hub.tinyeventbus.Bus; 4 | import lol.hub.tinyeventbus.Sub; 5 | import org.junit.jupiter.api.Assertions; 6 | import org.junit.jupiter.api.BeforeAll; 7 | import org.junit.jupiter.api.Test; 8 | import org.junit.jupiter.api.parallel.Execution; 9 | import org.junit.jupiter.api.parallel.ExecutionMode; 10 | 11 | @Execution(ExecutionMode.SAME_THREAD) 12 | class InstanceTests { 13 | 14 | private static Bus bus; 15 | private static boolean invoked; 16 | 17 | Sub sub = Sub.of(BooleanEvent.class, e -> invoked = e.value); 18 | 19 | @BeforeAll 20 | static void setUp() { 21 | bus = new Bus(); 22 | invoked = false; 23 | } 24 | 25 | @Test 26 | void reg() { 27 | bus.reg(sub); 28 | bus.pub(new BooleanEvent(true)); 29 | Assertions.assertTrue(invoked); 30 | } 31 | 32 | @Test 33 | void del() { 34 | bus.unreg(sub); 35 | bus.pub(new BooleanEvent(true)); 36 | Assertions.assertFalse(invoked); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/test/java/lol/hub/tinyeventbus/tests/MultiTest.java: -------------------------------------------------------------------------------- 1 | package lol.hub.tinyeventbus.tests; 2 | 3 | import lol.hub.tinyeventbus.Bus; 4 | import lol.hub.tinyeventbus.Sub; 5 | import org.junit.jupiter.api.Assertions; 6 | import org.junit.jupiter.api.BeforeEach; 7 | import org.junit.jupiter.api.Test; 8 | import org.junit.jupiter.api.parallel.Execution; 9 | import org.junit.jupiter.api.parallel.ExecutionMode; 10 | 11 | @Execution(ExecutionMode.SAME_THREAD) 12 | class MultiTest { 13 | 14 | private static Bus bus = new Bus(); 15 | private static int hits; 16 | 17 | private final Sub sub = new Sub<>(Object.class, o -> hits++); 18 | 19 | private static final Sub subStatic = Sub.of(Object.class, o -> hits++); 20 | 21 | @BeforeEach 22 | void setUp() { 23 | bus = new Bus(); 24 | hits = 0; 25 | } 26 | 27 | @Test 28 | void reg() { 29 | bus.reg(sub); 30 | bus.reg(sub); 31 | bus.pub(new Object()); 32 | Assertions.assertEquals(1, hits); 33 | } 34 | 35 | @Test 36 | void regStatic() { 37 | bus.reg(subStatic); 38 | bus.reg(subStatic); 39 | bus.pub(new Object()); 40 | Assertions.assertEquals(1, hits); 41 | } 42 | 43 | @Test 44 | void regInline() { 45 | bus.reg(new Sub<>(Object.class, o -> hits++)); 46 | bus.reg(Sub.of(Object.class, o -> hits++)); 47 | bus.pub(new Object()); 48 | Assertions.assertEquals(2, hits); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /src/test/java/lol/hub/tinyeventbus/tests/OrderTest.java: -------------------------------------------------------------------------------- 1 | package lol.hub.tinyeventbus.tests; 2 | 3 | import lol.hub.tinyeventbus.Bus; 4 | import lol.hub.tinyeventbus.Sub; 5 | import org.junit.jupiter.api.Assertions; 6 | import org.junit.jupiter.api.BeforeAll; 7 | import org.junit.jupiter.api.Test; 8 | 9 | class OrderTest { 10 | 11 | private static Bus bus; 12 | private static String str; 13 | 14 | Sub subC1 = new Sub<>(Object.class, e -> str += "C"); 15 | Sub subC2 = Sub.of(Object.class, e -> str += "C"); 16 | Sub subE = new Sub<>(Object.class, e -> str += "E", -2); 17 | Sub subA = Sub.of(Object.class, e -> str += "A", 2); 18 | Sub subB = Sub.of(Object.class, e -> str += "B", 1); 19 | Sub subD = new Sub<>(Object.class, e -> str += "D", -1); 20 | 21 | @BeforeAll 22 | static void setUp() { 23 | bus = new Bus(); 24 | str = ""; 25 | } 26 | 27 | @Test 28 | void order() { 29 | bus.reg(subC1); 30 | bus.reg(subC2); 31 | bus.reg(subE); 32 | bus.reg(subA); 33 | bus.reg(subB); 34 | bus.reg(subD); 35 | bus.pub(new Object()); 36 | Assertions.assertEquals("ABCCDE", str); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/test/java/lol/hub/tinyeventbus/tests/RefTest.java: -------------------------------------------------------------------------------- 1 | package lol.hub.tinyeventbus.tests; 2 | 3 | import lol.hub.tinyeventbus.Bus; 4 | import lol.hub.tinyeventbus.Sub; 5 | import org.junit.jupiter.api.Assertions; 6 | import org.junit.jupiter.api.Test; 7 | import org.junit.jupiter.api.parallel.Execution; 8 | import org.junit.jupiter.api.parallel.ExecutionMode; 9 | 10 | @Execution(ExecutionMode.SAME_THREAD) 11 | class RefTest { 12 | 13 | private final Bus bus = new Bus(); 14 | 15 | @Test 16 | void simple() { 17 | //noinspection Convert2MethodRef 18 | bus.reg(new Sub(TestEvent.class, e -> e.cancel())); 19 | final TestEvent evA = new TestEvent(); 20 | bus.pub(evA); 21 | Assertions.assertTrue(evA.isCanceled()); 22 | } 23 | 24 | @Test 25 | void simpleOf() { 26 | //noinspection Convert2MethodRef 27 | Sub sub = Sub.of(TestEvent.class, e -> e.cancel()); 28 | bus.reg(sub); 29 | final TestEvent ev = new TestEvent(); 30 | bus.pub(ev); 31 | Assertions.assertTrue(ev.isCanceled()); 32 | } 33 | 34 | @Test 35 | void simpleOfInline() { 36 | //noinspection Convert2MethodRef 37 | bus.reg(Sub.of(TestEvent.class, e -> e.cancel())); 38 | final TestEvent ev = new TestEvent(); 39 | bus.pub(ev); 40 | Assertions.assertTrue(ev.isCanceled()); 41 | } 42 | 43 | @Test 44 | void refNonWonky() { 45 | bus.reg(new Sub<>(ToggleEvent.class, ToggleEvent::flip)); 46 | final ToggleEvent ev = new ToggleEvent(); 47 | bus.pub(ev); 48 | Assertions.assertTrue(ev.state); 49 | } 50 | 51 | @Test 52 | void refWonky() { 53 | bus.reg(new Sub<>(ToggleEvent.class, ToggleEvent::cancel)); 54 | final ToggleEvent ev = new ToggleEvent(); 55 | bus.pub(ev); 56 | Assertions.assertTrue(ev.isCanceled()); 57 | } 58 | 59 | @Test 60 | void ref() { 61 | bus.reg(new Sub<>(TestEvent.class,TestEvent::cancel)); 62 | final TestEvent ev = new TestEvent(); 63 | bus.pub(ev); 64 | Assertions.assertTrue(ev.isCanceled()); 65 | } 66 | 67 | @Test 68 | void refCancelableEvent() { 69 | bus.reg(new Sub(TestEvent.class, CancelableEvent::cancel)); 70 | final TestEvent ev = new TestEvent(); 71 | bus.pub(ev); 72 | Assertions.assertTrue(ev.isCanceled()); 73 | } 74 | 75 | @Test 76 | void refOf() { 77 | Sub sub = Sub.of(TestEvent.class, TestEvent::cancel); 78 | bus.reg(sub); 79 | final TestEvent ev = new TestEvent(); 80 | bus.pub(ev); 81 | Assertions.assertTrue(ev.isCanceled()); 82 | } 83 | 84 | @Test 85 | void refOfCancelableEvent() { 86 | Sub sub = Sub.of(TestEvent.class, CancelableEvent::cancel); 87 | bus.reg(sub); 88 | final TestEvent ev = new TestEvent(); 89 | bus.pub(ev); 90 | Assertions.assertTrue(ev.isCanceled()); 91 | } 92 | 93 | @Test 94 | void refOfInline() { 95 | bus.reg(Sub.of(TestEvent.class, TestEvent::cancel)); 96 | final TestEvent ev = new TestEvent(); 97 | bus.pub(ev); 98 | Assertions.assertTrue(ev.isCanceled()); 99 | } 100 | 101 | @Test 102 | void refOfInlineCancelableEvent() { 103 | bus.reg(Sub.of(TestEvent.class, CancelableEvent::cancel)); 104 | final TestEvent ev = new TestEvent(); 105 | bus.pub(ev); 106 | Assertions.assertTrue(ev.isCanceled()); 107 | } 108 | 109 | } 110 | -------------------------------------------------------------------------------- /src/test/java/lol/hub/tinyeventbus/tests/StaticTests.java: -------------------------------------------------------------------------------- 1 | package lol.hub.tinyeventbus.tests; 2 | 3 | import lol.hub.tinyeventbus.Bus; 4 | import lol.hub.tinyeventbus.Sub; 5 | import org.junit.jupiter.api.Assertions; 6 | import org.junit.jupiter.api.BeforeAll; 7 | import org.junit.jupiter.api.Test; 8 | import org.junit.jupiter.api.parallel.Execution; 9 | import org.junit.jupiter.api.parallel.ExecutionMode; 10 | 11 | @Execution(ExecutionMode.SAME_THREAD) 12 | class StaticTests { 13 | 14 | private static Bus bus; 15 | private static boolean invoked; 16 | 17 | Sub sub = new Sub<>(BooleanEvent.class, e -> invoked = e.value, 0); 18 | 19 | @BeforeAll 20 | static void setUp() { 21 | bus = new Bus(); 22 | invoked = false; 23 | } 24 | 25 | @Test 26 | void reg() { 27 | bus.reg(sub); 28 | bus.pub(new BooleanEvent(true)); 29 | Assertions.assertTrue(invoked); 30 | } 31 | 32 | @Test 33 | void del() { 34 | bus.unreg(sub); 35 | bus.pub(new BooleanEvent(true)); 36 | Assertions.assertFalse(invoked); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/test/java/lol/hub/tinyeventbus/tests/StressTests.java: -------------------------------------------------------------------------------- 1 | package lol.hub.tinyeventbus.tests; 2 | 3 | import lol.hub.tinyeventbus.Bus; 4 | import lol.hub.tinyeventbus.Sub; 5 | import org.junit.jupiter.api.Assertions; 6 | import org.junit.jupiter.api.BeforeEach; 7 | import org.junit.jupiter.api.DisplayName; 8 | import org.junit.jupiter.api.Test; 9 | import org.junit.jupiter.api.parallel.Execution; 10 | import org.junit.jupiter.api.parallel.ExecutionMode; 11 | 12 | import java.util.stream.IntStream; 13 | 14 | @Execution(ExecutionMode.SAME_THREAD) 15 | class StressTests { 16 | 17 | private static Bus bus; 18 | private static int hits; 19 | 20 | @BeforeEach 21 | void setUp() { 22 | bus = new Bus(); 23 | hits = 0; 24 | } 25 | 26 | Sub subA = Sub.of(Object.class, o -> hits++, Integer.MAX_VALUE); 27 | Sub subB = new Sub<>(Object.class, o -> hits++, 42); 28 | Sub subC = Sub.of(Object.class, o -> hits++); 29 | Sub subD = new Sub<>(Object.class, o -> hits++, -42); 30 | Sub subE = Sub.of(Object.class, o -> hits++, Integer.MIN_VALUE); 31 | 32 | @Test 33 | @DisplayName("pub 2m") 34 | void pub_() { 35 | final int runs = 2_000_000; 36 | bus.reg(subA); 37 | bus.reg(subB); 38 | bus.reg(subC); 39 | bus.reg(subD); 40 | bus.reg(subE); 41 | IntStream 42 | .range(0, runs) 43 | .forEach(i -> bus.pub(new Object())); 44 | Assertions.assertEquals(5 * runs, hits); 45 | } 46 | 47 | @Test 48 | @DisplayName("reg+pub 100k") 49 | void regpub() { 50 | final int runs = 100_000; 51 | IntStream 52 | .range(0, runs) 53 | .forEach(i -> { 54 | bus.reg(subA); 55 | bus.reg(subB); 56 | bus.reg(subC); 57 | bus.reg(subD); 58 | bus.reg(subE); 59 | bus.pub(new Object()); 60 | }); 61 | Assertions.assertEquals(5 * runs, hits); 62 | } 63 | 64 | @Test 65 | @DisplayName("reg+pub+del 10k") 66 | void regdelpub() { 67 | final int runs = 10_000; 68 | IntStream 69 | .range(0, runs) 70 | .forEach(i -> { 71 | bus.reg(subA); 72 | bus.reg(subB); 73 | bus.reg(subC); 74 | bus.reg(subD); 75 | bus.reg(subE); 76 | bus.pub(new Object()); 77 | bus.unreg(subA); 78 | bus.unreg(subB); 79 | bus.unreg(subC); 80 | bus.unreg(subD); 81 | bus.unreg(subE); 82 | }); 83 | Assertions.assertEquals(5 * runs, hits); 84 | } 85 | 86 | } 87 | -------------------------------------------------------------------------------- /src/test/java/lol/hub/tinyeventbus/tests/TestEvent.java: -------------------------------------------------------------------------------- 1 | package lol.hub.tinyeventbus.tests; 2 | 3 | public class TestEvent extends CancelableEvent { 4 | } 5 | -------------------------------------------------------------------------------- /src/test/java/lol/hub/tinyeventbus/tests/ToggleEvent.java: -------------------------------------------------------------------------------- 1 | package lol.hub.tinyeventbus.tests; 2 | 3 | public class ToggleEvent extends CancelableEvent { 4 | public boolean state = false; 5 | 6 | void flip() { 7 | state = !state; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/test/java/lol/hub/tinyeventbus/tests/UniqueTest.java: -------------------------------------------------------------------------------- 1 | package lol.hub.tinyeventbus.tests; 2 | 3 | import lol.hub.tinyeventbus.Bus; 4 | import lol.hub.tinyeventbus.Sub; 5 | import org.junit.jupiter.api.Assertions; 6 | import org.junit.jupiter.api.BeforeEach; 7 | import org.junit.jupiter.api.Test; 8 | import org.junit.jupiter.api.parallel.Execution; 9 | import org.junit.jupiter.api.parallel.ExecutionMode; 10 | 11 | @Execution(ExecutionMode.SAME_THREAD) 12 | class UniqueTest { 13 | 14 | private static Bus bus; 15 | private static int hits; 16 | 17 | @BeforeEach 18 | void setUp() { 19 | bus = new Bus(); 20 | hits = 0; 21 | } 22 | 23 | Sub sub = new Sub<>(Object.class, o -> hits++); 24 | 25 | @Test 26 | void multireg_a() { 27 | bus.reg(sub); 28 | bus.reg(sub); 29 | bus.pub(new Object()); 30 | Assertions.assertEquals(1, hits); 31 | } 32 | 33 | @Test 34 | void multireg_b() { 35 | bus.reg(new Sub<>(Object.class, o -> hits++)); 36 | bus.reg(new Sub<>(Object.class, o -> hits++)); 37 | bus.reg(Sub.of(Object.class, o -> hits++)); 38 | bus.reg(Sub.of(Object.class, o -> hits++)); 39 | bus.pub(new Object()); 40 | Assertions.assertEquals(4, hits); 41 | } 42 | 43 | } 44 | --------------------------------------------------------------------------------