pax_global_header00006660000000000000000000000064132261102030014500gustar00rootroot0000000000000052 comment=4010c2dea195bcde2ba71e8c21fd3d37eead68e2 Java-Thread-Affinity-affinity-3.1.7/000077500000000000000000000000001322611020300171545ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/.gitignore000077500000000000000000000004041322611020300211450ustar00rootroot00000000000000*.class # Package Files # *.jar *.war *.ear # IntelliJ *.iml *.ipr *.iws .idea # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* # Eclipse .classpath .project .settings/ # maven target # vim *.swp *.swo Java-Thread-Affinity-affinity-3.1.7/LICENSE000066400000000000000000000261351322611020300201700ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2014-2018 Chronicle Software Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Java-Thread-Affinity-affinity-3.1.7/README.md000066400000000000000000000151271322611020300204410ustar00rootroot00000000000000Thread Affinity ============= [![Maven Central](https://maven-badges.herokuapp.com/maven-central/net.openhft/affinity/badge.svg)](https://maven-badges.herokuapp.com/maven-central/net.openhft/affinity) Lets you bind a thread to a given core, this can improve performance (this library works best on linux). OpenHFT Java Thread Affinity library See [affinity/src/test/java](https://github.com/OpenHFT/Java-Thread-Affinity/tree/master/affinity/src/test/java) for working examples of how to use this library. [Thread Affinity usage Heatmap](http://jrvis.com/red-dwarf/?user=openhft&repo=Java-Thread-Affinity) ## Changes - V3.1.1 - Upgraded JNA dependency to 4.4.0 - V2.0.1 - Added getThreadId for the process if of the thread. ## Dependencies Java-Thread-Affinity will try to use [JNA](https://github.com/java-native-access/jna) to provide access to native thread-handling functions. JNA should be installed on your system to get the most from this library. ### JNA version Java-Thread-Affinity currently depends on JNA version 4.4.0, which in turn depends on a version of GLIBC >= 2.14. If your operating system is an old one, with a version of GLIBC released before 2011, this library will not be able to invoke native functions. To work around this problem, fork the repository, and override the `` tag for the artifacts `jna` and `jna-platform` in the project's `pom` file. ### Installing JNA on Ubuntu sudo apt-get install libjna-java ### Installing JNA on CentOS sudo yum install jna ## How does CPU allocation work? The library will read your `/proc/cpuinfo` if you have one or provide one and it will determine your CPU layout. If you don't have one it will assume every CPU is on one CPU socket. The library looks for isolated CPUs determined by looking at the CPUs you are not running on by default. i.e. if you have 16 CPUs but 8 of them are not available for general use (as determined by the affinity of the process on startup) it will start assigning to those CPUs. Note: if you have more than one process using this library you need to specify which CPUs the process can use otherwise it will assign the same CPUs to both processes. To control which CPUs a process can use, add -Daffinity.reserved={cpu-mask-in-hex} to the command line of the process. Note: the CPU 0 is reserved for the Operating System, it has to run somewhere. ## References https://github.com/peter-lawrey/Java-Thread-Affinity/wiki/Getting-started https://github.com/peter-lawrey/Java-Thread-Affinity/wiki/How-it-works http://vanillajava.blogspot.co.uk/2013/07/micro-jitter-busy-waiting-and-binding.html ## isolcpus Java-Thread-Affinity requires that you first isolate some CPU's. Once a CPU core is isolated, the Linux scheduler will not use the CPU core to run any user-space processes. The isolated CPUs will not participate in load balancing, and will not have tasks running on them unless explicitly assigned. To isolate the 1st and 3rd CPU cores (CPU numbers start from 0) on your system, add the following to the kernel command line during boot: isolcpus=1,3 ## Acquiring a CPU lock for a thread You can acquire a lock for a CPU in the following matter In Java 6 AffinityLock al = AffinityLock.acquireLock(); try { // do some work locked to a CPU. } finally { al.release(); } In Java 7 or 8 try (AffinityLock al = AffinityLock.acquireLock()) { // do some work while locked to a CPU. } You have further options such as ## Acquiring a CORE lock for a thread You can reserve a whole core. If you have hyper-threading enabled, this will use one CPU and leave it's twin CPU unused. try (AffinityLock al = AffinityLock.acquireCore()) { // do some work while locked to a CPU. } ## Controlling layout You can chose a layout relative to an existing lock. try (final AffinityLock al = AffinityLock.acquireLock()) { System.out.println("Main locked"); Thread t = new Thread(new Runnable() { @Override public void run() { try (AffinityLock al2 = al.acquireLock(AffinityStrategies.SAME_SOCKET, AffinityStrategies.ANY)) { System.out.println("Thread-0 locked"); } } }); t.start(); } In this example, the library will prefer a free CPU on the same Socket as the first thread, otherwise it will pick any free CPU. ## Getting the thread id. You can get the current thread id using int threadId = AffinitySupport.getThreadId(); ## Determining which CPU you are running on. You can get the current CPU being used by int cpuId = AffinitySupport.getCpu(); ## Controlling the affinity more directly. The affinity of the process on start up is long baseAffinity = AffinityLock.BASE_AFFINITY; The available CPU for reservation is long reservedAffinity = AffinityLock.RESERVED_AFFINITY; If you want to get/set the affinity directly you can do long currentAffinity = AffinitySupport.getAffinity(); AffinitySupport.setAffinity(1L << 5); // lock to CPU 5. ## Debugging affinity state For a detailed of view of the current affinity state (as seen by the library), execute the following script on Linux systems: ``` # change to the affinity lock-file directory (defaults to system property java.io.tmpdir) $ cd /tmp # dump affinity state $ for i in "$(ls cpu-*)"; do PID="$(cat $i | head -n1)"; TIMESTAMP="$(cat $i | tail -n1)"; echo "pid $PID locked at $TIMESTAMP in $i"; taskset -cp $PID; cat "/proc/$PID/cmdline"; echo; echo done pid 14584 locked at 2017.10.30 at 10:33:24 GMT in cpu-3.lock pid 14584's current affinity list: 3 /opt/jdk1.8.0_141/bin/java ... ``` # Support Material [Java Thread Affinity support group](https://groups.google.com/forum/?hl=en-GB#!forum/java-thread-affinity) For an article on how much difference affinity can make and how to use it http://vanillajava.blogspot.com/2013/07/micro-jitter-busy-waiting-and-binding.html # Questions and Answers ## Question I am currently working on a project related to deadlock detection in multithreaded programs in java. We are trying to run threads on different processors and thus came across your github posts regarding the same. https://github.com/peter-lawrey/Java-Thread-Affinity/wiki/Getting-started Being a beginner, I have little knowledge and thus need your assistance. We need to know how to run threads on specified cpu number and then switch threads when one is waiting. ## Answer Use : ``` java AffinityLock.setAffinity (1L << n); ``` where n is the cpu you want to run the thread on. Java-Thread-Affinity-affinity-3.1.7/affinity-test/000077500000000000000000000000001322611020300217425ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity-test/pom.xml000077500000000000000000000154021322611020300232640ustar00rootroot00000000000000 net.openhft java-parent-pom 1.1.13 4.0.0 affinity-test 3.1.1-SNAPSHOT bundle OpenHFT/Java-Thread-Affinity/affinity-test Java Thread Affinity library UTF-8 net.openhft third-party-bom pom 3.6.0 import net.openhft affinity ${project.version} com.sun.java tools net.openhft affinity javax.inject javax.inject test org.osgi org.osgi.core test org.osgi org.osgi.compendium test org.ops4j.pax.exam pax-exam-container-native test org.ops4j.pax.exam pax-exam-junit4 test org.ops4j.pax.exam pax-exam-link-mvn test org.ops4j.pax.url pax-url-aether test org.ops4j.pax.url pax-url-reference test org.apache.felix org.apache.felix.framework 4.4.1 test org.slf4j slf4j-api test org.slf4j slf4j-simple test org.apache.maven.plugins maven-compiler-plugin 3.6.2 -Xlint:deprecation 1.8 1.8 UTF-8 org.apache.servicemix.tooling depends-maven-plugin generate-depends-file generate-depends-file org.apache.felix maven-bundle-plugin true ${project.groupId}.${project.artifactId} ${project.artifactId} net.openhft.affinity.osgi * manifest scm:git:https://github.com/OpenHFT/Java-Thread-Affinity.git Java-Thread-Affinity-affinity-3.1.7/affinity-test/src/000077500000000000000000000000001322611020300225315ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity-test/src/main/000077500000000000000000000000001322611020300234555ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity-test/src/main/java/000077500000000000000000000000001322611020300243765ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity-test/src/main/java/net/000077500000000000000000000000001322611020300251645ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity-test/src/main/java/net/openhft/000077500000000000000000000000001322611020300266275ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity-test/src/main/java/net/openhft/affinity/000077500000000000000000000000001322611020300304405ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity-test/src/main/java/net/openhft/affinity/osgi/000077500000000000000000000000001322611020300314015ustar00rootroot00000000000000OSGiPlaceholder.java000066400000000000000000000013421322611020300351310ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity-test/src/main/java/net/openhft/affinity/osgi/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity.osgi; /** * A placeholder to have some plugin works */ public class OSGiPlaceholder { } Java-Thread-Affinity-affinity-3.1.7/affinity-test/src/test/000077500000000000000000000000001322611020300235105ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity-test/src/test/java/000077500000000000000000000000001322611020300244315ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity-test/src/test/java/net/000077500000000000000000000000001322611020300252175ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity-test/src/test/java/net/openhft/000077500000000000000000000000001322611020300266625ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity-test/src/test/java/net/openhft/affinity/000077500000000000000000000000001322611020300304735ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity-test/src/test/java/net/openhft/affinity/osgi/000077500000000000000000000000001322611020300314345ustar00rootroot00000000000000OSGiBundleTest.java000066400000000000000000000054161322611020300350210ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity-test/src/test/java/net/openhft/affinity/osgi/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity.osgi; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.PaxExam; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import javax.inject.Inject; import static org.junit.Assert.*; import static org.ops4j.pax.exam.CoreOptions.*; //@Ignore @RunWith(PaxExam.class) public class OSGiBundleTest extends net.openhft.affinity.osgi.OSGiTestBase { @Inject BundleContext context; @Configuration public Option[] config() { return options( systemProperty("org.osgi.framework.storage.clean").value("true"), systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("WARN"), mavenBundleAsInProject("org.slf4j","slf4j-api"), mavenBundleAsInProject("org.slf4j","slf4j-simple").noStart(), mavenBundleAsInProject("net.openhft","affinity"), workspaceBundle("affinity-test"), junitBundles(), systemPackage("sun.misc"), systemPackage("sun.nio.ch"), systemPackage("com.sun.jna"), systemPackage("com.sun.jna.ptr"), cleanCaches() ); } @Test public void checkInject() { assertNotNull(context); } @Test public void checkBundleState() { final Bundle bundle = findBundle(context, "net.openhft.affinity"); assertNotNull(bundle); assertEquals(bundle.getState(),Bundle.ACTIVE); } @Test public void checkBundleExports() { final Bundle bundle = findBundle(context, "net.openhft.affinity"); assertNotNull(bundle); final String exports = bundle.getHeaders().get("Export-Package"); final String[] packages = exports.split(","); assertTrue(packages.length >= 2); assertTrue(packages[0].startsWith("net.openhft.affinity;") || packages[0].startsWith("net.openhft.affinity.impl;")); assertTrue(packages[1].startsWith("net.openhft.affinity;") || packages[1].startsWith("net.openhft.affinity.impl;")); } } OSGiTestBase.java000066400000000000000000000041771322611020300344650ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity-test/src/test/java/net/openhft/affinity/osgi/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity.osgi; import org.ops4j.pax.exam.CoreOptions; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.options.MavenArtifactProvisionOption; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import java.io.File; public class OSGiTestBase { public static Option workspaceBundle(String projectName) { String baseDir = System.getProperty("main.basedir"); String bundleDir = null; bundleDir = String.format("%s/%s/target/classes",baseDir,projectName); if(new File(bundleDir).exists()) { return CoreOptions.bundle(String.format("reference:file:%s", bundleDir)); } bundleDir = String.format("%s/../%s/target/classes",baseDir,projectName); if(new File(bundleDir).exists()) { return CoreOptions.bundle(String.format("reference:file:%s", bundleDir)); } return null; } public static MavenArtifactProvisionOption mavenBundleAsInProject(final String groupId,final String artifactId) { return CoreOptions.mavenBundle().groupId(groupId).artifactId(artifactId).versionAsInProject(); } public static Bundle findBundle(BundleContext context, String symbolicName) { Bundle[] bundles = context.getBundles(); for (Bundle bundle : bundles) { if (bundle != null) { if (bundle.getSymbolicName().equals(symbolicName)) { return bundle; } } } return null; } } Java-Thread-Affinity-affinity-3.1.7/affinity/000077500000000000000000000000001322611020300207655ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/pom.xml000077500000000000000000000215001322611020300223030ustar00rootroot00000000000000 net.openhft java-parent-pom 1.1.13 4.0.0 affinity 3.1.7 bundle OpenHFT/Java-Thread-Affinity/affinity Java Thread Affinity library src/main/c UTF-8 net.openhft third-party-bom pom 3.6.0 import org.slf4j slf4j-api net.java.dev.jna jna net.java.dev.jna jna-platform com.intellij annotations org.easymock easymock test junit junit test org.slf4j slf4j-simple test org.apache.maven.plugins maven-compiler-plugin 3.6.2 -Xlint:deprecation 1.7 1.7 UTF-8 maven-antrun-plugin 1.7 build-native process-classes run org.codehaus.mojo exec-maven-plugin 1.2.1 build-native process-classes exec ${project.basedir}/${native.source.dir}/Makefile ${project.basedir}/${native.source.dir} org.apache.maven.plugins maven-scm-publish-plugin ${project.build.directory}/scmpublish/javadoc Publishing javadoc for ${project.artifactId}:${project.version} ${project.reporting.outputDirectory} true scm:git:git@github.com:OpenHFT/Java-Thread-Affinity gh-pages org.apache.servicemix.tooling depends-maven-plugin generate-depends-file generate-depends-file org.apache.felix maven-bundle-plugin true ${project.groupId}.${project.artifactId} OpenHFT :: ${project.artifactId} ${project.version} com.sun.jna.platform.*;resolution:=optional, * net.openhft.affinity.*;-noimport:=true, net.openhft.ticker.*;-noimport:=true manifest sonatype-nexus-staging https://oss.sonatype.org/content/repositories/staging true scm:git:git@github.com:OpenHFT/Java-Thread-Affinity.git scm:git:git@github.com:OpenHFT/Java-Thread-Affinity.git scm:git:git@github.com:OpenHFT/Java-Thread-Affinity.git affinity-3.1.7 Java-Thread-Affinity-affinity-3.1.7/affinity/src/000077500000000000000000000000001322611020300215545ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/000077500000000000000000000000001322611020300225005ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/c/000077500000000000000000000000001322611020300227225ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/c/Makefile000077500000000000000000000024621322611020300243710ustar00rootroot00000000000000#!/usr/bin/make -f # # Makefile for C code # # C sources to compile TARGET_DIR := ../../../target/classes TARGET := $(TARGET_DIR)/libCEInternals.so WORKING_DIR := $(TARGET_DIR)/../jni JAVA_CLASSES = software.chronicle.enterprise.internals.impl.NativeAffinity net.openhft.ticker.impl.JNIClock JNI_STUBS := $(subst .,_,$(JAVA_CLASSES)) JNI_HEADERS := $(patsubst %,$(WORKING_DIR)/%.h,$(JNI_STUBS)) JNI_SOURCES := $(patsubst %,%.cpp,$(JNI_STUBS)) JNI_JAVA_SOURCES := $(patsubst %,$(TARGET_DIR)/%.class,$(subst .,/,$(JAVA_CLASSES))) JAVA_BUILD_DIR := $(TARGET_DIR) JAVA_HOME ?= /usr/java/default JAVA_LIB := $(JAVA_HOME)/jre/lib JVM_SHARED_LIBS := -L$(JAVA_LIB)/amd64/server -L$(JAVA_LIB)/i386/server -L$(JAVA_LIB)/amd64/jrockit/ -L$(JAVA_LIB)/i386/jrockit/ CXX=g++ INCLUDES := -I $(JAVA_HOME)/include -I $(JAVA_HOME)/include/linux -I $(WORKING_DIR) # classpath for javah ifdef CLASSPATH JAVAH_CLASSPATH = $(JAVA_BUILD_DIR):$(CLASSPATH) else JAVAH_CLASSPATH = $(JAVA_BUILD_DIR) endif .PHONY : clean all: $(TARGET) $(TARGET): $(JNI_HEADERS) $(JNI_SOURCES) $(CXX) -O3 -Wall -shared -fPIC $(JVM_SHARED_LIBS) -ljvm -lrt $(INCLUDES) $(JNI_SOURCES) -o $(TARGET) $(JNI_HEADERS): $(JNI_JAVA_SOURCES) mkdir -p $(TARGET_DIR)/jni javah -force -classpath $(JAVAH_CLASSPATH) -d $(WORKING_DIR) $(JAVA_CLASSES) clean: rm $(TARGET) Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/c/net_openhft_ticker_impl_JNIClock.cpp000066400000000000000000000033221322611020300317750ustar00rootroot00000000000000/* vim: syntax=cpp * Copyright 2015 Higher Frequency Trading * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include #include "net_openhft_ticker_impl_JNIClock.h" #if defined(__i386__) static __inline__ unsigned long long rdtsc(void) { unsigned long long int x; __asm__ volatile (".byte 0x0f, 0x31" : "=A" (x)); return x; } #elif defined(__x86_64__) static __inline__ unsigned long long rdtsc(void) { unsigned hi, lo; __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi)); return ( (unsigned long long)lo)|( ((unsigned long long)hi)<<32 ); } #elif defined(__MIPS_32__) #define rdtsc(dest) \ _ _asm_ _ _ _volatile_ _("mfc0 %0,$9; nop" : "=r" (dest)) #elif defined(__MIPS_SGI__) #include static __inline__ unsigned long long rdtsc (void) { struct timespec tp; clock_gettime (CLOCK_SGI_CYCLE, &tp); return (unsigned long long)(tp.tv_sec * (unsigned long long)1000000000) + (unsigned long long)tp.tv_nsec; } #endif /* * Class: net_openhft_clock_impl_JNIClock * Method: rdtsc0 * Signature: ()J */ JNIEXPORT jlong JNICALL Java_net_openhft_ticker_impl_JNIClock_rdtsc0 (JNIEnv *env, jclass c) { return (jlong) rdtsc(); } software_chronicle_enterprise_internals_impl_NativeAffinity.cpp000066400000000000000000000057631322611020300376020ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/c/* vim: syntax=cpp * Copyright 2011 Higher Frequency Trading * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include #include #include #include #include #include #include "software_chronicle_enterprise_internals_impl_NativeAffinity.h" /* * Class: software_chronicle_enterprise_internals_impl_NativeAffinity * Method: getAffinity0 * Signature: ()J */ JNIEXPORT jbyteArray JNICALL Java_software_chronicle_enterprise_internals_impl_NativeAffinity_getAffinity0 (JNIEnv *env, jclass c) { // The default size of the structure supports 1024 CPUs, should be enough // for now In the future we can use dynamic sets, which can support more // CPUs, given OS can handle them as well cpu_set_t mask; const size_t size = sizeof(mask); int res = sched_getaffinity(0, size, &mask); if (res < 0) { return NULL; } jbyteArray ret = env->NewByteArray(size); jbyte* bytes = env->GetByteArrayElements(ret, 0); memcpy(bytes, &mask, size); env->SetByteArrayRegion(ret, 0, size, bytes); return ret; } /* * Class: software_chronicle_enterprise_internals_NativeAffinity * Method: setAffinity0 * Signature: (J)V */ JNIEXPORT void JNICALL Java_software_chronicle_enterprise_internals_impl_NativeAffinity_setAffinity0 (JNIEnv *env, jclass c, jbyteArray affinity) { cpu_set_t mask; const size_t size = sizeof(mask); CPU_ZERO(&mask); jbyte* bytes = env->GetByteArrayElements(affinity, 0); memcpy(&mask, bytes, size); sched_setaffinity(0, size, &mask); } /* * Class: software_chronicle_enterprise_internals_impl_NativeAffinity * Method: getProcessId0 * Signature: ()I */ JNIEXPORT jint JNICALL Java_software_chronicle_enterprise_internals_impl_NativeAffinity_getProcessId0 (JNIEnv *env, jclass c) { return (jint) getpid(); } /* * Class: software_chronicle_enterprise_internals_impl_NativeAffinity * Method: getThreadId0 * Signature: ()I */ JNIEXPORT jint JNICALL Java_software_chronicle_enterprise_internals_impl_NativeAffinity_getThreadId0 (JNIEnv *env, jclass c) { return (jint) (pid_t) syscall (SYS_gettid); } /* * Class: software_chronicle_enterprise_internals_impl_NativeAffinity * Method: getCpu0 * Signature: ()I */ JNIEXPORT jint JNICALL Java_software_chronicle_enterprise_internals_impl_NativeAffinity_getCpu0 (JNIEnv *env, jclass c) { return (jint) sched_getcpu(); } software_chronicle_enterprise_internals_impl_NativeAffinity_MacOSX.c000066400000000000000000000044461322611020300404110ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/c/* * Copyright 2011-2012 Peter Lawrey & Jerry Shea * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include #include "software_chronicle_enterprise_internals_impl_NativeAffinity.h" /* * Class: software_chronicle_enterprise_internals_impl_NativeAffinity * Method: getAffinity0 * Signature: ()J */ JNIEXPORT jlong JNICALL Java_software_chronicle_enterprise_internals_impl_NativeAffinity_getAffinity0 (JNIEnv *env, jclass c) { thread_port_t threadport = pthread_mach_thread_np(pthread_self()); struct thread_enterprise_internals_policy policy; policy.affinity_tag = 0; mach_msg_type_number_t count = THREAD_AFFINITY_POLICY_COUNT; boolean_t get_default = FALSE; if ((thread_policy_get(threadport, THREAD_AFFINITY_POLICY, (thread_policy_t)&policy, &count, &get_default)) != KERN_SUCCESS) { return ~0LL; } return (jlong) policy.affinity_tag; } /* * Class: software_chronicle_enterprise_internals_NativeAffinity * Method: setAffinity0 * Signature: (J)V */ JNIEXPORT void JNICALL Java_software_chronicle_enterprise_internals_impl_NativeAffinity_setAffinity0 (JNIEnv *env, jclass c, jlong affinity) { thread_port_t threadport = pthread_mach_thread_np(pthread_self()); struct thread_enterprise_internals_policy policy; policy.affinity_tag = affinity; int rc = thread_policy_set(threadport, THREAD_AFFINITY_POLICY, (thread_policy_t)&policy, THREAD_AFFINITY_POLICY_COUNT); if (rc != KERN_SUCCESS) { jclass ex = (*env)->FindClass(env, "java/lang/RuntimeException"); char msg[100]; sprintf(msg, "Bad return value from thread_policy_set: %d", rc); (*env)->ThrowNew(env, ex, msg); } } Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/000077500000000000000000000000001322611020300234215ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/java/000077500000000000000000000000001322611020300243425ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/java/lang/000077500000000000000000000000001322611020300252635ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/java/lang/ThreadLifecycleListener.java000066400000000000000000000022751322611020300326710ustar00rootroot00000000000000/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package java.lang; /** * A listener for various events in a Thread's life: creation, termination, etc. */ public interface ThreadLifecycleListener { /** * The specified thread is about to be started. * @param t the thread which is being started */ void started(Thread t); /** * The specified thread failed to start. * @param t the thread that had a failed start */ void startFailed(Thread t); /** * The specified thread has been terminated. * @param t the thread that has been terminated */ void terminated(Thread t); } Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/java/lang/ThreadTrackingGroup.java000066400000000000000000000031221322611020300320330ustar00rootroot00000000000000/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package java.lang; /** * A wrapper of {@link java.lang.ThreadGroup} that tracks the creation and termination of threads. */ public class ThreadTrackingGroup extends ThreadGroup { /** * Listener to be notified of various events in thread lifecycles. */ private final ThreadLifecycleListener listener; public ThreadTrackingGroup(ThreadGroup parent, ThreadLifecycleListener listener) { super(parent, ThreadTrackingGroup.class.getSimpleName().toLowerCase() + System.identityHashCode(listener)); this.listener = listener; } @Override void add(Thread t) { // System.out.println("ThreadTrackingGroup.add: " + t); //todo: remove super.add(t); listener.started(t); } @Override void threadStartFailed(Thread t) { super.threadStartFailed(t); listener.startFailed(t); } @Override void threadTerminated(Thread t) { super.threadTerminated(t); listener.terminated(t); } } Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/000077500000000000000000000000001322611020300242075ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/000077500000000000000000000000001322611020300256525ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/000077500000000000000000000000001322611020300274635ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/Affinity.java000066400000000000000000000172521322611020300321060ustar00rootroot00000000000000/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity; import net.openhft.affinity.impl.*; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Field; import java.util.BitSet; /** * Library to wrap low level JNI or JNA calls. Can be called without needing to know the actual * implementation used. * * @author peter.lawrey */ public enum Affinity { ; static final Logger LOGGER = LoggerFactory.getLogger(Affinity.class); @NotNull private static final IAffinity AFFINITY_IMPL; private static Boolean JNAAvailable; static { String osName = System.getProperty("os.name"); if (osName.contains("Win") && isWindowsJNAAffinityUsable()) { LOGGER.trace("Using Windows JNA-based affinity control implementation"); AFFINITY_IMPL = WindowsJNAAffinity.INSTANCE; } else if (osName.contains("x")) { /*if (osName.startsWith("Linux") && NativeAffinity.LOADED) { LOGGER.trace("Using Linux JNI-based affinity control implementation"); AFFINITY_IMPL = NativeAffinity.INSTANCE; } else*/ if (osName.startsWith("Linux") && isLinuxJNAAffinityUsable()) { LOGGER.trace("Using Linux JNA-based affinity control implementation"); AFFINITY_IMPL = LinuxJNAAffinity.INSTANCE; } else if (isPosixJNAAffinityUsable()) { LOGGER.trace("Using Posix JNA-based affinity control implementation"); AFFINITY_IMPL = PosixJNAAffinity.INSTANCE; } else { LOGGER.info("Using dummy affinity control implementation"); AFFINITY_IMPL = NullAffinity.INSTANCE; } } else if (osName.contains("Mac") && isMacJNAAffinityUsable()) { LOGGER.trace("Using MAC OSX JNA-based thread id implementation"); AFFINITY_IMPL = OSXJNAAffinity.INSTANCE; } else if (osName.contains("SunOS") && isSolarisJNAAffinityUsable()) { LOGGER.trace("Using Solaris JNA-based thread id implementation"); AFFINITY_IMPL = SolarisJNAAffinity.INSTANCE; } else { LOGGER.info("Using dummy affinity control implementation"); AFFINITY_IMPL = NullAffinity.INSTANCE; } } public static IAffinity getAffinityImpl() { return AFFINITY_IMPL; } private static boolean isWindowsJNAAffinityUsable() { if (isJNAAvailable()) { try { return WindowsJNAAffinity.LOADED; } catch (Throwable t) { logThrowable(t, "Windows JNA-based affinity not usable because it failed to load!"); return false; } } else { LOGGER.warn("Windows JNA-based affinity not usable due to JNA not being available!"); return false; } } private static boolean isPosixJNAAffinityUsable() { if (isJNAAvailable()) { try { return PosixJNAAffinity.LOADED; } catch (Throwable t) { logThrowable(t, "Posix JNA-based affinity not usable because it failed to load!"); return false; } } else { LOGGER.warn("Posix JNA-based affinity not usable due to JNA not being available!"); return false; } } private static boolean isLinuxJNAAffinityUsable() { if (isJNAAvailable()) { try { return LinuxJNAAffinity.LOADED; } catch (Throwable t) { logThrowable(t, "Linux JNA-based affinity not usable because it failed to load!"); return false; } } else { LOGGER.warn("Linux JNA-based affinity not usable due to JNA not being available!"); return false; } } private static boolean isMacJNAAffinityUsable() { if (isJNAAvailable()) { return true; } else { LOGGER.warn("MAX OSX JNA-based affinity not usable due to JNA not being available!"); return false; } } private static boolean isSolarisJNAAffinityUsable() { if (isJNAAvailable()) { return true; } else { LOGGER.warn("Solaris JNA-based affinity not usable due to JNA not being available!"); return false; } } private static void logThrowable(Throwable t, String description) { StringWriter sw = new StringWriter(); sw.append(description); sw.append(" Reason: "); t.printStackTrace(new PrintWriter(sw)); LOGGER.warn(sw.toString()); } public static BitSet getAffinity() { return AFFINITY_IMPL.getAffinity(); } public static void setAffinity(final BitSet affinity) { AFFINITY_IMPL.setAffinity(affinity); } public static void setAffinity(int cpu) { BitSet affinity = new BitSet(Runtime.getRuntime().availableProcessors()); affinity.set(cpu); setAffinity(affinity); } public static int getCpu() { return AFFINITY_IMPL.getCpu(); } public static int getThreadId() { return AFFINITY_IMPL.getThreadId(); } public static void setThreadId() { try { int threadId = Affinity.getThreadId(); final Field tid = Thread.class.getDeclaredField("tid"); tid.setAccessible(true); final Thread thread = Thread.currentThread(); tid.setLong(thread, threadId); Affinity.LOGGER.info("Set {} to thread id {}", thread.getName(), threadId); } catch (Exception e) { throw new IllegalStateException(e); } } public static boolean isJNAAvailable() { if (JNAAvailable == null) try { Class.forName("com.sun.jna.Platform"); JNAAvailable = true; } catch (ClassNotFoundException ignored) { JNAAvailable = false; } return JNAAvailable; } public static AffinityLock acquireLock() { return isNonForkingAffinityAvailable() ? NonForkingAffinityLock.acquireLock() : AffinityLock.acquireLock(); } public static AffinityLock acquireCore() { return isNonForkingAffinityAvailable() ? NonForkingAffinityLock.acquireCore() : AffinityLock.acquireCore(); } public static AffinityLock acquireLock(boolean bind) { return isNonForkingAffinityAvailable() ? NonForkingAffinityLock.acquireLock(bind) : AffinityLock.acquireLock(bind); } public static AffinityLock acquireCore(boolean bind) { return isNonForkingAffinityAvailable() ? NonForkingAffinityLock.acquireCore(bind) : AffinityLock.acquireCore(bind); } private static boolean isNonForkingAffinityAvailable() { BootClassPath bootClassPath = BootClassPath.INSTANCE; return bootClassPath.has("java.lang.ThreadTrackingGroup") && bootClassPath.has("java.lang.ThreadLifecycleListener"); } public static void resetToBaseAffinity() { Affinity.setAffinity(AffinityLock.BASE_AFFINITY); } } Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/AffinityLock.java000066400000000000000000000263071322611020300327200ustar00rootroot00000000000000/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity; import net.openhft.affinity.impl.NoCpuLayout; import net.openhft.affinity.impl.VanillaCpuLayout; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.util.BitSet; /** * This utility class support locking a thread to a single core, or reserving a whole core for a * thread. * * @author peter.lawrey */ public class AffinityLock implements Closeable { // Static fields and methods. public static final String AFFINITY_RESERVED = "affinity.reserved"; // TODO It seems like on virtualized platforms .availableProcessors() value can change at // TODO runtime. We should think about how to adopt to such change public static final int PROCESSORS; public static final BitSet BASE_AFFINITY; public static final BitSet RESERVED_AFFINITY; private static final Logger LOGGER = LoggerFactory.getLogger(AffinityLock.class); private static final LockInventory LOCK_INVENTORY; static final int ANY_CPU = -1; static { int processors = Runtime.getRuntime().availableProcessors(); VanillaCpuLayout cpuLayout = null; try { if (new File("/proc/cpuinfo").exists()) { cpuLayout = VanillaCpuLayout.fromCpuInfo(); processors = cpuLayout.cpus(); } } catch (IOException e) { LOGGER.warn("Unable to load /proc/cpuinfo", e); } PROCESSORS = processors; BASE_AFFINITY = Affinity.getAffinity(); RESERVED_AFFINITY = getReservedAffinity0(); LOCK_INVENTORY = new LockInventory(cpuLayout == null ? new NoCpuLayout(PROCESSORS) : cpuLayout); } /** * Logical ID of the CPU to which this lock belongs to. */ private final int cpuId; /** * CPU to which this lock belongs to is of general use. */ private final boolean base; /** * CPU to which this lock belongs to is reservable. */ private final boolean reservable; /** * An inventory build from the CPU layout which keeps track of the various locks belonging to * each CPU. */ private final LockInventory lockInventory; boolean bound = false; @Nullable Thread assignedThread; Throwable boundHere; AffinityLock(int cpuId, boolean base, boolean reservable, LockInventory lockInventory) { this.lockInventory = lockInventory; this.cpuId = cpuId; this.base = base; this.reservable = reservable; } /** * Set the CPU layout for this machine. CPUs which are not mentioned will be ignored.

* Changing the layout will have no impact on thread which have already been assigned. It only * affects subsequent assignments. * * @param cpuLayout for this application to use for this machine. */ public static void cpuLayout(@NotNull CpuLayout cpuLayout) { LOCK_INVENTORY.set(cpuLayout); } /** * @return The current CpuLayout for the application. */ @NotNull public static CpuLayout cpuLayout() { return LOCK_INVENTORY.getCpuLayout(); } private static BitSet getReservedAffinity0() { String reservedAffinity = System.getProperty(AFFINITY_RESERVED); if (BASE_AFFINITY != null && (reservedAffinity == null || reservedAffinity.trim().isEmpty())) { BitSet reserverable = new BitSet(PROCESSORS); reserverable.set(1, PROCESSORS, true); reserverable.andNot(BASE_AFFINITY); if (reserverable.isEmpty() && PROCESSORS > 1) { LoggerFactory.getLogger(AffinityLock.class).info("No isolated CPUs found, so assuming CPUs 1 to {} available.", (PROCESSORS - 1)); reserverable = new BitSet(PROCESSORS); // make the first CPU unavailable reserverable.set(1, PROCESSORS - 1, true); reserverable.set(0, false); return reserverable; } return reserverable; } long[] longs = new long[1]; longs[0] = Long.parseLong(reservedAffinity, 16); return BitSet.valueOf(longs); } /** * Assign any free cpu to this thread. * * @return A handle for the current AffinityLock. */ public static AffinityLock acquireLock() { return acquireLock(true); } /** * Assign any free core to this thread.

In reality, only one cpu is assigned, the rest of * the threads for that core are reservable so they are not used. * * @return A handle for the current AffinityLock. */ public static AffinityLock acquireCore() { return acquireCore(true); } /** * Assign a cpu which can be bound to the current thread or another thread.

This can be used * for defining your thread layout centrally and passing the handle via dependency injection. * * @param bind if true, bind the current thread, if false, reserve a cpu which can be bound * later. * @return A handle for an affinity lock. */ public static AffinityLock acquireLock(boolean bind) { return acquireLock(bind, ANY_CPU, AffinityStrategies.ANY); } /** * Assign a cpu which can be bound to the current thread or another thread.

This can be used * for defining your thread layout centrally and passing the handle via dependency injection. * * @param cpuId the CPU id to bind to * @return A handle for an affinity lock. */ public static AffinityLock acquireLock(int cpuId) { return acquireLock(true, cpuId, AffinityStrategies.ANY); } /** * Assign a core(and all its cpus) which can be bound to the current thread or another thread. *

This can be used for defining your thread layout centrally and passing the handle via * dependency injection. * * @param bind if true, bind the current thread, if false, reserve a cpu which can be bound * later. * @return A handle for an affinity lock. */ public static AffinityLock acquireCore(boolean bind) { return acquireCore(bind, ANY_CPU, AffinityStrategies.ANY); } private static AffinityLock acquireLock(boolean bind, int cpuId, @NotNull AffinityStrategy... strategies) { return LOCK_INVENTORY.acquireLock(bind, cpuId, strategies); } private static AffinityLock acquireCore(boolean bind, int cpuId, @NotNull AffinityStrategy... strategies) { return LOCK_INVENTORY.acquireCore(bind, cpuId, strategies); } /** * @return All the current locks as a String. */ @NotNull public static String dumpLocks() { return LOCK_INVENTORY.dumpLocks(); } private static boolean areAssertionsEnabled() { boolean debug = false; assert debug = true; return debug; } /** * Assigning the current thread has a side effect of preventing the lock being used again until * it is released. * * @param bind whether to bind the thread as well * @param wholeCore whether to reserve all the thread in the same core. */ final void assignCurrentThread(boolean bind, boolean wholeCore) { assignedThread = Thread.currentThread(); if (bind) bind(wholeCore); } /** * Bind the current thread to this reservable lock. */ public void bind() { bind(false); } /** * Bind the current thread to this reservable lock. * * @param wholeCore if true, also reserve the whole core. */ public void bind(boolean wholeCore) { if (bound && assignedThread != null && assignedThread.isAlive()) throw new IllegalStateException("cpu " + cpuId + " already bound to " + assignedThread); if (areAssertionsEnabled()) boundHere = new Throwable("Bound here"); if (wholeCore) { lockInventory.bindWholeCore(cpuId); } else if (cpuId >= 0) { bound = true; assignedThread = Thread.currentThread(); LOGGER.info("Assigning cpu {} to {}", cpuId, assignedThread); } if (cpuId >= 0) { BitSet affinity = new BitSet(); affinity.set(cpuId, true); Affinity.setAffinity(affinity); } } final boolean canReserve() { if (!LockCheck.isCpuFree(cpuId)) return false; if (!reservable) return false; if (assignedThread != null) { if (assignedThread.isAlive()) { return false; } LOGGER.warn("Lock assigned to {} but this thread is dead.", assignedThread); } return true; } /** * Give another affinity lock relative to this one based on a list of strategies.

The * strategies are evaluated in order to (like a search path) to find the next appropriate * thread. If ANY is not the last strategy, a warning is logged and no cpu is assigned (leaving * the OS to choose) * * @param strategies To determine if you want the same/different core/socket. * @return A matching AffinityLock. */ public AffinityLock acquireLock(AffinityStrategy... strategies) { return acquireLock(false, cpuId, strategies); } /** * Release the current AffinityLock which can be discarded. */ public void release() { lockInventory.release(); } @Override public void close() { release(); } @Override protected void finalize() throws Throwable { if (bound) { LOGGER.warn("Affinity lock for " + assignedThread + " was discarded rather than release()d in a controlled manner.", boundHere); release(); } super.finalize(); } /** * @return unique id for this CPI or -1 if not allocated. */ public int cpuId() { return cpuId; } /** * @return Was a cpu found to bind this lock to. */ public boolean isAllocated() { return cpuId >= 0; } /** * @return Has this AffinityLock been bound? */ public boolean isBound() { return bound; } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (assignedThread != null) sb.append(assignedThread).append(" alive=").append(assignedThread.isAlive()); else if (reservable) sb.append("Reserved for this application"); else if (base) sb.append("General use CPU"); else sb.append("CPU not available"); return sb.toString(); } } AffinityStrategies.java000066400000000000000000000046251322611020300340620ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity; /** * Pre-defined strategies for determining which thread to pick next. * * @author peter.lawrey */ public enum AffinityStrategies implements AffinityStrategy { /** * Any free cpu. */ ANY { @Override public boolean matches(int cpuId, int cpuId2) { return true; } }, /** * Must be a cpu on the same core. */ SAME_CORE { @Override public boolean matches(int cpuId, int cpuId2) { CpuLayout cpuLayout = AffinityLock.cpuLayout(); return cpuLayout.socketId(cpuId) == cpuLayout.socketId(cpuId2) && cpuLayout.coreId(cpuId) == cpuLayout.coreId(cpuId2); } }, /** * Must be a cpu on the same socket/chip but different core. */ SAME_SOCKET { @Override public boolean matches(int cpuId, int cpuId2) { CpuLayout cpuLayout = AffinityLock.cpuLayout(); return cpuLayout.socketId(cpuId) == cpuLayout.socketId(cpuId2) && cpuLayout.coreId(cpuId) != cpuLayout.coreId(cpuId2); } }, /** * Must be a cpu on any other core (or socket) */ DIFFERENT_CORE { @Override public boolean matches(int cpuId, int cpuId2) { CpuLayout cpuLayout = AffinityLock.cpuLayout(); return cpuLayout.socketId(cpuId) != cpuLayout.socketId(cpuId2) || cpuLayout.coreId(cpuId) != cpuLayout.coreId(cpuId2); } }, /** * Must be a cpu on any other socket. */ DIFFERENT_SOCKET { @Override public boolean matches(int cpuId, int cpuId2) { CpuLayout cpuLayout = AffinityLock.cpuLayout(); return cpuLayout.socketId(cpuId) != cpuLayout.socketId(cpuId2); } }; } AffinityStrategy.java000066400000000000000000000017421322611020300335470ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity; /** * Allow you define a strategy for find the a cpu relative to another select cpu. * * @author peter.lawrey */ public interface AffinityStrategy { /** * @param cpuId to cpuId to compare * @param cpuId2 with a second cpuId * @return true if it matches the criteria. */ boolean matches(int cpuId, int cpuId2); } Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/AffinitySupport.java000066400000000000000000000016211322611020300334740ustar00rootroot00000000000000/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity; /** * For backward compatibility with Affinity 2.x */ @Deprecated public class AffinitySupport { public static int getThreadId() { return Affinity.getThreadId(); } public static void setThreadId() { Affinity.setThreadId(); } } AffinityThreadFactory.java000066400000000000000000000046321322611020300345050ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicReference; /** * This is a ThreadFactory which assigns threads based the strategies provided. *

* If no strategies are provided AffinityStrategies.ANY is used. * * @author peter.lawrey */ public class AffinityThreadFactory implements ThreadFactory { private final String name; private final boolean daemon; @NotNull private final AffinityStrategy[] strategies; @Nullable private AffinityLock lastAffinityLock = null; private int id = 1; public AffinityThreadFactory(String name, AffinityStrategy... strategies) { this(name, true, strategies); } public AffinityThreadFactory(String name, boolean daemon, @NotNull AffinityStrategy... strategies) { this.name = name; this.daemon = daemon; this.strategies = strategies.length == 0 ? new AffinityStrategy[]{AffinityStrategies.ANY} : strategies; } @NotNull @Override public synchronized Thread newThread(@NotNull final Runnable r) { String name2 = id <= 1 ? name : (name + '-' + id); id++; Thread t = new Thread(new Runnable() { @Override public void run() { try (AffinityLock ignored = acquireLockBasedOnLast()) { r.run(); } } }, name2); t.setDaemon(daemon); return t; } private synchronized AffinityLock acquireLockBasedOnLast() { AffinityLock al = lastAffinityLock == null ? AffinityLock.acquireLock() : lastAffinityLock.acquireLock(strategies); if (al.cpuId() >= 0) lastAffinityLock = al; return al; } } Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/BootClassPath.java000066400000000000000000000077201322611020300330420ustar00rootroot00000000000000/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; enum BootClassPath { INSTANCE; private final Set bootClassPathResources = Collections.unmodifiableSet(getResourcesOnBootClasspath()); public final boolean has(String binaryClassName) { final String resourceClassName = binaryClassName.replace('.', '/').concat(".class"); return bootClassPathResources.contains(resourceClassName); } private static Set getResourcesOnBootClasspath() { final Logger logger = LoggerFactory.getLogger(BootClassPath.class); final Set resources = new HashSet<>(); final String bootClassPath = System.getProperty("sun.boot.class.path", ""); logger.trace("Boot class-path is: {}", bootClassPath); final String pathSeparator = System.getProperty("path.separator"); logger.trace("Path separator is: '{}'", pathSeparator); final String[] pathElements = bootClassPath.split(pathSeparator); for (final String pathElement : pathElements) { resources.addAll(findResources(Paths.get(pathElement), logger)); } return resources; } private static Set findResources(final Path path, final Logger logger) { if (!Files.exists(path)) { return Collections.emptySet(); } if (Files.isDirectory(path)) { return findResourcesInDirectory(path, logger); } return findResourcesInJar(path, logger); } private static Set findResourcesInJar(final Path path, final Logger logger) { final Set jarResources = new HashSet<>(); try { final JarFile jarFile = new JarFile(path.toFile()); final Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()) { final JarEntry jarEntry = entries.nextElement(); if (jarEntry.getName().endsWith(".class")) { jarResources.add(jarEntry.getName()); } } } catch (IOException e) { logger.warn("Not a jar file: {}", path); } return jarResources; } private static Set findResourcesInDirectory(final Path path, final Logger logger) { final Set dirResources = new HashSet<>(); try { Files.walkFileTree(path, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { if (file.getFileName().toString().endsWith(".class")) { dirResources.add(path.relativize(file).toString()); } return super.visitFile(file, attrs); } }); } catch (IOException e) { logger.warn("Error walking dir: " + path, e); } return dirResources; } } Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/CpuLayout.java000066400000000000000000000024131322611020300322530ustar00rootroot00000000000000/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity; /** * @author peter.lawrey */ public interface CpuLayout { /** * @return the number of cpus. */ int cpus(); int sockets(); int coresPerSocket(); int threadsPerCore(); /** * @param cpuId the logical processor number * @return which socket id this cpu is on. */ int socketId(int cpuId); /** * @param cpuId the logical processor number * @return which core on a socket this cpu is on. */ int coreId(int cpuId); /** * @param cpuId the logical processor number * @return which thread on a core this cpu is on. */ int threadId(int cpuId); } Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/IAffinity.java000066400000000000000000000025051322611020300322120ustar00rootroot00000000000000/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity; import java.util.BitSet; /** * Implementation interface * * @author cheremin * @since 29.12.11, 20:14 */ public interface IAffinity { /** * @return returns affinity mask for current thread, or null if unknown */ BitSet getAffinity(); /** * @param affinity sets affinity mask of current thread to specified value */ void setAffinity(final BitSet affinity); /** * @return the current cpu id, or -1 if unknown. */ int getCpu(); /** * @return the process id of the current process. */ int getProcessId(); /** * @return the thread id of the current thread or -1 is not available. */ int getThreadId(); } Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/LockCheck.java000066400000000000000000000114361322611020300321610ustar00rootroot00000000000000/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.text.SimpleDateFormat; import java.util.Date; /** * @author Rob Austin. */ enum LockCheck { ; private static final Logger LOGGER = LoggerFactory.getLogger(LockCheck.class); private static final String OS = System.getProperty("os.name").toLowerCase(); private static final int EMPTY_PID = Integer.MIN_VALUE; private static SimpleDateFormat df = new SimpleDateFormat("yyyy.MM" + ".dd 'at' HH:mm:ss z"); static final boolean IS_LINUX = OS.startsWith("linux"); static long getPID() { String processName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName(); return Long.parseLong(processName.split("@")[0]); } public static boolean isCpuFree(int cpu) { if (!IS_LINUX) return true; final File file = toFile(cpu); final boolean exists = file.exists(); if (!exists) { return true; } else { int currentProcess = 0; try { currentProcess = getProcessForCpu(file); } catch (RuntimeException | IOException e) { LOGGER.warn("Failed to determine process on cpu " + cpu, e); e.printStackTrace(); return true; } if (currentProcess == EMPTY_PID) { file.delete(); return true; } if (!isProcessRunning(currentProcess)) { file.delete(); return true; } return false; } } @NotNull static File toFile(int core) { return new File(tmpDir(), "cpu-" + core + ".lock"); } static void replacePid(int core, long processID) throws IOException { replacePid(toFile(core), processID); } private static void replacePid(File file, long processID) throws IOException { file.delete(); storePid(processID, file); } static boolean isProcessRunning(long pid) { if (IS_LINUX) return new File("/proc/" + pid).exists(); else throw new UnsupportedOperationException("this is only supported on LINUX"); } /** * stores the pid in a file, named by the core, the pid is written to the file with the date * below */ private synchronized static void storePid(long processID, File coreFile) throws IOException { try (Writer writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(coreFile, false), "utf-8"))) { String processIDStr = Long.toString(processID); writer.write(processIDStr + "\n" + df.format(new Date())); } } static int getProcessForCpu(int core) throws IOException { return getProcessForCpu(toFile(core)); } private static int getProcessForCpu(@NotNull File coreFile) throws IOException { try (BufferedReader reader = new BufferedReader(new InputStreamReader( new FileInputStream(coreFile), "utf-8"))) { final String firstLine = reader.readLine(); if (firstLine == null) { LOGGER.warn("Empty lock file {}", coreFile.getAbsolutePath()); return EMPTY_PID; } String s = firstLine.trim(); try { return Integer.parseInt(s); } catch (RuntimeException e) { LOGGER.warn("Corrupt lock file {}: first line = '{}'", coreFile.getAbsolutePath(), firstLine); e.printStackTrace(); return EMPTY_PID; } } } private static File tmpDir() { final File tempDir = new File(System.getProperty("java.io.tmpdir")); if (!tempDir.exists()) tempDir.mkdirs(); return tempDir; } static void updateCpu(int cpu) { if (!IS_LINUX) return; try { replacePid(toFile(cpu), getPID()); } catch (IOException e) { LOGGER.warn("Failed to update lock file for cpu " + cpu, e); e.printStackTrace(); } } }Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/LockInventory.java000066400000000000000000000202321322611020300331330ustar00rootroot00000000000000/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.NavigableMap; import java.util.TreeMap; class LockInventory { private static final Logger LOGGER = LoggerFactory.getLogger(LockInventory.class); /** * The locks belonging to physical cores. Since a physical core can host multiple logical cores * the relationship is one to many. */ private final NavigableMap physicalCoreLocks = new TreeMap(); private CpuLayout cpuLayout; /** * The lock belonging to each logical core. 1-to-1 relationship */ private AffinityLock[] logicalCoreLocks; public LockInventory(CpuLayout cpuLayout) { set(cpuLayout); } public static String dumpLocks(@NotNull AffinityLock[] locks) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < locks.length; i++) { AffinityLock al = locks[i]; sb.append(i).append(": "); sb.append(al.toString()); sb.append('\n'); } return sb.toString(); } public final synchronized CpuLayout getCpuLayout() { return cpuLayout; } public final synchronized void set(CpuLayout cpuLayout) { if (cpuLayout.equals(this.cpuLayout)) { return; } reset(cpuLayout); for (int i = 0; i < cpuLayout.cpus(); i++) { final boolean base = AffinityLock.BASE_AFFINITY.get(i); final boolean reservable = AffinityLock.RESERVED_AFFINITY.get(i); LOGGER.trace("cpu " + i + " base={} reservable= {}", i, base, reservable); AffinityLock lock = logicalCoreLocks[i] = newLock(i, base, reservable); int layoutId = lock.cpuId(); int physicalCore = toPhysicalCore(layoutId); AffinityLock[] locks = physicalCoreLocks.get(physicalCore); if (locks == null) { physicalCoreLocks.put(physicalCore, locks = new AffinityLock[cpuLayout.threadsPerCore()]); } locks[cpuLayout.threadId(layoutId)] = lock; } } public final synchronized AffinityLock acquireLock(boolean bind, int cpuId, AffinityStrategy... strategies) { final boolean specificCpuRequested = !isAnyCpu(cpuId); if (specificCpuRequested && cpuId != 0) { final AffinityLock required = logicalCoreLocks[cpuId]; if (required.canReserve() && anyStrategyMatches(cpuId, cpuId, strategies)) { updateLockForCurrentThread(bind, required, false); return required; } } LOGGER.warn("Unable to acquire lock on CPU {} for thread {}, trying to find another CPU", cpuId, Thread.currentThread()); for (AffinityStrategy strategy : strategies) { // consider all processors except cpu 0 which is usually used by the OS. // if you have only one core, this library is not appropriate in any case. for (int i = logicalCoreLocks.length - 1; i > 0; i--) { AffinityLock al = logicalCoreLocks[i]; if (al.canReserve() && (isAnyCpu(cpuId) || strategy.matches(cpuId, al.cpuId()))) { updateLockForCurrentThread(bind, al, false); return al; } } } LOGGER.warn("No reservable CPU for {}", Thread.currentThread()); return newLock(AffinityLock.ANY_CPU, false, false); } public final synchronized AffinityLock acquireCore(boolean bind, int cpuId, AffinityStrategy... strategies) { for (AffinityStrategy strategy : strategies) { LOOP: for (AffinityLock[] als : physicalCoreLocks.descendingMap().values()) { for (AffinityLock al : als) if (!al.canReserve() || !strategy.matches(cpuId, al.cpuId())) continue LOOP; final AffinityLock al = als[0]; updateLockForCurrentThread(bind, al, true); return al; } } LOGGER.warn("No reservable Core for {}", Thread.currentThread()); return acquireLock(bind, cpuId, strategies); } public final synchronized void bindWholeCore(int logicalCoreID) { if (logicalCoreID < 0) { LOGGER.warn("Can't bind core since it was not possible to reserve it!"); return; } int core = toPhysicalCore(logicalCoreID); for (AffinityLock al : physicalCoreLocks.get(core)) { if (al.isBound() && al.assignedThread != null && al.assignedThread.isAlive()) { LOGGER.warn("cpu {} already bound to {}", al.cpuId(), al.assignedThread); } else { al.bound = true; al.assignedThread = Thread.currentThread(); } } if (LOGGER.isInfoEnabled()) { StringBuilder sb = new StringBuilder().append("Assigning core ").append(core); String sep = ": cpus "; for (AffinityLock al : physicalCoreLocks.get(core)) { sb.append(sep).append(al.cpuId()); sep = ", "; } sb.append(" to ").append(Thread.currentThread()); LOGGER.info(sb.toString()); } } public final synchronized void release() { Thread t = Thread.currentThread(); for (AffinityLock al : logicalCoreLocks) { Thread at = al.assignedThread; if (at == t) { releaseAffinityLock(t, al, "Releasing cpu {} from {}"); } else if (at != null && !at.isAlive()) { releaseAffinityLock(t, al, "Releasing cpu {} from {} as it is not alive."); } } Affinity.resetToBaseAffinity(); } public final synchronized String dumpLocks() { return dumpLocks(logicalCoreLocks); } protected AffinityLock newLock(int cpuId, boolean base, boolean reservable) { return new AffinityLock(cpuId, base, reservable, this); } private void reset(CpuLayout cpuLayout) { this.cpuLayout = cpuLayout; this.logicalCoreLocks = new AffinityLock[cpuLayout.cpus()]; this.physicalCoreLocks.clear(); } private int toPhysicalCore(int layoutId) { return cpuLayout.socketId(layoutId) * cpuLayout.coresPerSocket() + cpuLayout.coreId(layoutId); } private void releaseAffinityLock(final Thread t, final AffinityLock al, final String format) { LOGGER.info(format, al.cpuId(), t); al.assignedThread = null; al.bound = false; al.boundHere = null; final String lockFilePath = LockCheck.toFile(al.cpuId()).getAbsolutePath(); try { Files.delete(Paths.get(lockFilePath)); } catch (IOException e) { LOGGER.warn("Failed to delete lock file at " + lockFilePath); } } private static boolean anyStrategyMatches(final int cpuOne, final int cpuTwo, final AffinityStrategy[] strategies) { for (AffinityStrategy strategy : strategies) { if (strategy.matches(cpuOne, cpuTwo)) { return true; } } return false; } private static boolean isAnyCpu(final int cpuId) { return cpuId == AffinityLock.ANY_CPU; } private static void updateLockForCurrentThread(final boolean bind, final AffinityLock al, final boolean b) { al.assignCurrentThread(bind, b); LockCheck.updateCpu(al.cpuId()); } }MicroJitterSampler.java000077500000000000000000000073341322611020300340400ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/* * Copyright 2014 Higher Frequency Trading * * http://www.higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.affinity; import java.io.PrintStream; /* e.g. After 2430 seconds, the average per hour was 2us 78400 3us 122703 4us 345238 6us 216098 8us 78694 10us 3977528 14us 114495 20us 4931 30us 203 40us 35 60us 18 80us 11 100us 9 140us 132 200us 85 300us 473 400us 5 1ms 24 */ /** * User: peter.lawrey Date: 30/06/13 Time: 13:13 */ public class MicroJitterSampler { private static final long[] DELAY = { 2 * 1000, 3 * 1000, 4 * 1000, 6 * 1000, 8 * 1000, 10 * 1000, 14 * 1000, 20 * 1000, 30 * 1000, 40 * 1000, 60 * 1000, 80 * 1000, 100 * 1000, 140 * 1000, 200 * 1000, 300 * 1000, 400 * 1000, 600 * 1000, 800 * 1000, 1000 * 1000, 2 * 1000 * 1000, 5 * 1000 * 1000, 10 * 1000 * 1000, 20 * 1000 * 1000, 50 * 1000 * 1000, 100 * 1000 * 1000 }; private static final double UTIL = Double.parseDouble(System.getProperty("util", "50")); // static final int CPU = Integer.getInteger("cpu", 0); private final int[] count = new int[DELAY.length]; private long totalTime = 0; public static void main(String... ignored) throws InterruptedException { // AffinityLock al = AffinityLock.acquireLock(); // warmup. new MicroJitterSampler().sample(1000 * 1000 * 1000); MicroJitterSampler microJitterSampler = new MicroJitterSampler(); while (!Thread.currentThread().isInterrupted()) { if (UTIL >= 100) { microJitterSampler.sample(30L * 1000 * 1000 * 1000); } else { long sampleLength = (long) ((1 / (1 - UTIL / 100) - 1) * 1000 * 1000); for (int i = 0; i < 30 * 1000; i += 2) { microJitterSampler.sample(sampleLength); //noinspection BusyWait Thread.sleep(1); } } microJitterSampler.print(System.out); } } private static String asString(long timeNS) { return timeNS < 1000 ? timeNS + "ns" : timeNS < 1000000 ? timeNS / 1000 + "us" : timeNS < 1000000000 ? timeNS / 1000000 + "ms" : timeNS / 1000000000 + "sec"; } void sample(long intervalNS) { long prev = System.nanoTime(); long end = prev + intervalNS; long now; do { now = System.nanoTime(); long time = now - prev; if (time >= DELAY[0]) { int i; for (i = 1; i < DELAY.length; i++) if (time < DELAY[i]) break; count[i - 1]++; } prev = now; } while (now < end); totalTime += intervalNS; } void print(PrintStream ps) { ps.println("After " + totalTime / 1000000000 + " seconds, the average per hour was"); for (int i = 0; i < DELAY.length; i++) { if (count[i] < 1) continue; long countPerHour = (long) Math.ceil(count[i] * 3600e9 / totalTime); ps.println(asString(DELAY[i]) + '\t' + countPerHour); } ps.println(); } } NonForkingAffinityLock.java000066400000000000000000000144521322611020300346320ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity; import net.openhft.affinity.impl.NoCpuLayout; import org.jetbrains.annotations.NotNull; import java.lang.reflect.Field; public class NonForkingAffinityLock extends AffinityLock implements ThreadLifecycleListener { private static final Field GROUP_FIELD = makeThreadFieldModifiable("group"); private static final Field TARGET_FIELD = makeThreadFieldModifiable("target"); private static final LockInventory LOCK_INVENTORY = new LockInventory(new NoCpuLayout(PROCESSORS)) { @Override protected AffinityLock newLock(int cpuId, boolean base, boolean reservable) { return new NonForkingAffinityLock(cpuId, base, reservable, this); } }; NonForkingAffinityLock(int cpuId, boolean base, boolean reservable, LockInventory lockInventory) { super(cpuId, base, reservable, lockInventory); } /** * Assign any free cpu to this thread. * * @return A handle for the current AffinityLock. */ public static AffinityLock acquireLock() { return acquireLock(true); } /** * Assign any free core to this thread. *

* In reality, only one cpu is assigned, the rest of the threads for that core are reservable so they are not used. * * @return A handle for the current AffinityLock. */ public static AffinityLock acquireCore() { return acquireCore(true); } /** * Assign a cpu which can be bound to the current thread or another thread. *

* This can be used for defining your thread layout centrally and passing the handle via dependency injection. * * @param bind if true, bind the current thread, if false, reserve a cpu which can be bound later. * @return A handle for an affinity lock. */ public static AffinityLock acquireLock(boolean bind) { return acquireLock(bind, AffinityLock.ANY_CPU, AffinityStrategies.ANY); } /** * Assign a core(and all its cpus) which can be bound to the current thread or another thread. *

* This can be used for defining your thread layout centrally and passing the handle via dependency injection. * * @param bind if true, bind the current thread, if false, reserve a cpu which can be bound later. * @return A handle for an affinity lock. */ public static AffinityLock acquireCore(boolean bind) { return acquireCore(bind, AffinityLock.ANY_CPU, AffinityStrategies.ANY); } private static AffinityLock acquireLock(boolean bind, int cpuId, @NotNull AffinityStrategy... strategies) { return LOCK_INVENTORY.acquireLock(bind, cpuId, strategies); } private static AffinityLock acquireCore(boolean bind, int cpuId, @NotNull AffinityStrategy... strategies) { return LOCK_INVENTORY.acquireCore(bind, cpuId, strategies); } /** * Set the CPU layout for this machine. CPUs which are not mentioned will be ignored. *

* Changing the layout will have no impact on thread which have already been assigned. * It only affects subsequent assignments. * * @param cpuLayout for this application to use for this machine. */ public static void cpuLayout(@NotNull CpuLayout cpuLayout) { LOCK_INVENTORY.set(cpuLayout); } /** * @return The current CpuLayout for the application. */ @NotNull public static CpuLayout cpuLayout() { return LOCK_INVENTORY.getCpuLayout(); } /** * @return All the current locks as a String. */ @NotNull public static String dumpLocks() { return LOCK_INVENTORY.dumpLocks(); } private static Field makeThreadFieldModifiable(String fieldName) { try { Field field = Thread.class.getDeclaredField(fieldName); field.setAccessible(true); return field; } catch (NoSuchFieldException e) { throw new RuntimeException(Thread.class.getName() + " class doesn't have a " + fieldName + " field! Quite unexpected!"); } } private static void changeGroupOfThread(Thread thread, ThreadGroup group) { try { GROUP_FIELD.set(thread, group); } catch (IllegalAccessException e) { throw new RuntimeException("Failed changing " + Thread.class.getName() + "'s the '" + GROUP_FIELD.getName() + "' field! Reason: " + e.getMessage()); } } private static void wrapRunnableOfThread(Thread thread, final AffinityLock lock) { try { final Runnable originalRunnable = (Runnable) TARGET_FIELD.get(thread); TARGET_FIELD.set( thread, new Runnable() { @Override public void run() { lock.release(); originalRunnable.run(); } } ); } catch (IllegalAccessException e) { throw new RuntimeException("Failed wrapping " + Thread.class.getName() + "'s '" + TARGET_FIELD.getName() + "' field! Reason: " + e.getMessage()); } } @Override public void bind(boolean wholeCore) { super.bind(wholeCore); Thread thread = Thread.currentThread(); changeGroupOfThread(thread, new ThreadTrackingGroup(thread.getThreadGroup(), this)); } @Override public void release() { Thread thread = Thread.currentThread(); changeGroupOfThread(thread, thread.getThreadGroup().getParent()); super.release(); } @Override public void started(Thread t) { wrapRunnableOfThread(t, this); } @Override public void startFailed(Thread t) { } @Override public void terminated(Thread t) { } } Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/impl/000077500000000000000000000000001322611020300304245ustar00rootroot00000000000000LinuxHelper.java000066400000000000000000000266721322611020300334640ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/impl/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity.impl; import com.sun.jna.*; import com.sun.jna.ptr.IntByReference; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.BitSet; import java.util.List; public class LinuxHelper { private static final String LIBRARY_NAME = "c"; private static final VersionHelper UNKNOWN = new VersionHelper(0, 0, 0); private static final VersionHelper VERSION_2_6 = new VersionHelper(2, 6, 0); private static final VersionHelper version; static { final utsname uname = new utsname(); VersionHelper ver = UNKNOWN; try { if (CLibrary.INSTANCE.uname(uname) == 0) { ver = new VersionHelper(uname.getRealeaseVersion()); } } catch (Throwable e) { //logger.warn("Failed to determine Linux version: " + e); } version = ver; } public static @NotNull cpu_set_t sched_getaffinity() { final CLibrary lib = CLibrary.INSTANCE; final cpu_set_t cpuset = new cpu_set_t(); final int size = version.isSameOrNewer(VERSION_2_6) ? cpu_set_t.SIZE_OF_CPU_SET_T : NativeLong.SIZE; try { if (lib.sched_getaffinity(0, size, cpuset) != 0) { throw new IllegalStateException("sched_getaffinity(0, " + size + ", cpuset) failed; errno=" + Native.getLastError()); } } catch (LastErrorException e) { throw new IllegalStateException("sched_getaffinity(0, (" + size + ") , cpuset) failed; errno=" + e.getErrorCode(), e); } return cpuset; } public static void sched_setaffinity(final BitSet affinity) { final CLibrary lib = CLibrary.INSTANCE; final cpu_set_t cpuset = new cpu_set_t(); final int size = version.isSameOrNewer(VERSION_2_6) ? cpu_set_t.SIZE_OF_CPU_SET_T : NativeLong.SIZE; final long[] bits = affinity.toLongArray(); for (int i = 0; i < bits.length; i++) { if (Platform.is64Bit()) { cpuset.__bits[i].setValue(bits[i]); } else { cpuset.__bits[i * 2].setValue(bits[i] & 0xFFFFFFFFL); cpuset.__bits[i * 2 + 1].setValue((bits[i] >>> 32) & 0xFFFFFFFFL); } } try { if (lib.sched_setaffinity(0, size, cpuset) != 0) { throw new IllegalStateException("sched_setaffinity(0, " + size + ", 0x" + Utilities.toHexString(affinity) + ") failed; errno=" + Native.getLastError()); } } catch (LastErrorException e) { throw new IllegalStateException("sched_setaffinity(0, " + size + ", 0x" + Utilities.toHexString(affinity) + ") failed; errno=" + e.getErrorCode(), e); } } public static int sched_getcpu() { final CLibrary lib = CLibrary.INSTANCE; try { final int ret = lib.sched_getcpu(); if (ret < 0) { throw new IllegalStateException("sched_getcpu() failed; errno=" + Native.getLastError()); } return ret; } catch (LastErrorException e) { throw new IllegalStateException("sched_getcpu() failed; errno=" + e.getErrorCode(), e); } catch (UnsatisfiedLinkError ule) { try { final IntByReference cpu = new IntByReference(); final IntByReference node = new IntByReference(); final int ret = lib.syscall(318, cpu, node, null); if (ret != 0) { throw new IllegalStateException("getcpu() failed; errno=" + Native.getLastError()); } return cpu.getValue(); } catch (LastErrorException lee) { if (lee.getErrorCode() == 38 && Platform.is64Bit()) { // unknown call final Pointer getcpuAddr = new Pointer((-10L << 20) + 1024L * 2L); final Function getcpu = Function.getFunction(getcpuAddr, Function.C_CONVENTION); final IntByReference cpu = new IntByReference(); if (getcpu.invokeInt(new Object[]{cpu, null, null}) < 0) { throw new IllegalStateException("getcpu() failed; errno=" + Native.getLastError()); } else { return cpu.getValue(); } } else { throw new IllegalStateException("getcpu() failed; errno=" + lee.getErrorCode(), lee); } } } } public static int getpid() { final CLibrary lib = CLibrary.INSTANCE; try { final int ret = lib.getpid(); if (ret < 0) { throw new IllegalStateException("getpid() failed; errno=" + Native.getLastError()); } return ret; } catch (LastErrorException e) { throw new IllegalStateException("getpid() failed; errno=" + e.getErrorCode(), e); } } public static int syscall(int number, Object... args) { final CLibrary lib = CLibrary.INSTANCE; try { final int ret = lib.syscall(number, args); if (ret < 0) { throw new IllegalStateException("sched_getcpu() failed; errno=" + Native.getLastError()); } return ret; } catch (LastErrorException e) { throw new IllegalStateException("sched_getcpu() failed; errno=" + e.getErrorCode(), e); } } interface CLibrary extends Library { CLibrary INSTANCE = (CLibrary) Native.loadLibrary(LIBRARY_NAME, CLibrary.class); int sched_setaffinity(final int pid, final int cpusetsize, final cpu_set_t cpuset) throws LastErrorException; int sched_getaffinity(final int pid, final int cpusetsize, final cpu_set_t cpuset) throws LastErrorException; int getpid() throws LastErrorException; int sched_getcpu() throws LastErrorException; int uname(final utsname name) throws LastErrorException; int syscall(int number, Object... args) throws LastErrorException; } /** * Structure describing the system and machine. */ public static class utsname extends Structure { public static final int _UTSNAME_LENGTH = 65; static List FIELD_ORDER = Arrays.asList( "sysname", "nodename", "release", "version", "machine", "domainname" ); /** * Name of the implementation of the operating system. */ public byte[] sysname = new byte[_UTSNAME_LENGTH]; /** * Name of this node on the network. */ public byte[] nodename = new byte[_UTSNAME_LENGTH]; /** * Current release level of this implementation. */ public byte[] release = new byte[_UTSNAME_LENGTH]; /** * Current version level of this release. */ public byte[] version = new byte[_UTSNAME_LENGTH]; /** * Name of the hardware type the system is running on. */ public byte[] machine = new byte[_UTSNAME_LENGTH]; /** * NIS or YP domain name */ public byte[] domainname = new byte[_UTSNAME_LENGTH]; static int length(final byte[] data) { int len = 0; final int datalen = data.length; while (len < datalen && data[len] != 0) len++; return len; } @Override protected List getFieldOrder() { return FIELD_ORDER; } public String getSysname() { return new String(sysname, 0, length(sysname)); } @SuppressWarnings({"UnusedDeclaration"}) public String getNodename() { return new String(nodename, 0, length(nodename)); } public String getRelease() { return new String(release, 0, length(release)); } public String getRealeaseVersion() { final String release = getRelease(); final int releaseLen = release.length(); int len = 0; for (; len < releaseLen; len++) { final char c = release.charAt(len); if (Character.isDigit(c) || c == '.') { continue; } break; } return release.substring(0, len); } public String getVersion() { return new String(version, 0, length(version)); } public String getMachine() { return new String(machine, 0, length(machine)); } @SuppressWarnings({"UnusedDeclaration"}) public String getDomainname() { return new String(domainname, 0, length(domainname)); } @Override public String toString() { return getSysname() + " " + getRelease() + " " + getVersion() + " " + getMachine(); } } public static class cpu_set_t extends Structure { static final int __CPU_SETSIZE = 1024; static final int __NCPUBITS = 8 * NativeLong.SIZE; static final int SIZE_OF_CPU_SET_T = (__CPU_SETSIZE / __NCPUBITS) * NativeLong.SIZE; static List FIELD_ORDER = Arrays.asList("__bits"); public NativeLong[] __bits = new NativeLong[__CPU_SETSIZE / __NCPUBITS]; public cpu_set_t() { for (int i = 0; i < __bits.length; i++) { __bits[i] = new NativeLong(0); } } @SuppressWarnings({"UnusedDeclaration"}) public static void __CPU_ZERO(cpu_set_t cpuset) { for (NativeLong bits : cpuset.__bits) { bits.setValue(0l); } } public static int __CPUELT(int cpu) { return cpu / __NCPUBITS; } public static long __CPUMASK(int cpu) { return 1l << (cpu % __NCPUBITS); } @SuppressWarnings({"UnusedDeclaration"}) public static void __CPU_SET(int cpu, cpu_set_t cpuset) { cpuset.__bits[__CPUELT(cpu)].setValue( cpuset.__bits[__CPUELT(cpu)].longValue() | __CPUMASK(cpu)); } @SuppressWarnings({"UnusedDeclaration"}) public static void __CPU_CLR(int cpu, cpu_set_t cpuset) { cpuset.__bits[__CPUELT(cpu)].setValue( cpuset.__bits[__CPUELT(cpu)].longValue() & ~__CPUMASK(cpu)); } @SuppressWarnings({"UnusedDeclaration"}) public static boolean __CPU_ISSET(int cpu, cpu_set_t cpuset) { return (cpuset.__bits[__CPUELT(cpu)].longValue() & __CPUMASK(cpu)) != 0; } @Override protected List getFieldOrder() { return FIELD_ORDER; } } } LinuxJNAAffinity.java000066400000000000000000000052251322611020300343360ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/impl/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity.impl; import com.sun.jna.NativeLong; import com.sun.jna.Platform; import net.openhft.affinity.IAffinity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.BitSet; public enum LinuxJNAAffinity implements IAffinity { INSTANCE; public static final boolean LOADED; private static final Logger LOGGER = LoggerFactory.getLogger(LinuxJNAAffinity.class); private static final int PROCESS_ID; private static final int SYS_gettid = Platform.is64Bit() ? 186 : 224; private static final Object[] NO_ARGS = {}; static { int pid = -1; try { pid = LinuxHelper.getpid(); } catch (Exception ignored) { } PROCESS_ID = pid; } static { boolean loaded = false; try { INSTANCE.getAffinity(); loaded = true; } catch (UnsatisfiedLinkError e) { LOGGER.warn("Unable to load jna library {}", e); } LOADED = loaded; } private final ThreadLocal THREAD_ID = new ThreadLocal<>(); @Override public BitSet getAffinity() { final LinuxHelper.cpu_set_t cpuset = LinuxHelper.sched_getaffinity(); BitSet ret = new BitSet(LinuxHelper.cpu_set_t.__CPU_SETSIZE); int i = 0; for (NativeLong nl : cpuset.__bits) { for (int j = 0; j < Long.SIZE; j++) ret.set(i++, ((nl.longValue() >>> j) & 1) != 0); } return ret; } // TODO: FIXME!!! CHANGE IAffinity TO SUPPORT PLATFORMS WITH 64+ CORES FIXME!!! @Override public void setAffinity(final BitSet affinity) { LinuxHelper.sched_setaffinity(affinity); } @Override public int getCpu() { return LinuxHelper.sched_getcpu(); } @Override public int getProcessId() { return PROCESS_ID; } @Override public int getThreadId() { Integer tid = THREAD_ID.get(); if (tid == null) THREAD_ID.set(tid = LinuxHelper.syscall(SYS_gettid, NO_ARGS)); return tid; } } NoCpuLayout.java000066400000000000000000000026441322611020300334400ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/impl/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity.impl; import net.openhft.affinity.CpuLayout; /** * This assumes there is one socket with every cpu on a different core. * * @author peter.lawrey */ public class NoCpuLayout implements CpuLayout { private final int cpus; public NoCpuLayout(int cpus) { this.cpus = cpus; } @Override public int sockets() { return 1; } @Override public int coresPerSocket() { return cpus; } @Override public int threadsPerCore() { return 1; } public int cpus() { return cpus; } @Override public int socketId(int cpuId) { return 0; } @Override public int coreId(int cpuId) { return cpuId; } @Override public int threadId(int cpuId) { return 0; } } NullAffinity.java000066400000000000000000000031521322611020300336150ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/impl/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity.impl; import net.openhft.affinity.IAffinity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.management.ManagementFactory; import java.util.BitSet; /** * @author peter.lawrey */ public enum NullAffinity implements IAffinity { INSTANCE; private static final Logger LOGGER = LoggerFactory.getLogger(NullAffinity.class); @Override public BitSet getAffinity() { return new BitSet(); } @Override public void setAffinity(final BitSet affinity) { LOGGER.trace("unable to set mask to {} as the JNIa nd JNA libraries and not loaded", Utilities.toHexString(affinity)); } @Override public int getCpu() { return -1; } @Override public int getProcessId() { final String name = ManagementFactory.getRuntimeMXBean().getName(); return Integer.parseInt(name.split("@")[0]); } @Override public int getThreadId() { throw new UnsupportedOperationException(); } } OSXJNAAffinity.java000066400000000000000000000045401322611020300337070ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/impl/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity.impl; import com.sun.jna.LastErrorException; import com.sun.jna.Library; import com.sun.jna.Native; import net.openhft.affinity.IAffinity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.management.ManagementFactory; import java.util.BitSet; /** * This is essentially the same as the NullAffinity implementation but with concrete * support for getThreadId(). * * @author daniel.shaya */ public enum OSXJNAAffinity implements IAffinity { INSTANCE; private static final Logger LOGGER = LoggerFactory.getLogger(OSXJNAAffinity.class); private final ThreadLocal THREAD_ID = new ThreadLocal<>(); @Override public BitSet getAffinity() { return new BitSet(); } @Override public void setAffinity(final BitSet affinity) { LOGGER.trace("unable to set mask to {} as the JNIa nd JNA libraries and not loaded", Utilities.toHexString(affinity)); } @Override public int getCpu() { return -1; } @Override public int getProcessId() { final String name = ManagementFactory.getRuntimeMXBean().getName(); return Integer.parseInt(name.split("@")[0]); } @Override public int getThreadId() { Integer tid = THREAD_ID.get(); if (tid == null) { tid = CLibrary.INSTANCE.pthread_self(); //The tid assumed to be an unsigned 24 bit, see net.openhft.lang.Jvm.getMaxPid() tid = tid & 0xFFFFFF; THREAD_ID.set(tid); } return tid; } interface CLibrary extends Library { CLibrary INSTANCE = (CLibrary) Native.loadLibrary("libpthread.dylib", CLibrary.class); int pthread_self() throws LastErrorException; } } PosixJNAAffinity.java000066400000000000000000000214231322611020300343370ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/impl/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity.impl; import com.sun.jna.*; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.PointerByReference; import net.openhft.affinity.IAffinity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.BitSet; /** * Implementation of {@link IAffinity} based on JNA call of * sched_setaffinity(3)/sched_getaffinity(3) from 'c' library. Applicable for most * linux/unix platforms *

* TODO Support assignment to core 64 and above * * @author peter.lawrey * @author BegemoT */ public enum PosixJNAAffinity implements IAffinity { INSTANCE; public static final boolean LOADED; private static final Logger LOGGER = LoggerFactory.getLogger(PosixJNAAffinity.class); private static final String LIBRARY_NAME = Platform.isWindows() ? "msvcrt" : "c"; private static final int PROCESS_ID; private static final boolean ISLINUX = "Linux".equals(System.getProperty("os.name")); private static final boolean IS64BIT = is64Bit0(); private static final int SYS_gettid = is64Bit() ? 186 : 224; private static final Object[] NO_ARGS = {}; static { int processId; try { processId = CLibrary.INSTANCE.getpid(); } catch (Exception ignored) { processId = -1; } PROCESS_ID = processId; } static { boolean loaded = false; try { INSTANCE.getAffinity(); loaded = true; } catch (UnsatisfiedLinkError e) { LOGGER.warn("Unable to load jna library {}", e); } LOADED = loaded; } private final ThreadLocal THREAD_ID = new ThreadLocal(); public static boolean is64Bit() { return IS64BIT; } private static boolean is64Bit0() { String systemProp; systemProp = System.getProperty("com.ibm.vm.bitmode"); if (systemProp != null) { return "64".equals(systemProp); } systemProp = System.getProperty("sun.arch.data.model"); if (systemProp != null) { return "64".equals(systemProp); } systemProp = System.getProperty("java.vm.version"); return systemProp != null && systemProp.contains("_64"); } @Override public BitSet getAffinity() { final CLibrary lib = CLibrary.INSTANCE; final int procs = Runtime.getRuntime().availableProcessors(); final int cpuSetSizeInLongs = (procs + 63) / 64; final int cpuSetSizeInBytes = cpuSetSizeInLongs * 8; final Memory cpusetArray = new Memory(cpuSetSizeInBytes); final PointerByReference cpuset = new PointerByReference(cpusetArray); try { final int ret = lib.sched_getaffinity(0, cpuSetSizeInBytes, cpuset); if (ret < 0) { throw new IllegalStateException("sched_getaffinity((" + cpuSetSizeInBytes + ") , &(" + cpusetArray + ") ) return " + ret); } ByteBuffer buff = cpusetArray.getByteBuffer(0, cpuSetSizeInBytes); return BitSet.valueOf(buff.array()); } catch (LastErrorException e) { if (e.getErrorCode() != 22) { throw new IllegalStateException("sched_getaffinity((" + cpuSetSizeInBytes + ") , &(" + cpusetArray + ") ) errorNo=" + e.getErrorCode(), e); } } // fall back to the old method final IntByReference cpuset32 = new IntByReference(0); try { final int ret = lib.sched_getaffinity(0, Integer.SIZE / 8, cpuset32); if (ret < 0) { throw new IllegalStateException("sched_getaffinity((" + Integer.SIZE / 8 + ") , &(" + cpuset32 + ") ) return " + ret); } long[] longs = new long[1]; longs[0] = cpuset32.getValue() & 0xFFFFFFFFL; return BitSet.valueOf(longs); } catch (LastErrorException e) { throw new IllegalStateException("sched_getaffinity((" + Integer.SIZE / 8 + ") , &(" + cpuset32 + ") ) errorNo=" + e.getErrorCode(), e); } } @Override public void setAffinity(final BitSet affinity) { int procs = Runtime.getRuntime().availableProcessors(); if (affinity.isEmpty()) { throw new IllegalArgumentException("Cannot set zero affinity"); } final CLibrary lib = CLibrary.INSTANCE; byte[] buff = affinity.toByteArray(); final int cpuSetSizeInBytes = buff.length; final Memory cpusetArray = new Memory(cpuSetSizeInBytes); try { cpusetArray.write(0, buff, 0, buff.length); final int ret = lib.sched_setaffinity(0, cpuSetSizeInBytes, new PointerByReference(cpusetArray)); if (ret < 0) { throw new IllegalStateException("sched_setaffinity((" + cpuSetSizeInBytes + ") , &(" + affinity + ") ) return " + ret); } } catch (LastErrorException e) { if (e.getErrorCode() != 22 || !Arrays.equals(buff, cpusetArray.getByteArray(0, cpuSetSizeInBytes))) { throw new IllegalStateException("sched_setaffinity((" + cpuSetSizeInBytes + ") , &(" + affinity + ") ) errorNo=" + e.getErrorCode(), e); } } final int value = (int) affinity.toLongArray()[0]; if (value == 0) { throw new IllegalArgumentException("Cannot set zero affinity"); } final IntByReference cpuset32 = new IntByReference(0); cpuset32.setValue(value); try { final int ret = lib.sched_setaffinity(0, Integer.SIZE / 8, cpuset32); if (ret < 0) throw new IllegalStateException("sched_setaffinity((" + Integer.SIZE / 8 + ") , &(" + Integer.toHexString(cpuset32.getValue()) + ") ) return " + ret); } catch (LastErrorException e) { throw new IllegalStateException("sched_setaffinity((" + Integer.SIZE / 8 + ") , &(" + Integer.toHexString(cpuset32.getValue()) + ") ) errorNo=" + e.getErrorCode(), e); } } @Override public int getCpu() { final CLibrary lib = CLibrary.INSTANCE; try { final int ret = lib.sched_getcpu(); if (ret < 0) throw new IllegalStateException("sched_getcpu( ) return " + ret); return ret; } catch (LastErrorException e) { throw new IllegalStateException("sched_getcpu( ) errorNo=" + e.getErrorCode(), e); } catch (UnsatisfiedLinkError ule) { try { final IntByReference cpu = new IntByReference(); final IntByReference node = new IntByReference(); final int ret = lib.syscall(318, cpu, node, null); if (ret != 0) { throw new IllegalStateException("getcpu( ) return " + ret); } return cpu.getValue(); } catch (LastErrorException lee) { throw new IllegalStateException("getcpu( ) errorNo=" + lee.getErrorCode(), lee); } } } @Override public int getProcessId() { return PROCESS_ID; } @Override public int getThreadId() { if (ISLINUX) { Integer tid = THREAD_ID.get(); if (tid == null) THREAD_ID.set(tid = CLibrary.INSTANCE.syscall(SYS_gettid, NO_ARGS)); return tid; } return -1; } /** * @author BegemoT */ interface CLibrary extends Library { CLibrary INSTANCE = (CLibrary) Native.loadLibrary(LIBRARY_NAME, CLibrary.class); int sched_setaffinity(final int pid, final int cpusetsize, final PointerType cpuset) throws LastErrorException; int sched_getaffinity(final int pid, final int cpusetsize, final PointerType cpuset) throws LastErrorException; int sched_getcpu() throws LastErrorException; int getcpu(final IntByReference cpu, final IntByReference node, final PointerType tcache) throws LastErrorException; int getpid() throws LastErrorException; int syscall(int number, Object... args) throws LastErrorException; } } SolarisJNAAffinity.java000066400000000000000000000045311322611020300346520ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/impl/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity.impl; import com.sun.jna.LastErrorException; import com.sun.jna.Library; import com.sun.jna.Native; import net.openhft.affinity.IAffinity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.management.ManagementFactory; import java.util.BitSet; /** * This is essentially the same as the NullAffinity implementation but with concrete * support for getThreadId(). * * @author daniel.shaya */ public enum SolarisJNAAffinity implements IAffinity { INSTANCE; private static final Logger LOGGER = LoggerFactory.getLogger(SolarisJNAAffinity.class); private final ThreadLocal THREAD_ID = new ThreadLocal<>(); @Override public BitSet getAffinity() { return new BitSet(); } @Override public void setAffinity(final BitSet affinity) { LOGGER.trace("unable to set mask to {} as the JNIa nd JNA libraries and not loaded", Utilities.toHexString(affinity)); } @Override public int getCpu() { return -1; } @Override public int getProcessId() { final String name = ManagementFactory.getRuntimeMXBean().getName(); return Integer.parseInt(name.split("@")[0]); } @Override public int getThreadId() { Integer tid = THREAD_ID.get(); if (tid == null) { tid = CLibrary.INSTANCE.pthread_self(); //The tid assumed to be an unsigned 24 bit, see net.openhft.lang.Jvm.getMaxPid() tid = tid & 0xFFFFFF; THREAD_ID.set(tid); } return tid; } interface CLibrary extends Library { CLibrary INSTANCE = (CLibrary) Native.loadLibrary("c", CLibrary.class); int pthread_self() throws LastErrorException; } } Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/impl/Utilities.java000077500000000000000000000037271322611020300332560ustar00rootroot00000000000000/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity.impl; import java.io.ByteArrayOutputStream; import java.io.PrintWriter; import java.util.BitSet; /* * Created by andre on 20/06/15. */ public final class Utilities { private Utilities() { throw new InstantiationError( "Must not instantiate this class" ); } /** * Creates a hexademical representation of the bit set * * @param set the bit set to convert * @return the hexademical string representation */ public static String toHexString(final BitSet set) { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(out); final long[] longs = set.toLongArray(); for (int i = 0; i < longs.length; i++) { writer.write(Long.toHexString(longs[i])); } writer.flush(); return new String(out.toByteArray(), java.nio.charset.StandardCharsets.UTF_8); } public static String toBinaryString(BitSet set) { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(out); final long[] longs = set.toLongArray(); for (int i = 0; i < longs.length; i++) { writer.write(Long.toBinaryString(longs[i])); } writer.flush(); return new String(out.toByteArray(), java.nio.charset.StandardCharsets.UTF_8); } } VanillaCpuLayout.java000066400000000000000000000177741322611020300344640ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/impl/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity.impl; import net.openhft.affinity.CpuLayout; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.util.*; import static java.lang.Integer.parseInt; /** * @author peter.lawrey */ public class VanillaCpuLayout implements CpuLayout { public static final int MAX_CPUS_SUPPORTED = 64; @NotNull private final List cpuDetails; private final int sockets; private final int coresPerSocket; private final int threadsPerCore; VanillaCpuLayout(@NotNull List cpuDetails) { this.cpuDetails = cpuDetails; SortedSet sockets = new TreeSet(), cores = new TreeSet(), threads = new TreeSet(); for (CpuInfo cpuDetail : cpuDetails) { sockets.add(cpuDetail.socketId); cores.add((cpuDetail.socketId << 16) + cpuDetail.coreId); threads.add(cpuDetail.threadId); } this.sockets = sockets.size(); this.coresPerSocket = cores.size() / sockets.size(); this.threadsPerCore = threads.size(); if (cpuDetails.size() != sockets() * coresPerSocket() * threadsPerCore()) { StringBuilder error = new StringBuilder(); error.append("cpuDetails.size= ").append(cpuDetails.size()) .append(" != sockets: ").append(sockets()) .append(" * coresPerSocket: ").append(coresPerSocket()) .append(" * threadsPerCore: ").append(threadsPerCore()).append('\n'); for (CpuInfo detail : cpuDetails) { error.append(detail).append('\n'); } throw new AssertionError(error); } } @NotNull public static VanillaCpuLayout fromProperties(String fileName) throws IOException { return fromProperties(openFile(fileName)); } @NotNull public static VanillaCpuLayout fromProperties(InputStream is) throws IOException { Properties prop = new Properties(); prop.load(is); return fromProperties(prop); } @NotNull public static VanillaCpuLayout fromProperties(@NotNull Properties prop) { List cpuDetails = new ArrayList(); for (int i = 0; i < MAX_CPUS_SUPPORTED; i++) { String line = prop.getProperty("" + i); if (line == null) break; String[] word = line.trim().split(" *, *"); CpuInfo details = new CpuInfo(parseInt(word[0]), parseInt(word[1]), parseInt(word[2])); cpuDetails.add(details); } return new VanillaCpuLayout(cpuDetails); } @NotNull public static VanillaCpuLayout fromCpuInfo() throws IOException { return fromCpuInfo("/proc/cpuinfo"); } @NotNull public static VanillaCpuLayout fromCpuInfo(String filename) throws IOException { return fromCpuInfo(openFile(filename)); } private static InputStream openFile(String filename) throws FileNotFoundException { try { return new FileInputStream(filename); } catch (FileNotFoundException e) { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename); if (is == null) throw e; return is; } } @NotNull public static VanillaCpuLayout fromCpuInfo(InputStream is) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line; List cpuDetails = new ArrayList(); CpuInfo details = new CpuInfo(); Map threadCount = new LinkedHashMap(); while ((line = br.readLine()) != null) { if (line.trim().isEmpty()) { String key = details.socketId + "," + details.coreId; Integer count = threadCount.get(key); if (count == null) threadCount.put(key, count = 1); else threadCount.put(key, count += 1); details.threadId = count - 1; cpuDetails.add(details); details = new CpuInfo(); details.coreId = cpuDetails.size(); continue; } String[] words = line.split("\\s*:\\s*", 2); if (words[0].equals("physical id")) details.socketId = parseInt(words[1]); else if (words[0].equals("core id")) details.coreId = parseInt(words[1]); } return new VanillaCpuLayout(cpuDetails); } @Override public int cpus() { return cpuDetails.size(); } public int sockets() { return sockets; } public int coresPerSocket() { return coresPerSocket; } @Override public int threadsPerCore() { return threadsPerCore; } @Override public int socketId(int cpuId) { return cpuDetails.get(cpuId).socketId; } @Override public int coreId(int cpuId) { return cpuDetails.get(cpuId).coreId; } @Override public int threadId(int cpuId) { return cpuDetails.get(cpuId).threadId; } @NotNull @Override public String toString() { StringBuilder sb = new StringBuilder(); for (int i = 0, cpuDetailsSize = cpuDetails.size(); i < cpuDetailsSize; i++) { CpuInfo cpuDetail = cpuDetails.get(i); sb.append(i).append(": ").append(cpuDetail).append('\n'); } return sb.toString(); } @Override public boolean equals(@Nullable Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; VanillaCpuLayout that = (VanillaCpuLayout) o; if (coresPerSocket != that.coresPerSocket) return false; if (sockets != that.sockets) return false; if (threadsPerCore != that.threadsPerCore) return false; return cpuDetails.equals(that.cpuDetails); } @Override public int hashCode() { int result = cpuDetails.hashCode(); result = 31 * result + sockets; result = 31 * result + coresPerSocket; result = 31 * result + threadsPerCore; return result; } static class CpuInfo { int socketId, coreId, threadId; CpuInfo() { } CpuInfo(int socketId, int coreId, int threadId) { this.socketId = socketId; this.coreId = coreId; this.threadId = threadId; } @NotNull @Override public String toString() { return "CpuInfo{" + "socketId=" + socketId + ", coreId=" + coreId + ", threadId=" + threadId + '}'; } @Override public boolean equals(@Nullable Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CpuInfo cpuInfo = (CpuInfo) o; if (coreId != cpuInfo.coreId) return false; if (socketId != cpuInfo.socketId) return false; return threadId == cpuInfo.threadId; } @Override public int hashCode() { int result = socketId; result = 31 * result + coreId; result = 31 * result + threadId; return result; } } } VersionHelper.java000066400000000000000000000047371322611020300340100ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/impl/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity.impl; public class VersionHelper { private static final String DELIM = "."; private final int major; private final int minor; private final int release; public VersionHelper(int major_, int minor_, int release_) { major = major_; minor = minor_; release = release_; } public VersionHelper(String ver) { if (ver != null && (ver = ver.trim()).length() > 0) { final String[] parts = ver.split("\\."); major = parts.length > 0 ? Integer.parseInt(parts[0]) : 0; minor = parts.length > 1 ? Integer.parseInt(parts[1]) : 0; release = parts.length > 2 ? Integer.parseInt(parts[2]) : 0; } else { major = minor = release = 0; } } public String toString() { return major + DELIM + minor + DELIM + release; } public boolean equals(Object o) { if (o != null && (o instanceof VersionHelper)) { VersionHelper ver = (VersionHelper) o; return this.major == ver.major && this.minor == ver.minor && this.release == ver.release; } else { return false; } } public int hashCode() { return (major << 16) | (minor << 8) | release; } @SuppressWarnings({"UnusedDeclaration"}) public boolean majorMinorEquals(final VersionHelper ver) { return ver != null && this.major == ver.major && this.minor == ver.minor; } public boolean isSameOrNewer(final VersionHelper ver) { return ver != null && (this.major > ver.major || this.major == ver.major && (this.minor > ver.minor || this.minor == ver.minor && this.release >= ver.release)); } } WindowsJNAAffinity.java000066400000000000000000000112451322611020300346700ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/affinity/impl/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity.impl; import com.sun.jna.LastErrorException; import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.PointerType; import com.sun.jna.platform.win32.Kernel32; import com.sun.jna.platform.win32.WinDef; import com.sun.jna.ptr.LongByReference; import net.openhft.affinity.IAffinity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.BitSet; /** * Implementation of {@link net.openhft.affinity.IAffinity} based on JNA call of * sched_SetThreadAffinityMask/GetProcessAffinityMask from Windows 'kernel32' library. Applicable for * most windows platforms *

* * * @author andre.monteiro */ public enum WindowsJNAAffinity implements IAffinity { INSTANCE; public static final boolean LOADED; private static final Logger LOGGER = LoggerFactory.getLogger(WindowsJNAAffinity.class); static { boolean loaded = false; try { INSTANCE.getAffinity(); loaded = true; } catch (UnsatisfiedLinkError e) { LOGGER.warn("Unable to load jna library", e); } LOADED = loaded; } private final ThreadLocal THREAD_ID = new ThreadLocal<>(); @Override public BitSet getAffinity() { final CLibrary lib = CLibrary.INSTANCE; final LongByReference cpuset1 = new LongByReference(0); final LongByReference cpuset2 = new LongByReference(0); try { final int ret = lib.GetProcessAffinityMask(-1, cpuset1, cpuset2); // Successful result is positive, according to the docs // https://msdn.microsoft.com/en-us/library/windows/desktop/ms683213%28v=vs.85%29.aspx if (ret <= 0) { throw new IllegalStateException("GetProcessAffinityMask(( -1 ), &(" + cpuset1 + "), &(" + cpuset2 + ") ) return " + ret); } long[] longs = new long[1]; longs[0] = cpuset1.getValue(); return BitSet.valueOf(longs); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return new BitSet(); } @Override public void setAffinity(final BitSet affinity) { final CLibrary lib = CLibrary.INSTANCE; WinDef.DWORD aff; long[] longs = affinity.toLongArray(); switch (longs.length) { case 0: aff = new WinDef.DWORD(0); break; case 1: aff = new WinDef.DWORD(longs[0]); break; default: throw new IllegalArgumentException("Windows API does not support more than 64 CPUs for thread affinity"); } int pid = getTid(); try { lib.SetThreadAffinityMask(pid, aff); } catch (LastErrorException e) { throw new IllegalStateException("SetThreadAffinityMask((" + pid + ") , &(" + affinity + ") ) errorNo=" + e.getErrorCode(), e); } } public int getTid() { final CLibrary lib = CLibrary.INSTANCE; try { return lib.GetCurrentThread(); } catch (LastErrorException e) { throw new IllegalStateException("GetCurrentThread( ) errorNo=" + e.getErrorCode(), e); } } @Override public int getCpu() { return -1; } @Override public int getProcessId() { return Kernel32.INSTANCE.GetCurrentProcessId(); } @Override public int getThreadId() { Integer tid = THREAD_ID.get(); if (tid == null) THREAD_ID.set(tid = Kernel32.INSTANCE.GetCurrentThreadId()); return tid; } /** * @author BegemoT */ private interface CLibrary extends Library { CLibrary INSTANCE = (CLibrary) Native.loadLibrary("kernel32", CLibrary.class); int GetProcessAffinityMask(final int pid, final PointerType lpProcessAffinityMask, final PointerType lpSystemAffinityMask) throws LastErrorException; void SetThreadAffinityMask(final int pid, final WinDef.DWORD lpProcessAffinityMask) throws LastErrorException; int GetCurrentThread() throws LastErrorException; } } Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/ticker/000077500000000000000000000000001322611020300271335ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/ticker/ITicker.java000077500000000000000000000014761322611020300313430ustar00rootroot00000000000000/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.ticker; /* * Created by Peter Lawrey on 13/07/15. */ public interface ITicker { long nanoTime(); long ticks(); long toNanos(long ticks); double toMicros(double ticks); } Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/ticker/Ticker.java000066400000000000000000000031051322611020300312160ustar00rootroot00000000000000/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.ticker; import net.openhft.ticker.impl.JNIClock; import net.openhft.ticker.impl.SystemClock; /** * Static factory for available {@link ITicker} interface implementation * * @author Peter.Lawrey */ public final class Ticker { public static final ITicker INSTANCE; static { if (JNIClock.LOADED) { INSTANCE = JNIClock.INSTANCE; } else { INSTANCE = SystemClock.INSTANCE; } } private Ticker() { throw new InstantiationError( "Must not instantiate this class" ); } /** * @return The current value of the system timer, in nanoseconds. */ public static long ticks() { return INSTANCE.ticks(); } public static long nanoTime() { return toNanos(ticks()); } public static long toNanos(long ticks) { return INSTANCE.toNanos(ticks); } public static double toMicros(long ticks) { return INSTANCE.toMicros(ticks); } }Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/ticker/impl/000077500000000000000000000000001322611020300300745ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/ticker/impl/JNIClock.java000066400000000000000000000060471322611020300323420ustar00rootroot00000000000000/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.ticker.impl; import net.openhft.ticker.ITicker; import software.chronicle.enterprise.internals.impl.NativeAffinity; import java.util.logging.Logger; /** * JNI-based implementation, trying to use rdtsc() system call * to access the most precise timer available * * @author cheremin * @since 29.12.11, 18:56 */ public enum JNIClock implements ITicker { INSTANCE; public static final boolean LOADED; private static final Logger LOGGER = Logger.getLogger(JNIClock.class.getName()); private static final int FACTOR_BITS = 17; private static final long START; private static long RDTSC_FACTOR = 1 << FACTOR_BITS; private static double RDTSC_MICRO_FACTOR = 1e-3; private static long CPU_FREQUENCY = 1000; static { boolean loaded; long start; try { // ensure it is loaded. NativeAffinity.INSTANCE.getCpu(); estimateFrequency(50); estimateFrequency(200); LOGGER.info("Estimated clock frequency was " + CPU_FREQUENCY + " MHz"); start = rdtsc0(); loaded = true; } catch (UnsatisfiedLinkError ule) { LOGGER.fine("Unable to find libCEInternals in [" + System.getProperty("java.library.path") + "] " + ule); start = 0; loaded = false; } LOADED = loaded; START = start; } static long tscToNano(final long tsc) { return (tsc * RDTSC_FACTOR) >> FACTOR_BITS; } private static void estimateFrequency(int factor) { final long start = System.nanoTime(); long now; while ((now = System.nanoTime()) == start) { } long end = start + factor * 1000000; final long start0 = rdtsc0(); while ((now = System.nanoTime()) < end) { } long end0 = rdtsc0(); end = now; RDTSC_FACTOR = ((end - start) << FACTOR_BITS) / (end0 - start0) - 1; RDTSC_MICRO_FACTOR = 1e-3 * (end - start) / (end0 - start0); CPU_FREQUENCY = (end0 - start0 + 1) * 1000 / (end - start); } native static long rdtsc0(); public long nanoTime() { return tscToNano(rdtsc0() - START); } @Override public long ticks() { return rdtsc0(); } @Override public long toNanos(long ticks) { return tscToNano(ticks); } @Override public double toMicros(double ticks) { return ticks * RDTSC_MICRO_FACTOR; } }Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/net/openhft/ticker/impl/SystemClock.java000066400000000000000000000022611322611020300332000ustar00rootroot00000000000000/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.ticker.impl; import net.openhft.ticker.ITicker; /** * Default implementation, use plain {@link System#nanoTime()} * * @author cheremin * @since 29.12.11, 18:54 */ public enum SystemClock implements ITicker { INSTANCE; @Override public long nanoTime() { return System.nanoTime(); } @Override public long ticks() { return nanoTime(); } @Override public long toNanos(long ticks) { return ticks; } @Override public double toMicros(double ticks) { return ticks / 1e3; } }Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/software/000077500000000000000000000000001322611020300252535ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/software/chronicle/000077500000000000000000000000001322611020300272215ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/software/chronicle/enterprise/000077500000000000000000000000001322611020300314015ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/software/chronicle/enterprise/internals/000077500000000000000000000000001322611020300334005ustar00rootroot00000000000000impl/000077500000000000000000000000001322611020300342625ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/software/chronicle/enterprise/internalsNativeAffinity.java000066400000000000000000000037231322611020300400520ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/main/java/software/chronicle/enterprise/internals/impl/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package software.chronicle.enterprise.internals.impl; import net.openhft.affinity.IAffinity; import java.util.BitSet; public enum NativeAffinity implements IAffinity { INSTANCE; public static final boolean LOADED; static { LOADED = loadAffinityNativeLibrary(); } private native static byte[] getAffinity0(); private native static void setAffinity0(byte[] affinity); private native static int getCpu0(); private native static int getProcessId0(); private native static int getThreadId0(); private native static long rdtsc0(); private static boolean loadAffinityNativeLibrary() { try { System.loadLibrary("CEInternals"); return true; } catch (UnsatisfiedLinkError e) { return false; } } @Override public BitSet getAffinity() { final byte[] buff = getAffinity0(); if (buff == null) { return null; } return BitSet.valueOf(buff); } @Override public void setAffinity(BitSet affinity) { setAffinity0(affinity.toByteArray()); } @Override public int getCpu() { return getCpu0(); } @Override public int getProcessId() { return getProcessId0(); } @Override public int getThreadId() { return getThreadId0(); } } Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/000077500000000000000000000000001322611020300225335ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/000077500000000000000000000000001322611020300234545ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/net/000077500000000000000000000000001322611020300242425ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/net/openhft/000077500000000000000000000000001322611020300257055ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/net/openhft/affinity/000077500000000000000000000000001322611020300275165ustar00rootroot00000000000000AffinityLockBindMain.java000066400000000000000000000050331322611020300342670ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/net/openhft/affinity/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity; import static net.openhft.affinity.AffinityStrategies.*; /** * @author peter.lawrey */ public final class AffinityLockBindMain { private AffinityLockBindMain() { throw new InstantiationError( "Must not instantiate this class" ); } public static void main(String... args) throws InterruptedException { AffinityLock al = AffinityLock.acquireLock(); try { // find a cpu on a different socket, otherwise a different core. AffinityLock readerLock = al.acquireLock(DIFFERENT_SOCKET, DIFFERENT_CORE); new Thread(new SleepRunnable(readerLock, false), "reader").start(); // find a cpu on the same core, or the same socket, or any free cpu. AffinityLock writerLock = readerLock.acquireLock(SAME_CORE, SAME_SOCKET, ANY); new Thread(new SleepRunnable(writerLock, false), "writer").start(); Thread.sleep(200); } finally { al.release(); } // allocate a whole core to the engine so it doesn't have to compete for resources. al = AffinityLock.acquireCore(false); new Thread(new SleepRunnable(al, true), "engine").start(); Thread.sleep(200); System.out.println("\nThe assignment of CPUs is\n" + AffinityLock.dumpLocks()); } static class SleepRunnable implements Runnable { private final AffinityLock affinityLock; private final boolean wholeCore; SleepRunnable(AffinityLock affinityLock, boolean wholeCore) { this.affinityLock = affinityLock; this.wholeCore = wholeCore; } public void run() { affinityLock.bind(wholeCore); try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { affinityLock.release(); } } } } AffinityLockMain.java000066400000000000000000000033351322611020300334750ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/net/openhft/affinity/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity; /** * @author peter.lawrey */ public final class AffinityLockMain { private AffinityLockMain() { throw new InstantiationError( "Must not instantiate this class" ); } public static void main(String... args) throws InterruptedException { AffinityLock al = AffinityLock.acquireLock(); try { new Thread(new SleepRunnable(), "reader").start(); new Thread(new SleepRunnable(), "writer").start(); Thread.sleep(200); } finally { al.release(); } new Thread(new SleepRunnable(), "engine").start(); Thread.sleep(200); System.out.println("\nThe assignment of CPUs is\n" + AffinityLock.dumpLocks()); } private static class SleepRunnable implements Runnable { public void run() { AffinityLock al = AffinityLock.acquireLock(); try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { al.release(); } } } } AffinityLockTest.java000066400000000000000000000227361322611020300335360ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/net/openhft/affinity/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity; import net.openhft.affinity.impl.VanillaCpuLayout; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertThat; import static org.junit.Assume.assumeTrue; /** * @author peter.lawrey */ public class AffinityLockTest { private static final Logger logger = LoggerFactory.getLogger(AffinityLockTest.class); @Test public void dumpLocksI7() throws IOException { LockInventory lockInventory = new LockInventory(VanillaCpuLayout.fromCpuInfo("i7.cpuinfo")); AffinityLock[] locks = { new AffinityLock(0, true, false, lockInventory), new AffinityLock(1, false, false, lockInventory), new AffinityLock(2, false, true, lockInventory), new AffinityLock(3, false, true, lockInventory), new AffinityLock(4, true, false, lockInventory), new AffinityLock(5, false, false, lockInventory), new AffinityLock(6, false, true, lockInventory), new AffinityLock(7, false, true, lockInventory), }; locks[2].assignedThread = new Thread(new InterrupedThread(), "logger"); locks[2].assignedThread.start(); locks[3].assignedThread = new Thread(new InterrupedThread(), "engine"); locks[3].assignedThread.start(); locks[6].assignedThread = new Thread(new InterrupedThread(), "main"); locks[7].assignedThread = new Thread(new InterrupedThread(), "tcp"); locks[7].assignedThread.start(); final String actual = LockInventory.dumpLocks(locks); assertEquals("0: General use CPU\n" + "1: CPU not available\n" + "2: Thread[logger,5,main] alive=true\n" + "3: Thread[engine,5,main] alive=true\n" + "4: General use CPU\n" + "5: CPU not available\n" + "6: Thread[main,5,main] alive=false\n" + "7: Thread[tcp,5,main] alive=true\n", actual); System.out.println(actual); locks[2].assignedThread.interrupt(); locks[3].assignedThread.interrupt(); locks[6].assignedThread.interrupt(); locks[7].assignedThread.interrupt(); } @Test public void dumpLocksI3() throws IOException { LockInventory lockInventory = new LockInventory(VanillaCpuLayout.fromCpuInfo("i3.cpuinfo")); AffinityLock[] locks = { new AffinityLock(0, true, false, lockInventory), new AffinityLock(1, false, true, lockInventory), new AffinityLock(2, true, false, lockInventory), new AffinityLock(3, false, true, lockInventory), }; locks[1].assignedThread = new Thread(new InterrupedThread(), "engine"); locks[1].assignedThread.start(); locks[3].assignedThread = new Thread(new InterrupedThread(), "main"); final String actual = LockInventory.dumpLocks(locks); assertEquals("0: General use CPU\n" + "1: Thread[engine,5,main] alive=true\n" + "2: General use CPU\n" + "3: Thread[main,5,main] alive=false\n", actual); System.out.println(actual); locks[1].assignedThread.interrupt(); } @Test public void dumpLocksCoreDuo() throws IOException { LockInventory lockInventory = new LockInventory(VanillaCpuLayout.fromCpuInfo("core.duo.cpuinfo")); AffinityLock[] locks = { new AffinityLock(0, true, false, lockInventory), new AffinityLock(1, false, true, lockInventory), }; locks[1].assignedThread = new Thread(new InterrupedThread(), "engine"); locks[1].assignedThread.start(); final String actual = LockInventory.dumpLocks(locks); assertEquals("0: General use CPU\n" + "1: Thread[engine,5,main] alive=true\n", actual); System.out.println(actual); locks[1].assignedThread.interrupt(); } @Test public void assignReleaseThread() throws IOException { if (AffinityLock.RESERVED_AFFINITY.isEmpty()) { System.out.println("Cannot run affinity test as no threads gave been reserved."); System.out.println("Use isolcpus= in grub.conf or use -D" + AffinityLock.AFFINITY_RESERVED + "={hex mask}"); return; } else if (!new File("/proc/cpuinfo").exists()) { System.out.println("Cannot run affinity test as this system doesn't have a /proc/cpuinfo file"); return; } AffinityLock.cpuLayout(VanillaCpuLayout.fromCpuInfo()); assertEquals(AffinityLock.BASE_AFFINITY, Affinity.getAffinity()); AffinityLock al = AffinityLock.acquireLock(); assertEquals(1, Affinity.getAffinity().cardinality()); al.release(); assertEquals(AffinityLock.BASE_AFFINITY, Affinity.getAffinity()); assertEquals(AffinityLock.BASE_AFFINITY, Affinity.getAffinity()); AffinityLock al2 = AffinityLock.acquireCore(); assertEquals(1, Affinity.getAffinity().cardinality()); al2.release(); assertEquals(AffinityLock.BASE_AFFINITY, Affinity.getAffinity()); } @Test public void testIssue21() throws IOException { if (!new File("/proc/cpuinfo").exists()) { System.out.println("Cannot run affinity test as this system doesn't have a /proc/cpuinfo file"); return; } AffinityLock.cpuLayout(VanillaCpuLayout.fromCpuInfo()); AffinityLock al = AffinityLock.acquireLock(); AffinityLock alForAnotherThread = al.acquireLock(AffinityStrategies.ANY); if (Runtime.getRuntime().availableProcessors() > 2) { AffinityLock alForAnotherThread2 = al.acquireLock(AffinityStrategies.ANY); assertNotSame(alForAnotherThread, alForAnotherThread2); if (alForAnotherThread.cpuId() != -1) assertNotSame(alForAnotherThread.cpuId(), alForAnotherThread2.cpuId()); alForAnotherThread2.release(); } else { assertNotSame(alForAnotherThread, al); if (alForAnotherThread.cpuId() != -1) assertNotSame(alForAnotherThread.cpuId(), al.cpuId()); } alForAnotherThread.release(); al.release(); } @Test public void testIssue19() { System.out.println("AffinityLock.PROCESSORS=" + AffinityLock.PROCESSORS); AffinityLock al = AffinityLock.acquireLock(); List locks = new ArrayList<>(); locks.add(al); for (int i = 0; i < 256; i++) locks.add(al = al.acquireLock(AffinityStrategies.DIFFERENT_SOCKET, AffinityStrategies.DIFFERENT_CORE, AffinityStrategies.SAME_SOCKET, AffinityStrategies.ANY)); for (AffinityLock lock : locks) { lock.release(); } } @Test public void testGettid() { System.out.println("cpu= " + Affinity.getCpu()); } @Test public void testAffinity() throws InterruptedException { // System.out.println("Started"); logger.info("Started"); displayStatus(); try (AffinityLock al = AffinityLock.acquireLock()) { System.out.println("Main locked"); displayStatus(); Thread t = new Thread(new Runnable() { @Override public void run() { AffinityLock al2 = al.acquireLock(AffinityStrategies.SAME_SOCKET, AffinityStrategies.ANY); System.out.println("Thread-0 locked"); displayStatus(); al2.release(); } }); t.start(); t.join(); System.out.println("Thread-0 unlocked"); displayStatus(); } System.out.println("All unlocked"); displayStatus(); } @Test public void shouldReturnLockForSpecifiedCpu() { assumeTrue(Runtime.getRuntime().availableProcessors() > 3); try (final AffinityLock affinityLock = AffinityLock.acquireLock(2)) { assertThat(affinityLock.cpuId(), is(2)); } } @Test public void lockFilesShouldBeRemovedOnRelease() { final AffinityLock lock = AffinityLock.acquireLock(); assertThat(Files.exists(Paths.get(LockCheck.toFile(lock.cpuId()).getAbsolutePath())), is(true)); lock.release(); assertThat(Files.exists(Paths.get(LockCheck.toFile(lock.cpuId()).getAbsolutePath())), is(false)); } private void displayStatus() { System.out.println(Thread.currentThread() + " on " + Affinity.getCpu() + "\n" + AffinityLock.dumpLocks()); } } AffinitySupportMain.java000066400000000000000000000032201322611020300342520ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/net/openhft/affinity/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity; /** * @author peter.lawrey */ public final class AffinitySupportMain { private AffinitySupportMain() { throw new InstantiationError( "Must not instantiate this class" ); } public static void main(String... args) { AffinityLock al = AffinityLock.acquireLock(); try { new Thread(new SleepRunnable(), "reader").start(); new Thread(new SleepRunnable(), "writer").start(); new Thread(new SleepRunnable(), "engine").start(); } finally { al.release(); } System.out.println("\nThe assignment of CPUs is\n" + AffinityLock.dumpLocks()); } private static class SleepRunnable implements Runnable { public void run() { AffinityLock al = AffinityLock.acquireLock(); try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { al.release(); } } } } AffinityThreadFactoryMain.java000066400000000000000000000033611322611020300353430ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/net/openhft/affinity/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static net.openhft.affinity.AffinityStrategies.*; /** * @author peter.lawrey */ public final class AffinityThreadFactoryMain { private static final ExecutorService ES = Executors.newFixedThreadPool(4, new AffinityThreadFactory("bg", SAME_CORE, DIFFERENT_SOCKET, ANY)); private AffinityThreadFactoryMain(){ throw new InstantiationError( "Must not instantiate this class" ); } public static void main(String... args) throws InterruptedException { for (int i = 0; i < 12; i++) ES.submit(new Callable() { @Override public Void call() throws InterruptedException { Thread.sleep(100); return null; } }); Thread.sleep(200); System.out.println("\nThe assignment of CPUs is\n" + AffinityLock.dumpLocks()); ES.shutdown(); ES.awaitTermination(1, TimeUnit.SECONDS); } } BootClassPathTest.java000066400000000000000000000005421322611020300336510ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/net/openhft/affinitypackage net.openhft.affinity; import org.junit.Test; import static org.junit.Assert.assertTrue; public class BootClassPathTest { @Test public void shouldDetectClassesOnClassPath() throws Exception { assertTrue(BootClassPath.INSTANCE.has("java.lang.Thread")); assertTrue(BootClassPath.INSTANCE.has("java.lang.Runtime")); } }InterrupedThread.java000066400000000000000000000016261322611020300335600ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/net/openhft/affinity/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity; /** * @author peter.lawrey */ class InterrupedThread implements Runnable { public void run() { try { Thread.sleep(Integer.MAX_VALUE); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/net/openhft/affinity/LockCheckTest.java000066400000000000000000000055041322611020300330530ustar00rootroot00000000000000/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity; import org.junit.Assert; import org.junit.Assume; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.RandomAccessFile; import static net.openhft.affinity.LockCheck.IS_LINUX; /** * @author Rob Austin. */ public class LockCheckTest { private static final String TMP = System.getProperty("java.io.tmpdir"); private static final String TARGET = System.getProperty("project.build.directory", findTarget()); private int cpu = 1111; @Before public void before() { Assume.assumeTrue(IS_LINUX); System.setProperty("java.io.tmpdir", TARGET + "/" + System.nanoTime()); } @Test public void test() throws IOException { Assert.assertTrue(LockCheck.isCpuFree(cpu)); LockCheck.updateCpu(cpu); Assert.assertEquals(LockCheck.getPID(), LockCheck.getProcessForCpu(cpu)); } @Test public void testPidOnLinux() { Assert.assertTrue(LockCheck.isProcessRunning(LockCheck.getPID())); } @Test public void testReplace() throws IOException { cpu++; Assert.assertTrue(LockCheck.isCpuFree(cpu + 1)); LockCheck.replacePid(cpu, 123L); Assert.assertEquals(123L, LockCheck.getProcessForCpu(cpu)); } @Test public void shouldNotBlowUpIfPidFileIsEmpty() throws Exception { LockCheck.updateCpu(cpu); final File file = LockCheck.toFile(cpu); new RandomAccessFile(file, "rw").setLength(0); LockCheck.isCpuFree(cpu); } @Test public void shouldNotBlowUpIfPidFileIsCorrupt() throws Exception { LockCheck.updateCpu(cpu); final File file = LockCheck.toFile(cpu); try (final FileWriter writer = new FileWriter(file, false)) { writer.append("not a number\nnot a date"); } LockCheck.isCpuFree(cpu); } private static String findTarget() { for (File dir = new File(System.getProperty("user.dir")); dir != null; dir = dir.getParentFile()) { File target = new File(dir, "target"); if (target.exists()) return target.getAbsolutePath(); } return TMP + "/target"; } }Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/net/openhft/affinity/impl/000077500000000000000000000000001322611020300304575ustar00rootroot00000000000000AbstractAffinityImplTest.java000066400000000000000000000054701322611020300361700ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/net/openhft/affinity/impl/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity.impl; import net.openhft.affinity.IAffinity; import org.junit.After; import org.junit.Ignore; import org.junit.Test; import java.util.BitSet; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * @author cheremin * @since 29.12.11, 20:25 */ public abstract class AbstractAffinityImplTest { protected static final int CORES = Runtime.getRuntime().availableProcessors(); protected static final BitSet CORES_MASK = new BitSet(CORES); static { CORES_MASK.set(0, CORES, true); } public abstract IAffinity getImpl(); @Test public void getAffinityCompletesGracefully() { getImpl().getAffinity(); } @Test public void getAffinityReturnsValidValue() { final BitSet affinity = getImpl().getAffinity(); assertTrue( "Affinity mask " + Utilities.toBinaryString(affinity) + " must be non-empty", !affinity.isEmpty() ); final long allCoresMask = (1L << CORES) - 1; assertTrue( "Affinity mask " + Utilities.toBinaryString(affinity) + " must be <=(2^" + CORES + "-1 = " + allCoresMask + ")", affinity.length() <= CORES_MASK.length() ); } @Test public void setAffinityCompletesGracefully() { BitSet affinity = new BitSet(1); affinity.set(0, true); getImpl().setAffinity(affinity); } @Test public void getAffinityReturnsValuePreviouslySet() { final IAffinity impl = getImpl(); for (int core = 0; core < CORES; core++) { final BitSet mask = new BitSet(); mask.set(core, true); getAffinityReturnsValuePreviouslySet(impl, mask); } } private void getAffinityReturnsValuePreviouslySet(final IAffinity impl, final BitSet mask) { impl.setAffinity(mask); final BitSet _mask = impl.getAffinity(); assertEquals(mask, _mask); } @After public void tearDown() { try { getImpl().setAffinity(CORES_MASK); } catch (Exception e) { e.printStackTrace(); } } } LinuxJNAAffinityTest.java000077500000000000000000000031771322611020300352400ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/net/openhft/affinity/impl/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity.impl; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; import java.util.BitSet; import static org.junit.Assert.assertEquals; /* * Created by Peter Lawrey on 23/03/16. */ public class LinuxJNAAffinityTest { @BeforeClass public static void checkJniLibraryPresent() { Assume.assumeTrue(LinuxJNAAffinity.LOADED); } @Test public void LinuxJNA() { int nbits = Runtime.getRuntime().availableProcessors(); BitSet affinity0 = LinuxJNAAffinity.INSTANCE.getAffinity(); System.out.println(affinity0); BitSet affinity = new BitSet(nbits); affinity.set(1); LinuxJNAAffinity.INSTANCE.setAffinity(affinity); BitSet affinity2 = LinuxJNAAffinity.INSTANCE.getAffinity(); System.out.println(affinity2); assertEquals(1, LinuxJNAAffinity.INSTANCE.getCpu()); assertEquals(affinity, affinity2); affinity.set(0, nbits); LinuxJNAAffinity.INSTANCE.setAffinity(affinity); } } NativeAffinityImpTest.java000077500000000000000000000040441322611020300354760ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/net/openhft/affinity/impl/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity.impl; import net.openhft.affinity.AffinitySupport; import net.openhft.affinity.IAffinity; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; import software.chronicle.enterprise.internals.impl.NativeAffinity; import static org.junit.Assert.assertTrue; /* * Created by andre on 22/06/15. */ public class NativeAffinityImpTest extends AbstractAffinityImplTest { @BeforeClass public static void checkJniLibraryPresent() { Assume.assumeTrue(NativeAffinity.LOADED); Assume.assumeTrue("linux".equalsIgnoreCase(System.getProperty("os.name"))); } @Override public IAffinity getImpl() { return NativeAffinity.INSTANCE; } @Test public void testGettid() { System.out.println("pid=" + getImpl().getProcessId()); System.out.println("tid=" + getImpl().getThreadId()); AffinitySupport.setThreadId(); for (int j = 0; j < 3; j++) { final int runs = 100000; long tid = 0; long time = 0; for (int i = 0; i < runs; i++) { long start = System.nanoTime(); tid = Thread.currentThread().getId(); time += System.nanoTime() - start; assertTrue(tid > 0); assertTrue(tid < 1 << 16); } System.out.printf("gettid took an average of %,d ns, tid=%d%n", time / runs, tid); } } } PosixJNAAffinityTest.java000066400000000000000000000037121322611020300352330ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/net/openhft/affinity/impl/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity.impl; import net.openhft.affinity.Affinity; import net.openhft.affinity.AffinitySupport; import net.openhft.affinity.IAffinity; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.assertTrue; /** * @author peter.lawrey */ public class PosixJNAAffinityTest extends AbstractAffinityImplTest { @BeforeClass public static void checkJniLibraryPresent() { Assume.assumeTrue("linux".equalsIgnoreCase(System.getProperty("os.name"))); } @Override public IAffinity getImpl() { return Affinity.getAffinityImpl(); } @Test public void testGettid() { System.out.println("pid=" + getImpl().getProcessId()); System.out.println("tid=" + getImpl().getThreadId()); AffinitySupport.setThreadId(); for (int j = 0; j < 3; j++) { final int runs = 100000; long tid = 0; long time = 0; for (int i = 0; i < runs; i++) { long start = System.nanoTime(); tid = Thread.currentThread().getId(); time += System.nanoTime() - start; assertTrue(tid > 0); assertTrue(tid < 1 << 16); } System.out.printf("gettid took an average of %,d ns, tid=%d%n", time / runs, tid); } } } VanillaCpuLayoutTest.java000066400000000000000000000146231322611020300353450ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/net/openhft/affinity/impl/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity.impl; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import static junit.framework.Assert.assertEquals; /** * @author peter.lawrey */ public class VanillaCpuLayoutTest { @Test public void testFromCpuInfoI7() throws IOException { final InputStream i7 = getClass().getClassLoader().getResourceAsStream("i7.cpuinfo"); VanillaCpuLayout vcl = VanillaCpuLayout.fromCpuInfo(i7); assertEquals("0: CpuInfo{socketId=0, coreId=0, threadId=0}\n" + "1: CpuInfo{socketId=0, coreId=1, threadId=0}\n" + "2: CpuInfo{socketId=0, coreId=2, threadId=0}\n" + "3: CpuInfo{socketId=0, coreId=3, threadId=0}\n" + "4: CpuInfo{socketId=0, coreId=0, threadId=1}\n" + "5: CpuInfo{socketId=0, coreId=1, threadId=1}\n" + "6: CpuInfo{socketId=0, coreId=2, threadId=1}\n" + "7: CpuInfo{socketId=0, coreId=3, threadId=1}\n", vcl.toString()); } @Test public void testFromCpuInfoOthers() throws IOException { { final InputStream is = getClass().getClassLoader().getResourceAsStream("amd64.dual.core.cpuinfo"); VanillaCpuLayout vcl = VanillaCpuLayout.fromCpuInfo(is); assertEquals("0: CpuInfo{socketId=0, coreId=0, threadId=0}\n" + "1: CpuInfo{socketId=0, coreId=1, threadId=0}\n", vcl.toString()); } { final InputStream is = getClass().getClassLoader().getResourceAsStream("core.duo.cpuinfo"); VanillaCpuLayout vcl = VanillaCpuLayout.fromCpuInfo(is); assertEquals("0: CpuInfo{socketId=0, coreId=0, threadId=0}\n" + "1: CpuInfo{socketId=0, coreId=1, threadId=0}\n", vcl.toString()); } { final InputStream is = getClass().getClassLoader().getResourceAsStream("amd64.quad.core.cpuinfo"); VanillaCpuLayout vcl = VanillaCpuLayout.fromCpuInfo(is); assertEquals("0: CpuInfo{socketId=0, coreId=0, threadId=0}\n" + "1: CpuInfo{socketId=0, coreId=1, threadId=0}\n" + "2: CpuInfo{socketId=0, coreId=2, threadId=0}\n" + "3: CpuInfo{socketId=0, coreId=3, threadId=0}\n", vcl.toString()); } { final InputStream is = getClass().getClassLoader().getResourceAsStream("dual.xeon.cpuinfo"); VanillaCpuLayout vcl = VanillaCpuLayout.fromCpuInfo(is); assertEquals("0: CpuInfo{socketId=0, coreId=0, threadId=0}\n" + "1: CpuInfo{socketId=0, coreId=0, threadId=1}\n" + "2: CpuInfo{socketId=3, coreId=3, threadId=0}\n" + "3: CpuInfo{socketId=3, coreId=3, threadId=1}\n", vcl.toString()); } { final InputStream is = getClass().getClassLoader().getResourceAsStream("i3.cpuinfo"); VanillaCpuLayout vcl = VanillaCpuLayout.fromCpuInfo(is); assertEquals("0: CpuInfo{socketId=0, coreId=0, threadId=0}\n" + "1: CpuInfo{socketId=0, coreId=2, threadId=0}\n" + "2: CpuInfo{socketId=0, coreId=0, threadId=1}\n" + "3: CpuInfo{socketId=0, coreId=2, threadId=1}\n", vcl.toString()); } { final InputStream is = getClass().getClassLoader().getResourceAsStream("q6600.noht.cpuinfo"); VanillaCpuLayout vcl = VanillaCpuLayout.fromCpuInfo(is); assertEquals("0: CpuInfo{socketId=0, coreId=0, threadId=0}\n" + "1: CpuInfo{socketId=0, coreId=2, threadId=0}\n" + "2: CpuInfo{socketId=0, coreId=1, threadId=0}\n" + "3: CpuInfo{socketId=0, coreId=3, threadId=0}\n", vcl.toString()); } { final InputStream is = getClass().getClassLoader().getResourceAsStream("dual.E5405.cpuinfo"); VanillaCpuLayout vcl = VanillaCpuLayout.fromCpuInfo(is); assertEquals("0: CpuInfo{socketId=0, coreId=0, threadId=0}\n" + "1: CpuInfo{socketId=0, coreId=1, threadId=0}\n" + "2: CpuInfo{socketId=0, coreId=2, threadId=0}\n" + "3: CpuInfo{socketId=0, coreId=3, threadId=0}\n" + "4: CpuInfo{socketId=1, coreId=4, threadId=0}\n" + "5: CpuInfo{socketId=1, coreId=5, threadId=0}\n" + "6: CpuInfo{socketId=1, coreId=6, threadId=0}\n" + "7: CpuInfo{socketId=1, coreId=7, threadId=0}\n", vcl.toString()); } } @Test public void testNoIDs() throws IOException { final InputStream noids = getClass().getClassLoader().getResourceAsStream("q6600.vm.cpuinfo"); VanillaCpuLayout vcl = VanillaCpuLayout.fromCpuInfo(noids); assertEquals("0: CpuInfo{socketId=0, coreId=0, threadId=0}\n" + "1: CpuInfo{socketId=0, coreId=1, threadId=0}\n" + "2: CpuInfo{socketId=0, coreId=2, threadId=0}\n" + "3: CpuInfo{socketId=0, coreId=3, threadId=0}\n", vcl.toString()); } @Test public void testFromProperties() throws IOException { final InputStream i7 = getClass().getClassLoader().getResourceAsStream("i7.properties"); VanillaCpuLayout vcl = VanillaCpuLayout.fromProperties(i7); assertEquals("0: CpuInfo{socketId=0, coreId=0, threadId=0}\n" + "1: CpuInfo{socketId=0, coreId=1, threadId=0}\n" + "2: CpuInfo{socketId=0, coreId=2, threadId=0}\n" + "3: CpuInfo{socketId=0, coreId=3, threadId=0}\n" + "4: CpuInfo{socketId=0, coreId=0, threadId=1}\n" + "5: CpuInfo{socketId=0, coreId=1, threadId=1}\n" + "6: CpuInfo{socketId=0, coreId=2, threadId=1}\n" + "7: CpuInfo{socketId=0, coreId=3, threadId=1}\n", vcl.toString()); } } VersionHelperTest.java000066400000000000000000000027721322611020300347000ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/net/openhft/affinity/impl/* * Copyright 20127higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.affinity.impl; import org.junit.Assert; import org.junit.Test; public class VersionHelperTest { @Test public void isSameOrNewerTest() { final VersionHelper v0 = new VersionHelper(0,0,0); final VersionHelper v2_6 = new VersionHelper(2,6,0); final VersionHelper v4_1 = new VersionHelper(4,1,1); final VersionHelper v4_9 = new VersionHelper(4,9,0); final VersionHelper v9_9 = new VersionHelper(9,9,9); VersionHelper[] versions = new VersionHelper[] { v0, v2_6, v4_1, v4_9, v9_9 }; for (int i = 0; i < versions.length; i++) { for (int j = 0; j < versions.length; j++) { Assert.assertEquals(String.format("expected %s.isSameOrNewer(%s) to be %b", versions[i], versions[j], i >= j), i >= j, versions[i].isSameOrNewer(versions[j])); } } } } Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/net/openhft/ticker/000077500000000000000000000000001322611020300271665ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/net/openhft/ticker/impl/000077500000000000000000000000001322611020300301275ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/net/openhft/ticker/impl/JNIClockTest.java000077500000000000000000000051501322611020300332320ustar00rootroot00000000000000/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.ticker.impl; import net.openhft.affinity.Affinity; import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.assertEquals; /* * Created by Peter Lawrey on 13/07/15. */ public class JNIClockTest { @Test @Ignore("TODO Fix") public void testNanoTime() throws InterruptedException { for (int i = 0; i < 20000; i++) System.nanoTime(); Affinity.setAffinity(2); JNIClock instance = JNIClock.INSTANCE; for (int i = 0; i < 50; i++) { long start0 = System.nanoTime(); long start1 = instance.ticks(); Thread.sleep(10); long time0 = System.nanoTime(); long time1 = instance.ticks(); if (i > 1) { assertEquals(10_100_000, time0 - start0, 100_000); assertEquals(10_100_000, instance.toNanos(time1 - start1), 100_000); assertEquals(instance.toNanos(time1 - start1) / 1e3, instance.toMicros(time1 - start1), 0.6); } } } @Test @Ignore("Long running") public void testJitter() { Affinity.setAffinity(2); assertEquals(2, Affinity.getCpu()); int samples = 100000, count = 0; long[] time = new long[samples]; long[] length = new long[samples]; JNIClock clock = JNIClock.INSTANCE; long start = clock.ticks(), prev = start, prevJump = start; for (int i = 0; i < 1000_000_000; i++) { long now = clock.ticks(); long delta = now - prev; if (delta > 4_000) { time[count] = now - prevJump; prevJump = now; length[count] = delta; count++; if (count >= samples) break; } prev = now; } for (int i = 0; i < count; i++) { System.out.println(((long) (clock.toMicros(time[i]) * 10)) / 10.0 + ", " + ((long) (clock.toMicros(length[i]) * 10) / 10.0)); } } }Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/org/000077500000000000000000000000001322611020300242435ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/org/junit/000077500000000000000000000000001322611020300253745ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/org/junit/Assert.java000066400000000000000000001035661322611020300275130ustar00rootroot00000000000000/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.junit; import org.hamcrest.Matcher; import org.hamcrest.MatcherAssert; import org.junit.internal.ArrayComparisonFailure; import org.junit.internal.ExactComparisonCriteria; import org.junit.internal.InexactComparisonCriteria; /** * TODO replace with 4.12 when it is released with a simple bug fix. *

* A set of assertion methods useful for writing tests. Only failed assertions * are recorded. These methods can be used directly: * Assert.assertEquals(...), however, they read better if they * are referenced through static import:
*

*

 * import static org.junit.Assert.*;
 *    ...
 *    assertEquals(...);
 * 
* * @see AssertionError * @since 4.0 */ public class Assert { /** * Protect constructor since it is a static only class */ protected Assert() { } /** * Asserts that a condition is true. If it isn't it throws an * {@link AssertionError} with the given message. * * @param message the identifying message for the {@link AssertionError} (null * okay) * @param condition condition to be checked */ static public void assertTrue(String message, boolean condition) { if (!condition) { fail(message); } } /** * Asserts that a condition is true. If it isn't it throws an * {@link AssertionError} without a message. * * @param condition condition to be checked */ static public void assertTrue(boolean condition) { assertTrue(null, condition); } /** * Asserts that a condition is false. If it isn't it throws an * {@link AssertionError} with the given message. * * @param message the identifying message for the {@link AssertionError} (null * okay) * @param condition condition to be checked */ static public void assertFalse(String message, boolean condition) { assertTrue(message, !condition); } /** * Asserts that a condition is false. If it isn't it throws an * {@link AssertionError} without a message. * * @param condition condition to be checked */ static public void assertFalse(boolean condition) { assertFalse(null, condition); } /** * Fails a test with the given message. * * @param message the identifying message for the {@link AssertionError} (null * okay) * @see AssertionError */ static public void fail(String message) { if (message == null) { throw new AssertionError(); } throw new AssertionError(message); } /** * Fails a test with no message. */ static public void fail() { fail(null); } /** * Asserts that two objects are equal. If they are not, an * {@link AssertionError} is thrown with the given message. If * expected and actual are null, * they are considered equal. * * @param message the identifying message for the {@link AssertionError} (null * okay) * @param expected expected value * @param actual actual value */ static public void assertEquals(String message, Object expected, Object actual) { if (equalsRegardingNull(expected, actual)) { return; } else if (expected instanceof String && actual instanceof String) { String cleanMessage = message == null ? "" : message; throw new ComparisonFailure(cleanMessage, (String) expected, (String) actual); } else { failNotEquals(message, expected, actual); } } private static boolean equalsRegardingNull(Object expected, Object actual) { if (expected == null) { return actual == null; } return isEquals(expected, actual); } private static boolean isEquals(Object expected, Object actual) { return expected.equals(actual); } /** * Asserts that two objects are equal. If they are not, an * {@link AssertionError} without a message is thrown. If * expected and actual are null, * they are considered equal. * * @param expected expected value * @param actual the value to check against expected */ static public void assertEquals(Object expected, Object actual) { assertEquals(null, expected, actual); } /** * Asserts that two objects are not equals. If they are, an * {@link AssertionError} is thrown with the given message. If * first and second are null, * they are considered equal. * * @param message the identifying message for the {@link AssertionError} (null * okay) * @param first first value to check * @param second the value to check against first */ static public void assertNotEquals(String message, Object first, Object second) { if (equalsRegardingNull(first, second)) { failEquals(message, first); } } /** * Asserts that two objects are not equals. If they are, an * {@link AssertionError} without a message is thrown. If * first and second are null, * they are considered equal. * * @param first first value to check * @param second the value to check against first */ static public void assertNotEquals(Object first, Object second) { assertNotEquals(null, first, second); } private static void failEquals(String message, Object actual) { String formatted = "Values should be different. "; if (message != null) { formatted = message + ". "; } formatted += "Actual: " + actual; fail(formatted); } /** * Asserts that two longs are not equals. If they are, an * {@link AssertionError} is thrown with the given message. * * @param message the identifying message for the {@link AssertionError} (null * okay) * @param first first value to check * @param second the value to check against first */ static public void assertNotEquals(String message, long first, long second) { assertNotEquals(message, (Long) first, (Long) second); } /** * Asserts that two longs are not equals. If they are, an * {@link AssertionError} without a message is thrown. * * @param first first value to check * @param second the value to check against first */ static public void assertNotEquals(long first, long second) { assertNotEquals(null, first, second); } /** * Asserts that two doubles or floats are not equal to within a positive delta. * If they are, an {@link AssertionError} is thrown with the given * message. If the expected value is infinity then the delta value is * ignored. NaNs are considered equal: * assertNotEquals(Double.NaN, Double.NaN, *) fails * * @param message the identifying message for the {@link AssertionError} (null * okay) * @param first first value to check * @param second the value to check against first * @param delta the maximum delta between expected and * actual for which both numbers are still * considered equal. */ static public void assertNotEquals(String message, double first, double second, double delta) { if (!doubleIsDifferent(first, second, delta)) { failEquals(message, new Double(first)); } } /** * Asserts that two doubles or floats are not equal to within a positive delta. * If they are, an {@link AssertionError} is thrown. If the expected * value is infinity then the delta value is ignored.NaNs are considered * equal: assertNotEquals(Double.NaN, Double.NaN, *) fails * * @param first first value to check * @param second the value to check against first * @param delta the maximum delta between expected and * actual for which both numbers are still * considered equal. */ static public void assertNotEquals(double first, double second, double delta) { assertNotEquals(null, first, second, delta); } /** * Asserts that two object arrays are equal. If they are not, an * {@link AssertionError} is thrown with the given message. If * expecteds and actuals are null, * they are considered equal. * * @param message the identifying message for the {@link AssertionError} (null * okay) * @param expecteds Object array or array of arrays (multi-dimensional array) with * expected values. * @param actuals Object array or array of arrays (multi-dimensional array) with * actual values */ public static void assertArrayEquals(String message, Object[] expecteds, Object[] actuals) throws ArrayComparisonFailure { internalArrayEquals(message, expecteds, actuals); } /** * Asserts that two object arrays are equal. If they are not, an * {@link AssertionError} is thrown. If expected and * actual are null, they are considered * equal. * * @param expecteds Object array or array of arrays (multi-dimensional array) with * expected values * @param actuals Object array or array of arrays (multi-dimensional array) with * actual values */ public static void assertArrayEquals(Object[] expecteds, Object[] actuals) { assertArrayEquals(null, expecteds, actuals); } /** * Asserts that two byte arrays are equal. If they are not, an * {@link AssertionError} is thrown with the given message. * * @param message the identifying message for the {@link AssertionError} (null * okay) * @param expecteds byte array with expected values. * @param actuals byte array with actual values */ public static void assertArrayEquals(String message, byte[] expecteds, byte[] actuals) throws ArrayComparisonFailure { internalArrayEquals(message, expecteds, actuals); } /** * Asserts that two byte arrays are equal. If they are not, an * {@link AssertionError} is thrown. * * @param expecteds byte array with expected values. * @param actuals byte array with actual values */ public static void assertArrayEquals(byte[] expecteds, byte[] actuals) { assertArrayEquals(null, expecteds, actuals); } /** * Asserts that two char arrays are equal. If they are not, an * {@link AssertionError} is thrown with the given message. * * @param message the identifying message for the {@link AssertionError} (null * okay) * @param expecteds char array with expected values. * @param actuals char array with actual values */ public static void assertArrayEquals(String message, char[] expecteds, char[] actuals) throws ArrayComparisonFailure { internalArrayEquals(message, expecteds, actuals); } /** * Asserts that two char arrays are equal. If they are not, an * {@link AssertionError} is thrown. * * @param expecteds char array with expected values. * @param actuals char array with actual values */ public static void assertArrayEquals(char[] expecteds, char[] actuals) { assertArrayEquals(null, expecteds, actuals); } /** * Asserts that two short arrays are equal. If they are not, an * {@link AssertionError} is thrown with the given message. * * @param message the identifying message for the {@link AssertionError} (null * okay) * @param expecteds short array with expected values. * @param actuals short array with actual values */ public static void assertArrayEquals(String message, short[] expecteds, short[] actuals) throws ArrayComparisonFailure { internalArrayEquals(message, expecteds, actuals); } /** * Asserts that two short arrays are equal. If they are not, an * {@link AssertionError} is thrown. * * @param expecteds short array with expected values. * @param actuals short array with actual values */ public static void assertArrayEquals(short[] expecteds, short[] actuals) { assertArrayEquals(null, expecteds, actuals); } /** * Asserts that two int arrays are equal. If they are not, an * {@link AssertionError} is thrown with the given message. * * @param message the identifying message for the {@link AssertionError} (null * okay) * @param expecteds int array with expected values. * @param actuals int array with actual values */ public static void assertArrayEquals(String message, int[] expecteds, int[] actuals) throws ArrayComparisonFailure { internalArrayEquals(message, expecteds, actuals); } /** * Asserts that two int arrays are equal. If they are not, an * {@link AssertionError} is thrown. * * @param expecteds int array with expected values. * @param actuals int array with actual values */ public static void assertArrayEquals(int[] expecteds, int[] actuals) { assertArrayEquals(null, expecteds, actuals); } /** * Asserts that two long arrays are equal. If they are not, an * {@link AssertionError} is thrown with the given message. * * @param message the identifying message for the {@link AssertionError} (null * okay) * @param expecteds long array with expected values. * @param actuals long array with actual values */ public static void assertArrayEquals(String message, long[] expecteds, long[] actuals) throws ArrayComparisonFailure { internalArrayEquals(message, expecteds, actuals); } /** * Asserts that two long arrays are equal. If they are not, an * {@link AssertionError} is thrown. * * @param expecteds long array with expected values. * @param actuals long array with actual values */ public static void assertArrayEquals(long[] expecteds, long[] actuals) { assertArrayEquals(null, expecteds, actuals); } /** * Asserts that two double arrays are equal. If they are not, an * {@link AssertionError} is thrown with the given message. * * @param message the identifying message for the {@link AssertionError} (null * okay) * @param expecteds double array with expected values. * @param actuals double array with actual values */ public static void assertArrayEquals(String message, double[] expecteds, double[] actuals, double delta) throws ArrayComparisonFailure { new InexactComparisonCriteria(delta).arrayEquals(message, expecteds, actuals); } /** * Asserts that two double arrays are equal. If they are not, an * {@link AssertionError} is thrown. * * @param expecteds double array with expected values. * @param actuals double array with actual values */ public static void assertArrayEquals(double[] expecteds, double[] actuals, double delta) { assertArrayEquals(null, expecteds, actuals, delta); } /** * Asserts that two float arrays are equal. If they are not, an * {@link AssertionError} is thrown with the given message. * * @param message the identifying message for the {@link AssertionError} (null * okay) * @param expecteds float array with expected values. * @param actuals float array with actual values */ public static void assertArrayEquals(String message, float[] expecteds, float[] actuals, float delta) throws ArrayComparisonFailure { new InexactComparisonCriteria(delta).arrayEquals(message, expecteds, actuals); } /** * Asserts that two float arrays are equal. If they are not, an * {@link AssertionError} is thrown. * * @param expecteds float array with expected values. * @param actuals float array with actual values */ public static void assertArrayEquals(float[] expecteds, float[] actuals, float delta) { assertArrayEquals(null, expecteds, actuals, delta); } /** * Asserts that two object arrays are equal. If they are not, an * {@link AssertionError} is thrown with the given message. If * expecteds and actuals are null, * they are considered equal. * * @param message the identifying message for the {@link AssertionError} (null * okay) * @param expecteds Object array or array of arrays (multi-dimensional array) with * expected values. * @param actuals Object array or array of arrays (multi-dimensional array) with * actual values */ private static void internalArrayEquals(String message, Object expecteds, Object actuals) throws ArrayComparisonFailure { new ExactComparisonCriteria().arrayEquals(message, expecteds, actuals); } /** * Asserts that two doubles are equal to within a positive delta. * If they are not, an {@link AssertionError} is thrown with the given * message. If the expected value is infinity then the delta value is * ignored. NaNs are considered equal: * assertEquals(Double.NaN, Double.NaN, *) passes * * @param message the identifying message for the {@link AssertionError} (null * okay) * @param expected expected value * @param actual the value to check against expected * @param delta the maximum delta between expected and * actual for which both numbers are still * considered equal. */ static public void assertEquals(String message, double expected, double actual, double delta) { if (doubleIsDifferent(expected, actual, delta)) { failNotEquals(message, new Double(expected), new Double(actual)); } } /** * Asserts that two floats are equal to within a positive delta. * If they are not, an {@link AssertionError} is thrown with the given * message. If the expected value is infinity then the delta value is * ignored. NaNs are considered equal: * assertEquals(Float.NaN, Float.NaN, *) passes * * @param message the identifying message for the {@link AssertionError} (null * okay) * @param expected expected value * @param actual the value to check against expected * @param delta the maximum delta between expected and * actual for which both numbers are still * considered equal. */ static public void assertEquals(String message, float expected, float actual, float delta) { if (Float.compare(expected, actual) == 0) { return; } if (!(Math.abs(expected - actual) <= delta)) { failNotEquals(message, new Float(expected), new Float(actual)); } } static private boolean doubleIsDifferent(double d1, double d2, double delta) { if (Double.compare(d1, d2) == 0) { return false; } return (Math.abs(d1 - d2) > delta); } /** * Asserts that two longs are equal. If they are not, an * {@link AssertionError} is thrown. * * @param expected expected long value. * @param actual actual long value */ static public void assertEquals(long expected, long actual) { if (expected != actual) assertEquals(null, expected, actual); } /** * Asserts that two longs are equal. If they are not, an * {@link AssertionError} is thrown with the given message. * * @param message the identifying message for the {@link AssertionError} (null * okay) * @param expected long expected value. * @param actual long actual value */ static public void assertEquals(String message, long expected, long actual) { assertEquals(message, (Long) expected, (Long) actual); } /** * @deprecated Use * assertEquals(double expected, double actual, double delta) * instead */ @Deprecated static public void assertEquals(double expected, double actual) { assertEquals(null, expected, actual); } /** * @deprecated Use * assertEquals(String message, double expected, double actual, double delta) * instead */ @Deprecated static public void assertEquals(String message, double expected, double actual) { fail("Use assertEquals(expected, actual, delta) to compare floating-point numbers"); } /** * Asserts that two doubles are equal to within a positive delta. * If they are not, an {@link AssertionError} is thrown. If the expected * value is infinity then the delta value is ignored.NaNs are considered * equal: assertEquals(Double.NaN, Double.NaN, *) passes * * @param expected expected value * @param actual the value to check against expected * @param delta the maximum delta between expected and * actual for which both numbers are still * considered equal. */ static public void assertEquals(double expected, double actual, double delta) { assertEquals(null, expected, actual, delta); } /** * Asserts that two floats are equal to within a positive delta. * If they are not, an {@link AssertionError} is thrown. If the expected * value is infinity then the delta value is ignored. NaNs are considered * equal: assertEquals(Float.NaN, Float.NaN, *) passes * * @param expected expected value * @param actual the value to check against expected * @param delta the maximum delta between expected and * actual for which both numbers are still * considered equal. */ static public void assertEquals(float expected, float actual, float delta) { assertEquals(null, expected, actual, delta); } /** * Asserts that an object isn't null. If it is an {@link AssertionError} is * thrown with the given message. * * @param message the identifying message for the {@link AssertionError} (null * okay) * @param object Object to check or null */ static public void assertNotNull(String message, Object object) { assertTrue(message, object != null); } /** * Asserts that an object isn't null. If it is an {@link AssertionError} is * thrown. * * @param object Object to check or null */ static public void assertNotNull(Object object) { assertNotNull(null, object); } /** * Asserts that an object is null. If it is not, an {@link AssertionError} * is thrown with the given message. * * @param message the identifying message for the {@link AssertionError} (null * okay) * @param object Object to check or null */ static public void assertNull(String message, Object object) { if (object == null) { return; } failNotNull(message, object); } /** * Asserts that an object is null. If it isn't an {@link AssertionError} is * thrown. * * @param object Object to check or null */ static public void assertNull(Object object) { assertNull(null, object); } static private void failNotNull(String message, Object actual) { String formatted = ""; if (message != null) { formatted = message + " "; } fail(formatted + "expected null, but was:<" + actual + ">"); } /** * Asserts that two objects refer to the same object. If they are not, an * {@link AssertionError} is thrown with the given message. * * @param message the identifying message for the {@link AssertionError} (null * okay) * @param expected the expected object * @param actual the object to compare to expected */ static public void assertSame(String message, Object expected, Object actual) { if (expected == actual) { return; } failNotSame(message, expected, actual); } /** * Asserts that two objects refer to the same object. If they are not the * same, an {@link AssertionError} without a message is thrown. * * @param expected the expected object * @param actual the object to compare to expected */ static public void assertSame(Object expected, Object actual) { assertSame(null, expected, actual); } /** * Asserts that two objects do not refer to the same object. If they do * refer to the same object, an {@link AssertionError} is thrown with the * given message. * * @param message the identifying message for the {@link AssertionError} (null * okay) * @param unexpected the object you don't expect * @param actual the object to compare to unexpected */ static public void assertNotSame(String message, Object unexpected, Object actual) { if (unexpected == actual) { failSame(message); } } /** * Asserts that two objects do not refer to the same object. If they do * refer to the same object, an {@link AssertionError} without a message is * thrown. * * @param unexpected the object you don't expect * @param actual the object to compare to unexpected */ static public void assertNotSame(Object unexpected, Object actual) { assertNotSame(null, unexpected, actual); } static private void failSame(String message) { String formatted = ""; if (message != null) { formatted = message + " "; } fail(formatted + "expected not same"); } static private void failNotSame(String message, Object expected, Object actual) { String formatted = ""; if (message != null) { formatted = message + " "; } fail(formatted + "expected same:<" + expected + "> was not:<" + actual + ">"); } static private void failNotEquals(String message, Object expected, Object actual) { fail(format(message, expected, actual)); } static String format(String message, Object expected, Object actual) { String formatted = ""; if (message != null && !message.equals("")) { formatted = message + " "; } String expectedString = String.valueOf(expected); String actualString = String.valueOf(actual); if (expectedString.equals(actualString)) { return formatted + "expected: " + formatClassAndValue(expected, expectedString) + " but was: " + formatClassAndValue(actual, actualString); } else { return formatted + "expected:<" + expectedString + "> but was:<" + actualString + ">"; } } private static String formatClassAndValue(Object value, String valueString) { String className = value == null ? "null" : value.getClass().getName(); return className + "<" + valueString + ">"; } /** * Asserts that two object arrays are equal. If they are not, an * {@link AssertionError} is thrown with the given message. If * expecteds and actuals are null, * they are considered equal. * * @param message the identifying message for the {@link AssertionError} (null * okay) * @param expecteds Object array or array of arrays (multi-dimensional array) with * expected values. * @param actuals Object array or array of arrays (multi-dimensional array) with * actual values * @deprecated use assertArrayEquals */ @Deprecated public static void assertEquals(String message, Object[] expecteds, Object[] actuals) { assertArrayEquals(message, expecteds, actuals); } /** * Asserts that two object arrays are equal. If they are not, an * {@link AssertionError} is thrown. If expected and * actual are null, they are considered * equal. * * @param expecteds Object array or array of arrays (multi-dimensional array) with * expected values * @param actuals Object array or array of arrays (multi-dimensional array) with * actual values * @deprecated use assertArrayEquals */ @Deprecated public static void assertEquals(Object[] expecteds, Object[] actuals) { assertArrayEquals(expecteds, actuals); } /** * Asserts that actual satisfies the condition specified by * matcher. If not, an {@link AssertionError} is thrown with * information about the matcher and failing value. Example: *

*

     *   assertThat(0, is(1)); // fails:
     *     // failure message:
     *     // expected: is <1>
     *     // got value: <0>
     *   assertThat(0, is(not(1))) // passes
     * 
*

* org.hamcrest.Matcher does not currently document the meaning * of its type parameter T. This method assumes that a matcher * typed as Matcher<T> can be meaningfully applied only * to values that could be assigned to a variable of type T. * * @param the static type accepted by the matcher (this can flag obvious * compile-time problems such as {@code assertThat(1, is("a"))} * @param actual the computed value being compared * @param matcher an expression, built of {@link Matcher}s, specifying allowed * values * @see org.hamcrest.CoreMatchers * @see org.hamcrest.MatcherAssert */ public static void assertThat(T actual, Matcher matcher) { assertThat("", actual, matcher); } /** * Asserts that actual satisfies the condition specified by * matcher. If not, an {@link AssertionError} is thrown with * the reason and information about the matcher and failing value. Example: *

*

     *   assertThat("Help! Integers don't work", 0, is(1)); // fails:
     *     // failure message:
     *     // Help! Integers don't work
     *     // expected: is <1>
     *     // got value: <0>
     *   assertThat("Zero is one", 0, is(not(1))) // passes
     * 
*

* org.hamcrest.Matcher does not currently document the meaning * of its type parameter T. This method assumes that a matcher * typed as Matcher<T> can be meaningfully applied only * to values that could be assigned to a variable of type T. * * @param reason additional information about the error * @param the static type accepted by the matcher (this can flag obvious * compile-time problems such as {@code assertThat(1, is("a"))} * @param actual the computed value being compared * @param matcher an expression, built of {@link Matcher}s, specifying allowed * values * @see org.hamcrest.CoreMatchers * @see org.hamcrest.MatcherAssert */ public static void assertThat(String reason, T actual, Matcher matcher) { MatcherAssert.assertThat(reason, actual, matcher); } } Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/software/000077500000000000000000000000001322611020300253065ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/software/chronicle/000077500000000000000000000000001322611020300272545ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/software/chronicle/enterprise/000077500000000000000000000000001322611020300314345ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/software/chronicle/enterprise/internals/000077500000000000000000000000001322611020300334335ustar00rootroot00000000000000JnaAffinityTest.java000066400000000000000000000070311322611020300372620ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/software/chronicle/enterprise/internals/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package software.chronicle.enterprise.internals; import net.openhft.affinity.IAffinity; import net.openhft.affinity.impl.LinuxJNAAffinity; import net.openhft.affinity.impl.Utilities; import org.junit.After; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; import java.util.BitSet; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * @author peter.lawrey */ public class JnaAffinityTest { protected static final int CORES = Runtime.getRuntime().availableProcessors(); protected static final BitSet CORES_MASK = new BitSet(CORES); static { CORES_MASK.set(0, CORES, true); } @BeforeClass public static void checkJniLibraryPresent() { Assume.assumeTrue(LinuxJNAAffinity.LOADED); } @Test public void getAffinityCompletesGracefully() { System.out.println("affinity: " + Utilities.toBinaryString(getImpl().getAffinity())); } @Test public void getAffinityReturnsValidValue() { final BitSet affinity = getImpl().getAffinity(); assertTrue( "Affinity mask " + Utilities.toBinaryString(affinity) + " must be non-empty", !affinity.isEmpty() ); final int allCoresMask = (1 << CORES) - 1; assertTrue( "Affinity mask " + Utilities.toBinaryString(affinity) + " must be <=(2^" + CORES + "-1 = " + allCoresMask + ")", affinity.length() <= CORES_MASK.length() ); } @Test public void setAffinityCompletesGracefully() { BitSet affinity = new BitSet(1); affinity.set(0, true); getImpl().setAffinity(affinity); } @Test public void getAffinityReturnsValuePreviouslySet() { String osName = System.getProperty("os.name"); if (!osName.startsWith("Linux")) { System.out.println("Skipping Linux tests"); return; } final IAffinity impl = LinuxJNAAffinity.INSTANCE; final int cores = CORES; for (int core = 0; core < cores; core++) { final BitSet mask = new BitSet(); mask.set(core, true); getAffinityReturnsValuePreviouslySet(impl, mask); } } @Test public void showOtherIds() { System.out.println("processId: " + LinuxJNAAffinity.INSTANCE.getProcessId()); System.out.println("threadId: " + LinuxJNAAffinity.INSTANCE.getThreadId()); System.out.println("cpu: " + LinuxJNAAffinity.INSTANCE.getCpu()); } private void getAffinityReturnsValuePreviouslySet(final IAffinity impl, final BitSet mask) { impl.setAffinity(mask); final BitSet _mask = impl.getAffinity(); assertEquals(mask, _mask); } @After public void tearDown() { getImpl().setAffinity(CORES_MASK); } public IAffinity getImpl() { return LinuxJNAAffinity.INSTANCE; } } NativeAffinityTest.java000066400000000000000000000110011322611020300377700ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/java/software/chronicle/enterprise/internals/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package software.chronicle.enterprise.internals; import net.openhft.affinity.IAffinity; import net.openhft.affinity.impl.LinuxJNAAffinity; import net.openhft.affinity.impl.Utilities; import org.junit.*; import software.chronicle.enterprise.internals.impl.NativeAffinity; import java.util.BitSet; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * @author peter.lawrey */ public class NativeAffinityTest { protected static final int CORES = Runtime.getRuntime().availableProcessors(); protected static final BitSet CORES_MASK = new BitSet(CORES); static { CORES_MASK.set(0, CORES, true); } @BeforeClass public static void checkJniLibraryPresent() { Assume.assumeTrue(NativeAffinity.LOADED); } @Test public void getAffinityCompletesGracefully() { System.out.println("affinity: " + Utilities.toBinaryString(getImpl().getAffinity())); } @Test public void getAffinityReturnsValidValue() { final BitSet affinity = getImpl().getAffinity(); assertTrue( "Affinity mask " + Utilities.toBinaryString(affinity) + " must be non-empty", !affinity.isEmpty() ); final int allCoresMask = (1 << CORES) - 1; assertTrue( "Affinity mask " + Utilities.toBinaryString(affinity) + " must be <=(2^" + CORES + "-1 = " + allCoresMask + ")", affinity.length() <= CORES_MASK.length() ); } @Test public void setAffinityCompletesGracefully() { BitSet affinity = new BitSet(1); affinity.set(0, true); getImpl().setAffinity(affinity); } @Test @Ignore("TODO AFFINITY-25") public void getAffinityReturnsValuePreviouslySet() { String osName = System.getProperty("os.name"); if (!osName.startsWith("Linux")) { System.out.println("Skipping Linux tests"); return; } final IAffinity impl = NativeAffinity.INSTANCE; final int cores = CORES; for (int core = 0; core < cores; core++) { final BitSet mask = new BitSet(); mask.set(core, true); getAffinityReturnsValuePreviouslySet(impl, mask); } } @Test @Ignore("TODO AFFINITY-25") public void JNAwithJNI() { String osName = System.getProperty("os.name"); if (!osName.startsWith("Linux")) { System.out.println("Skipping Linux tests"); return; } int nbits = Runtime.getRuntime().availableProcessors(); BitSet affinity = new BitSet(nbits); affinity.set(1); NativeAffinity.INSTANCE.setAffinity(affinity); BitSet affinity2 = LinuxJNAAffinity.INSTANCE.getAffinity(); assertEquals(1, NativeAffinity.INSTANCE.getCpu()); assertEquals(affinity, affinity2); affinity.clear(); affinity.set(2); LinuxJNAAffinity.INSTANCE.setAffinity(affinity); BitSet affinity3 = NativeAffinity.INSTANCE.getAffinity(); assertEquals(2, LinuxJNAAffinity.INSTANCE.getCpu()); assertEquals(affinity, affinity3); affinity.set(0, nbits); LinuxJNAAffinity.INSTANCE.setAffinity(affinity); } @Test public void showOtherIds() { System.out.println("processId: " + NativeAffinity.INSTANCE.getProcessId()); System.out.println("threadId: " + NativeAffinity.INSTANCE.getThreadId()); System.out.println("cpu: " + NativeAffinity.INSTANCE.getCpu()); } private void getAffinityReturnsValuePreviouslySet(final IAffinity impl, final BitSet mask) { impl.setAffinity(mask); final BitSet _mask = impl.getAffinity(); assertEquals(mask, _mask); } @After public void tearDown() { getImpl().setAffinity(CORES_MASK); } public IAffinity getImpl() { return NativeAffinity.INSTANCE; } } Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/resources/000077500000000000000000000000001322611020300245455ustar00rootroot00000000000000Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/resources/amd64.dual.core.cpuinfo000066400000000000000000000031641322611020300307240ustar00rootroot00000000000000processor : 0 vendor_id : AuthenticAMD cpu family : 15 model : 107 model name : Athlon 64 Dual Core 5000+ stepping : 2 cpu MHz : 2599.998 cache size : 512 KB physical id : 0 siblings : 2 core id : 0 cpu cores : 2 fpu : yes fpu_exception : yes cpuid level : 1 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt rdtscp lm 3dnowext 3dnow rep_good pni cx16 lahf_lm cmp_legacy svm extapic cr8_legacy 3dnowprefetch bogomips : 5204.18 TLB size : 1024 4K pages clflush size : 64 cache_alignment : 64 address sizes : 40 bits physical, 48 bits virtual power management: ts fid vid ttp tm stc 100mhzsteps processor : 1 vendor_id : AuthenticAMD cpu family : 15 model : 107 model name : Athlon 64 Dual Core 5000+ stepping : 2 cpu MHz : 2599.998 cache size : 512 KB physical id : 0 siblings : 2 core id : 1 cpu cores : 2 fpu : yes fpu_exception : yes cpuid level : 1 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt rdtscp lm 3dnowext 3dnow rep_good pni cx16 lahf_lm cmp_legacy svm extapic cr8_legacy 3dnowprefetch bogomips : 5200.04 TLB size : 1024 4K pages clflush size : 64 cache_alignment : 64 address sizes : 40 bits physical, 48 bits virtual power management: ts fid vid ttp tm stc 100mhzsteps Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/resources/amd64.quad.core.cpuinfo000066400000000000000000000064641322611020300307370ustar00rootroot00000000000000processor : 0 vendor_id : AuthenticAMD cpu family : 16 model : 4 model name : Quad-Core AMD Opteron(tm) Processor 2374 HE stepping : 2 cpu MHz : 2194.255 cache size : 512 KB physical id : 0 siblings : 4 core id : 0 cpu cores : 4 apicid : 0 initial apicid : 0 fpu : yes fpu_exception : yes cpuid level : 5 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm 3dnowext 3dnow constant_tsc rep_good nonstop_tsc extd_apicid pni monitor cx16 popcnt lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt bogomips : 4388.50 TLB size : 1024 4K pages clflush size : 64 cache_alignment : 64 address sizes : 48 bits physical, 48 bits virtual power management: ts ttp tm stc 100mhzsteps hwpstate processor : 1 vendor_id : AuthenticAMD cpu family : 16 model : 4 model name : Quad-Core AMD Opteron(tm) Processor 2374 HE stepping : 2 cpu MHz : 2194.255 cache size : 512 KB physical id : 0 siblings : 4 core id : 1 cpu cores : 4 apicid : 1 initial apicid : 1 fpu : yes fpu_exception : yes cpuid level : 5 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm 3dnowext 3dnow constant_tsc rep_good nonstop_tsc extd_apicid pni monitor cx16 popcnt lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt bogomips : 4389.05 TLB size : 1024 4K pages clflush size : 64 cache_alignment : 64 address sizes : 48 bits physical, 48 bits virtual power management: ts ttp tm stc 100mhzsteps hwpstate processor : 2 vendor_id : AuthenticAMD cpu family : 16 model : 4 model name : Quad-Core AMD Opteron(tm) Processor 2374 HE stepping : 2 cpu MHz : 2194.255 cache size : 512 KB physical id : 0 siblings : 4 core id : 2 cpu cores : 4 apicid : 2 initial apicid : 2 fpu : yes fpu_exception : yes cpuid level : 5 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm 3dnowext 3dnow constant_tsc rep_good nonstop_tsc extd_apicid pni monitor cx16 popcnt lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt bogomips : 4389.05 TLB size : 1024 4K pages clflush size : 64 cache_alignment : 64 address sizes : 48 bits physical, 48 bits virtual power management: ts ttp tm stc 100mhzsteps hwpstate processor : 3 vendor_id : AuthenticAMD cpu family : 16 model : 4 model name : Quad-Core AMD Opteron(tm) Processor 2374 HE stepping : 2 cpu MHz : 2194.255 cache size : 512 KB physical id : 0 siblings : 4 core id : 3 cpu cores : 4 apicid : 3 initial apicid : 3 fpu : yes fpu_exception : yes cpuid level : 5 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm 3dnowext 3dnow constant_tsc rep_good nonstop_tsc extd_apicid pni monitor cx16 popcnt lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt bogomips : 4389.05 TLB size : 1024 4K pages clflush size : 64 cache_alignment : 64 address sizes : 48 bits physical, 48 bits virtual power management: ts ttp tm stc 100mhzsteps hwpstate Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/resources/core.duo.cpuinfo000066400000000000000000000026101322611020300276470ustar00rootroot00000000000000processor : 0 vendor_id : GenuineIntel cpu family : 6 model : 23 model name : Intel(R) Core(TM)2 Duo CPU T8300 @ 2.40GHz stepping : 6 cpu MHz : 800.000 cache size : 3072 KB physical id : 0 siblings : 2 core id : 0 cpu cores : 2 apicid : 0 initial apicid : 0 fpu : yes fpu_exception : yes cpuid level : 10 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx lm constant_tsc arch_perfmon pebs bts rep_good nopl pni monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr sse4_1 lahf_lm ida bogomips : 4787.93 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: processor : 1 vendor_id : GenuineIntel cpu family : 6 model : 23 model name : Intel(R) Core(TM)2 Duo CPU T8300 @ 2.40GHz stepping : 6 cpu MHz : 800.000 cache size : 3072 KB physical id : 0 siblings : 2 core id : 1 cpu cores : 2 apicid : 1 initial apicid : 1 fpu : yes fpu_exception : yes cpuid level : 10 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx lm constant_tsc arch_perfmon pebs bts rep_good nopl pni monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr sse4_1 lahf_lm ida bogomips : 4787.96 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/resources/dual.E5405.cpuinfo000066400000000000000000000125001322611020300275560ustar00rootroot00000000000000processor : 0 vendor_id : GenuineIntel cpu family : 6 model : 7 model name : Intel(R) Xeon(R) CPU E5405 @ 2.00GHz stepping : 6 cpu MHz : 1995.138 cache size : 6144 KB physical id : 0 siblings : 4 core id : 0 cpu cores : 4 fdiv_bug : no hlt_bug : no f00f_bug : no coma_bug : no fpu : yes fpu_exception : yes cpuid level : 10 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx lm pni monitor ds_cpl tm2 xtpr bogomips : 3992.50 processor : 1 vendor_id : GenuineIntel cpu family : 6 model : 7 model name : Intel(R) Xeon(R) CPU E5405 @ 2.00GHz stepping : 6 cpu MHz : 1995.138 cache size : 6144 KB physical id : 0 siblings : 4 core id : 1 cpu cores : 4 fdiv_bug : no hlt_bug : no f00f_bug : no coma_bug : no fpu : yes fpu_exception : yes cpuid level : 10 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx lm pni monitor ds_cpl tm2 xtpr bogomips : 3990.03 processor : 2 vendor_id : GenuineIntel cpu family : 6 model : 7 model name : Intel(R) Xeon(R) CPU E5405 @ 2.00GHz stepping : 6 cpu MHz : 1995.138 cache size : 6144 KB physical id : 0 siblings : 4 core id : 2 cpu cores : 4 fdiv_bug : no hlt_bug : no f00f_bug : no coma_bug : no fpu : yes fpu_exception : yes cpuid level : 10 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx lm pni monitor ds_cpl tm2 xtpr bogomips : 3990.01 processor : 3 vendor_id : GenuineIntel cpu family : 6 model : 7 model name : Intel(R) Xeon(R) CPU E5405 @ 2.00GHz stepping : 6 cpu MHz : 1995.138 cache size : 6144 KB physical id : 0 siblings : 4 core id : 3 cpu cores : 4 fdiv_bug : no hlt_bug : no f00f_bug : no coma_bug : no fpu : yes fpu_exception : yes cpuid level : 10 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx lm pni monitor ds_cpl tm2 xtpr bogomips : 3990.11 processor : 4 vendor_id : GenuineIntel cpu family : 6 model : 7 model name : Intel(R) Xeon(R) CPU E5405 @ 2.00GHz stepping : 6 cpu MHz : 1995.138 cache size : 6144 KB physical id : 1 siblings : 4 core id : 4 cpu cores : 4 fdiv_bug : no hlt_bug : no f00f_bug : no coma_bug : no fpu : yes fpu_exception : yes cpuid level : 10 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx lm pni monitor ds_cpl tm2 xtpr bogomips : 3990.09 processor : 5 vendor_id : GenuineIntel cpu family : 6 model : 7 model name : Intel(R) Xeon(R) CPU E5405 @ 2.00GHz stepping : 6 cpu MHz : 1995.138 cache size : 6144 KB physical id : 1 siblings : 4 core id : 5 cpu cores : 4 fdiv_bug : no hlt_bug : no f00f_bug : no coma_bug : no fpu : yes fpu_exception : yes cpuid level : 10 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx lm pni monitor ds_cpl tm2 xtpr bogomips : 3990.05 processor : 6 vendor_id : GenuineIntel cpu family : 6 model : 7 model name : Intel(R) Xeon(R) CPU E5405 @ 2.00GHz stepping : 6 cpu MHz : 1995.138 cache size : 6144 KB physical id : 1 siblings : 4 core id : 6 cpu cores : 4 fdiv_bug : no hlt_bug : no f00f_bug : no coma_bug : no fpu : yes fpu_exception : yes cpuid level : 10 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx lm pni monitor ds_cpl tm2 xtpr bogomips : 3990.07 processor : 7 vendor_id : GenuineIntel cpu family : 6 model : 7 model name : Intel(R) Xeon(R) CPU E5405 @ 2.00GHz stepping : 6 cpu MHz : 1995.138 cache size : 6144 KB physical id : 1 siblings : 4 core id : 7 cpu cores : 4 fdiv_bug : no hlt_bug : no f00f_bug : no coma_bug : no fpu : yes fpu_exception : yes cpuid level : 10 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx lm pni monitor ds_cpl tm2 xtpr bogomips : 3990.02 Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/resources/dual.xeon.cpuinfo000066400000000000000000000044101322611020300300260ustar00rootroot00000000000000processor : 0 vendor_id : GenuineIntel cpu family : 15 model : 4 model name : Intel(R) Xeon(TM) MP CPU 3.66GHz stepping : 1 cpu MHz : 3670.025 cache size : 1024 KB physical id : 0 siblings : 2 core id : 0 cpu cores : 1 fpu : yes fpu_exception : yes cpuid level : 5 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall lm pni monitor ds_cpl est tm2 cid cx16 xtpr bogomips : 7208.96 clflush size : 64 cache_alignment : 128 address sizes : 40 bits physical, 48 bits virtual power management: processor : 1 vendor_id : GenuineIntel cpu family : 15 model : 4 model name : Intel(R) Xeon(TM) MP CPU 3.66GHz stepping : 1 cpu MHz : 3670.025 cache size : 1024 KB physical id : 0 siblings : 2 core id : 0 cpu cores : 1 fpu : yes fpu_exception : yes cpuid level : 5 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall lm pni monitor ds_cpl est tm2 cid cx16 xtpr bogomips : 7323.64 clflush size : 64 cache_alignment : 128 address sizes : 40 bits physical, 48 bits virtual power management: processor : 2 vendor_id : GenuineIntel cpu family : 15 model : 4 model name : Intel(R) Xeon(TM) MP CPU 3.66GHz stepping : 1 cpu MHz : 3670.025 cache size : 1024 KB physical id : 3 siblings : 2 core id : 3 cpu cores : 1 fpu : yes fpu_exception : yes cpuid level : 5 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall lm pni monitor ds_cpl est tm2 cid cx16 xtpr bogomips : 7323.64 clflush size : 64 cache_alignment : 128 address sizes : 40 bits physical, 48 bits virtual power management: processor : 3 vendor_id : GenuineIntel cpu family : 15 model : 4 model name : Intel(R) Xeon(TM) MP CPU 3.66GHz stepping : 1 cpu MHz : 3670.025 cache size : 1024 KB physical id : 3 siblings : 2 core id : 3 cpu cores : 1 fpu : yes fpu_exception : yes cpuid level : 5 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall lm pni monitor ds_cpl est tm2 cid cx16 xtpr bogomips : 7323.64 clflush size : 64 cache_alignment : 128 address sizes : 40 bits physical, 48 bits virtual power management: Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/resources/i3.cpuinfo000066400000000000000000000064041322611020300264510ustar00rootroot00000000000000processor : 0 vendor_id : GenuineIntel cpu family : 6 model : 37 model name : Intel(R) Core(TM) i3 CPU 530 @ 2.93GHz stepping : 2 cpu MHz : 1200.000 cache size : 4096 KB physical id : 0 siblings : 4 core id : 0 cpu cores : 2 apicid : 0 initial apicid : 0 fdiv_bug : no hlt_bug : no f00f_bug : no coma_bug : no fpu : yes fpu_exception : yes cpuid level : 11 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx rdtscp lm constant_tsc arch_perfmon pebs bts xtopology nonstop_tsc aperfmperf pni dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm sse4_1 sse4_2 popcnt lahf_lm arat tpr_shadow vnmi flexpriority ept vpid bogomips : 5866.15 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: processor : 1 vendor_id : GenuineIntel cpu family : 6 model : 37 model name : Intel(R) Core(TM) i3 CPU 530 @ 2.93GHz stepping : 2 cpu MHz : 1200.000 cache size : 4096 KB physical id : 0 siblings : 4 core id : 2 cpu cores : 2 apicid : 4 initial apicid : 4 fdiv_bug : no hlt_bug : no f00f_bug : no coma_bug : no fpu : yes fpu_exception : yes cpuid level : 11 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx rdtscp lm constant_tsc arch_perfmon pebs bts xtopology nonstop_tsc aperfmperf pni dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm sse4_1 sse4_2 popcnt lahf_lm arat tpr_shadow vnmi flexpriority ept vpid bogomips : 5866.64 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: processor : 2 vendor_id : GenuineIntel cpu family : 6 model : 37 model name : Intel(R) Core(TM) i3 CPU 530 @ 2.93GHz stepping : 2 cpu MHz : 1200.000 cache size : 4096 KB physical id : 0 siblings : 4 core id : 0 cpu cores : 2 apicid : 1 initial apicid : 1 fdiv_bug : no hlt_bug : no f00f_bug : no coma_bug : no fpu : yes fpu_exception : yes cpuid level : 11 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx rdtscp lm constant_tsc arch_perfmon pebs bts xtopology nonstop_tsc aperfmperf pni dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm sse4_1 sse4_2 popcnt lahf_lm arat tpr_shadow vnmi flexpriority ept vpid bogomips : 5866.62 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: processor : 3 vendor_id : GenuineIntel cpu family : 6 model : 37 model name : Intel(R) Core(TM) i3 CPU 530 @ 2.93GHz stepping : 2 cpu MHz : 1200.000 cache size : 4096 KB physical id : 0 siblings : 4 core id : 2 cpu cores : 2 apicid : 5 initial apicid : 5 fdiv_bug : no hlt_bug : no f00f_bug : no coma_bug : no fpu : yes fpu_exception : yes cpuid level : 11 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx rdtscp lm constant_tsc arch_perfmon pebs bts xtopology nonstop_tsc aperfmperf pni dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm sse4_1 sse4_2 popcnt lahf_lm arat tpr_shadow vnmi flexpriority ept vpid bogomips : 5866.65 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/resources/i7.cpuinfo000066400000000000000000000126601322611020300264560ustar00rootroot00000000000000processor : 0 vendor_id : GenuineIntel cpu family : 6 model : 42 model name : Intel(R) Core(TM) i7-2600K CPU @ 3.40GHz stepping : 7 cpu MHz : 3400.235 cache size : 8192 KB physical id : 0 siblings : 8 core id : 0 cpu cores : 4 apicid : 0 fpu : yes fpu_exception : yes cpuid level : 13 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall nx rdtscp lm constant_tsc ida nonstop_tsc arat pni monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr sse4_1 sse4_2 popcnt lahf_lm bogomips : 6800.47 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: [8] processor : 1 vendor_id : GenuineIntel cpu family : 6 model : 42 model name : Intel(R) Core(TM) i7-2600K CPU @ 3.40GHz stepping : 7 cpu MHz : 3400.235 cache size : 8192 KB physical id : 0 siblings : 8 core id : 1 cpu cores : 4 apicid : 2 fpu : yes fpu_exception : yes cpuid level : 13 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall nx rdtscp lm constant_tsc ida nonstop_tsc arat pni monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr sse4_1 sse4_2 popcnt lahf_lm bogomips : 6800.26 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: [8] processor : 2 vendor_id : GenuineIntel cpu family : 6 model : 42 model name : Intel(R) Core(TM) i7-2600K CPU @ 3.40GHz stepping : 7 cpu MHz : 3400.235 cache size : 8192 KB physical id : 0 siblings : 8 core id : 2 cpu cores : 4 apicid : 4 fpu : yes fpu_exception : yes cpuid level : 13 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall nx rdtscp lm constant_tsc ida nonstop_tsc arat pni monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr sse4_1 sse4_2 popcnt lahf_lm bogomips : 6800.07 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: [8] processor : 3 vendor_id : GenuineIntel cpu family : 6 model : 42 model name : Intel(R) Core(TM) i7-2600K CPU @ 3.40GHz stepping : 7 cpu MHz : 3400.235 cache size : 8192 KB physical id : 0 siblings : 8 core id : 3 cpu cores : 4 apicid : 6 fpu : yes fpu_exception : yes cpuid level : 13 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall nx rdtscp lm constant_tsc ida nonstop_tsc arat pni monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr sse4_1 sse4_2 popcnt lahf_lm bogomips : 6800.11 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: [8] processor : 4 vendor_id : GenuineIntel cpu family : 6 model : 42 model name : Intel(R) Core(TM) i7-2600K CPU @ 3.40GHz stepping : 7 cpu MHz : 3400.235 cache size : 8192 KB physical id : 0 siblings : 8 core id : 0 cpu cores : 4 apicid : 1 fpu : yes fpu_exception : yes cpuid level : 13 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall nx rdtscp lm constant_tsc ida nonstop_tsc arat pni monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr sse4_1 sse4_2 popcnt lahf_lm bogomips : 6799.97 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: [8] processor : 5 vendor_id : GenuineIntel cpu family : 6 model : 42 model name : Intel(R) Core(TM) i7-2600K CPU @ 3.40GHz stepping : 7 cpu MHz : 3400.235 cache size : 8192 KB physical id : 0 siblings : 8 core id : 1 cpu cores : 4 apicid : 3 fpu : yes fpu_exception : yes cpuid level : 13 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall nx rdtscp lm constant_tsc ida nonstop_tsc arat pni monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr sse4_1 sse4_2 popcnt lahf_lm bogomips : 6800.06 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: [8] processor : 6 vendor_id : GenuineIntel cpu family : 6 model : 42 model name : Intel(R) Core(TM) i7-2600K CPU @ 3.40GHz stepping : 7 cpu MHz : 3400.235 cache size : 8192 KB physical id : 0 siblings : 8 core id : 2 cpu cores : 4 apicid : 5 fpu : yes fpu_exception : yes cpuid level : 13 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall nx rdtscp lm constant_tsc ida nonstop_tsc arat pni monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr sse4_1 sse4_2 popcnt lahf_lm bogomips : 6800.03 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: [8] processor : 7 vendor_id : GenuineIntel cpu family : 6 model : 42 model name : Intel(R) Core(TM) i7-2600K CPU @ 3.40GHz stepping : 7 cpu MHz : 3400.235 cache size : 8192 KB physical id : 0 siblings : 8 core id : 3 cpu cores : 4 apicid : 7 fpu : yes fpu_exception : yes cpuid level : 13 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall nx rdtscp lm constant_tsc ida nonstop_tsc arat pni monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr sse4_1 sse4_2 popcnt lahf_lm bogomips : 6799.88 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: [8] Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/resources/i7.properties000066400000000000000000000012311322611020300271770ustar00rootroot00000000000000# # Copyright 2016 higherfrequencytrading.com # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # 0=0,0,0 1=0,1,0 2=0,2,0 3=0,3,0 4=0,0,1 5=0,1,1 6=0,2,1 7=0,3,1 Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/resources/q6600.noht.cpuinfo000066400000000000000000000055101322611020300276560ustar00rootroot00000000000000processor : 0 vendor_id : GenuineIntel cpu family : 6 model : 15 model name : Intel(R) Core(TM)2 Quad CPU Q6600 @ 2.40GHz stepping : 11 cpu MHz : 1596.000 cache size : 4096 KB physical id : 0 siblings : 4 core id : 0 cpu cores : 4 apicid : 0 initial apicid : 0 fpu : yes fpu_exception : yes cpuid level : 10 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx lm constant_tsc arch_perfmon pebs bts rep_good pni dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm lahf_lm tpr_shadow vnmi flexpriority bogomips : 4810.72 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: processor : 1 vendor_id : GenuineIntel cpu family : 6 model : 15 model name : Intel(R) Core(TM)2 Quad CPU Q6600 @ 2.40GHz stepping : 11 cpu MHz : 1596.000 cache size : 4096 KB physical id : 0 siblings : 4 core id : 2 cpu cores : 4 apicid : 2 initial apicid : 2 fpu : yes fpu_exception : yes cpuid level : 10 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx lm constant_tsc arch_perfmon pebs bts rep_good pni dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm lahf_lm tpr_shadow vnmi flexpriority bogomips : 4810.82 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: processor : 2 vendor_id : GenuineIntel cpu family : 6 model : 15 model name : Intel(R) Core(TM)2 Quad CPU Q6600 @ 2.40GHz stepping : 11 cpu MHz : 1596.000 cache size : 4096 KB physical id : 0 siblings : 4 core id : 1 cpu cores : 4 apicid : 1 initial apicid : 1 fpu : yes fpu_exception : yes cpuid level : 10 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx lm constant_tsc arch_perfmon pebs bts rep_good pni dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm lahf_lm tpr_shadow vnmi flexpriority bogomips : 4810.81 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: processor : 3 vendor_id : GenuineIntel cpu family : 6 model : 15 model name : Intel(R) Core(TM)2 Quad CPU Q6600 @ 2.40GHz stepping : 11 cpu MHz : 1596.000 cache size : 4096 KB physical id : 0 siblings : 4 core id : 3 cpu cores : 4 apicid : 3 initial apicid : 3 fpu : yes fpu_exception : yes cpuid level : 10 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx lm constant_tsc arch_perfmon pebs bts rep_good pni dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm lahf_lm tpr_shadow vnmi flexpriority bogomips : 4810.82 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: Java-Thread-Affinity-affinity-3.1.7/affinity/src/test/resources/q6600.vm.cpuinfo000066400000000000000000000047651322611020300273430ustar00rootroot00000000000000processor : 0 vendor_id : GenuineIntel cpu family : 6 model : 15 model name : Intel(R) Core(TM)2 Quad CPU Q6600 @ 2.40GHz stepping : 11 cpu MHz : 1596.000 cache size : 4096 KB fpu : yes fpu_exception : yes cpuid level : 10 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx lm constant_tsc arch_perfmon pebs bts rep_good pni dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm lahf_lm tpr_shadow vnmi flexpriority bogomips : 4810.72 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: processor : 1 vendor_id : GenuineIntel cpu family : 6 model : 15 model name : Intel(R) Core(TM)2 Quad CPU Q6600 @ 2.40GHz stepping : 11 cpu MHz : 1596.000 cache size : 4096 KB fpu : yes fpu_exception : yes cpuid level : 10 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx lm constant_tsc arch_perfmon pebs bts rep_good pni dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm lahf_lm tpr_shadow vnmi flexpriority bogomips : 4810.82 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: processor : 2 vendor_id : GenuineIntel cpu family : 6 model : 15 model name : Intel(R) Core(TM)2 Quad CPU Q6600 @ 2.40GHz stepping : 11 cpu MHz : 1596.000 cache size : 4096 KB fpu : yes fpu_exception : yes cpuid level : 10 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx lm constant_tsc arch_perfmon pebs bts rep_good pni dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm lahf_lm tpr_shadow vnmi flexpriority bogomips : 4810.81 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: processor : 3 vendor_id : GenuineIntel cpu family : 6 model : 15 model name : Intel(R) Core(TM)2 Quad CPU Q6600 @ 2.40GHz stepping : 11 cpu MHz : 1596.000 cache size : 4096 KB fpu : yes fpu_exception : yes cpuid level : 10 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx lm constant_tsc arch_perfmon pebs bts rep_good pni dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm lahf_lm tpr_shadow vnmi flexpriority bogomips : 4810.82 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: Java-Thread-Affinity-affinity-3.1.7/pom.xml000077500000000000000000000026551322611020300205040ustar00rootroot00000000000000 net.openhft root-parent-pom 1.1.9 4.0.0 Java-Thread-Affinity 3.1.1-SNAPSHOT pom OpenHFT/Java-Thread-Affinity Parent Java Thread Affinity library affinity affinity-test