Simple Java program 100 times slower after plugging in USB hotspot - java

I have following Java program:
class Main {
public static void main(String[] args) throws java.io.IOException {
long start = System.nanoTime();
java.io.File.createTempFile("java_test", ".txt").delete();
System.out.println((System.nanoTime() - start ) / 1e9);
}
}
Normally, it takes bout 63 miliseconds to execute:
$ java Main
0.06308555
But, once I connect Android phone as USB hotspot, it takes significantly longer. Depending on the machine anywhere from 3 to 40 seconds:
$ java Main
4.263285528
The strange thing is that nothing here is actually transferred over the network - plugged network adapters shouldn't matter.
I did a backtrace and it looks like majority of time is spent in NetworkInterface.getAll method:
"main" #1 prio=5 os_prio=0 tid=0x00000000023ae000 nid=0x142c runnable [0x000000000268d000]
java.lang.Thread.State: RUNNABLE
at java.net.NetworkInterface.getAll(Native Method)
at java.net.NetworkInterface.getNetworkInterfaces(Unknown Source)
at sun.security.provider.SeedGenerator.addNetworkAdapterInfo(Unknown Source)
at sun.security.provider.SeedGenerator.access$000(Unknown Source)
at sun.security.provider.SeedGenerator$1.run(Unknown Source)
at sun.security.provider.SeedGenerator$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.security.provider.SeedGenerator.getSystemEntropy(Unknown Source)
at sun.security.provider.SecureRandom$SeederHolder.<clinit>(Unknown Source)
at sun.security.provider.SecureRandom.engineNextBytes(Unknown Source)
- locked <0x000000076afa2820> (a sun.security.provider.SecureRandom)
at java.security.SecureRandom.nextBytes(Unknown Source)
- locked <0x000000076af6bdc8> (a java.security.SecureRandom)
at java.security.SecureRandom.next(Unknown Source)
at java.util.Random.nextLong(Unknown Source)
at java.io.File$TempDirectory.generateFile(Unknown Source)
at java.io.File.createTempFile(Unknown Source)
at java.io.File.createTempFile(Unknown Source)
at Main.main(Main.java:4)
which, in turn, seems to spend most of the time in GetIfTable Windows API method:
Child-SP RetAddr Call Site
00000000`0257ed78 000007fe`fd7210ba ntdll!NtDeviceIoControlFile+0xa
00000000`0257ed80 000007fe`fd721252 nsi+0x10ba
00000000`0257ee20 000007fe`fd7211f9 nsi!NsiEnumerateObjectsAllParametersEx+0x2e
00000000`0257ee60 000007fe`fd7217b0 nsi!NsiEnumerateObjectsAllParameters+0xc9
00000000`0257ef00 000007fe`f9c7928d nsi!NsiAllocateAndGetTable+0x184
00000000`0257efd0 00000000`6f8c5a01 IPHLPAPI!GetIfTable+0xa9
00000000`0257f090 00000000`6f8c6980 net!Java_java_net_NetworkInterface_getMTU0+0x1a1
00000000`0257f150 00000000`6f8c6e57 net!Java_java_net_NetworkInterface_isP2P0_XP+0x88
00000000`0257f270 00000000`6f8c6058 net!Java_java_net_NetworkInterface_getAll_XP+0x23
00000000`0257f2a0 00000000`02867f54 net!Java_java_net_NetworkInterface_getAll+0x2c
GetIfTable seems to be the problematic function. I'm observing the same slowdown both in example program from: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365943(v=vs.85).aspx and with following snippet:
#include <iphlpapi.h>
#include <stdlib.h>
int main() {
DWORD dwSize = sizeof(MIB_IFTABLE);
MIB_IFTABLE *pIfTable = malloc(dwSize);
GetIfTable(pIfTable, &dwSize, FALSE);
pIfTable = malloc(dwSize);
GetIfTable(pIfTable, &dwSize, FALSE);
return 0;
}
How do I fix or workaround this problem?
I can create temporary files on my own and avoid calling NetworkInterface.getNetworkInterfaces but SecureRandom is used all over Java standard library.
Is there a way to force SecureRandom not to use GetIfTable?
Java version:
> java -version
java version "1.8.0_101"
Java(TM) SE Runtime Environment (build 1.8.0_101-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.101-b13, mixed mode)
Windows version:
OS Name: Microsoft Windows 7 Professional
OS Version: 6.1.7601 Service Pack 1 Build 7601
Problematic network adapter:
Name [00000020] Remote NDIS based Internet Sharing Device
Adapter Type Ethernet 802.3
Product Type Remote NDIS based Internet Sharing Device
Installed Yes
PNP Device ID USB\VID_0FCE&PID_71C4&MI_00\7&6BE3F3B&0&0000
Last Reset 8/14/2016 12:26 PM
Index 20
Service Name usb_rndisx
IP Address 192.168.42.183, fe80::90ab:3786:4396:2870
IP Subnet 255.255.255.0, 64
Default IP Gateway 192.168.42.129
DHCP Enabled Yes
DHCP Server 192.168.42.129
DHCP Lease Expires 8/14/2016 3:27 PM
DHCP Lease Obtained 8/14/2016 2:27 PM
MAC Address 02:18:61:77:7D:72
Driver c:\windows\system32\drivers\usb8023x.sys (6.1.7600.16385, 19.50 KB (19,968 bytes), 7/14/2009 2:09 AM)

Default implementation of SecureRandom scans network interfaces as an additional source of system entropy. In order to avoid this, you need to register a custom java.security.Provider that contains a different implementation of SecureRandomSpi.
Fortunately, JDK for Windows already has a suitable SecureRandomSpi implementation that relies on Microsoft Crypto API: sun.security.mscapi.PRNG. Though this is non-public API, the class exists in all versions of OpenJDK and Oracle JDK from 1.6 to 9, and the fallback is available anyway.
There are two ways to register MS Crypto PRNG as the default SecureRandom algorithm.
1. From within the application by calling WindowsSecureRandom.register() at the very beginning.
import java.security.Provider;
import java.security.Security;
public class WindowsSecureRandom extends Provider {
private static final String MSCAPI = "sun.security.mscapi.PRNG";
private WindowsSecureRandom() {
super("WindowsSecureRandom Provider", 1.0, null);
putService(new Service(this, "SecureRandom", "Windows-PRNG", MSCAPI, null, null));
}
public static void register() {
if (System.getProperty("os.name").contains("Windows")) {
try {
Class.forName(MSCAPI);
Security.insertProviderAt(new WindowsSecureRandom(), 1);
} catch (ClassNotFoundException e) {
// Fallback to default implementation
}
}
}
}
2. By reordering provider list in %JAVA_HOME%\jre\lib\security\java.security file.
security.provider.1=sun.security.mscapi.SunMSCAPI <<<--- make it the first provider
security.provider.2=sun.security.provider.Sun
security.provider.3=sun.security.rsa.SunRsaSign
security.provider.4=sun.security.ec.SunEC
security.provider.5=com.sun.net.ssl.internal.ssl.Provider
...
I've verified that with either solutions SeedGenerator and NetworkInterface classes are no longer loaded.

Related

Network unreachable when using Google Maps Geocode API in Google Dataflow

I'm using the Google Maps Geocode API (https://github.com/googlemaps/google-maps-services-java) in a Dataflow job. My DoFn prepares the GeoApiContext at Setup. The process element function is done like so:
public void processElement(ProcessContext c) {
String address = c.element().get("Address").toString();
String id = c.element().get("Id").toString();
Gson gson = new GsonBuilder().create();
try {
GeocodingResult[] results = GeocodingApi.newRequest(this.geocodeContext).address(address).language("pt-BR").components(ComponentFilter.country("BR")).await();
if(results.length == 0) {
TableRow outputRow = new TableRow();
outputRow.set("Id", id);
c.output(outputRow);
} else {
for(GeocodingResult r : results) {
TableRow outputRow = convertTableRow(gson.toJson(r).toString());
outputRow.set("Id", id);
c.output(outputRow);
}
}
} catch(ApiException e) {
LOGGER.error("ApiException on address: {}", address, e);
} catch(InterruptedException e) {
LOGGER.error("InterruptedException on address: {}", address, e);
} catch(IOException e) {
LOGGER.error("IOException on address: {}", address, e);
}
}
This code worked fine locally, but when deployed to dataflow it throws a network error:
exception: "java.net.ConnectException: Failed to connect to maps.googleapis.com/2607:f8b0:4001:c05:0:0:0:5f:443
at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:265)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:183)
at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.java:224)
at okhttp3.internal.connection.ExchangeFinder.findHealthyConnection(ExchangeFinder.java:108)
at okhttp3.internal.connection.ExchangeFinder.find(ExchangeFinder.java:88)
at okhttp3.internal.connection.Transmitter.newExchange(Transmitter.java:169)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:41)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:94)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:88)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:229)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:172)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.net.ConnectException: Network is unreachable (connect failed)
at java.base/java.net.PlainSocketImpl.socketConnect(Native Method)
at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399)
at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:242)
at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224)
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:403)
at java.base/java.net.Socket.connect(Socket.java:591)
at okhttp3.internal.platform.Platform.connectSocket(Platform.java:130)
at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:263)
... 22 more
I've ensured that the VM spawned has internet access and I can even ping the maps.googleapis.com endpoint from inside the container:
USER#test-geocode-07020834-qmrj-harness-3k2l ~ $ docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b2fd123138aa 3a1cb7aedd54 "/opt/google/dataflo…" 6 minutes ago Up 5 minutes k8s_healthchecker_dataflow-test-geocode-07020834-qmrj-harness-3k2l_default_5648e9815f2ca5beea8b0eb945e12d1f_0
086e36c3dd23 4127911f4769 "/opt/google/dataflo…" 6 minutes ago Up 5 minutes k8s_vmmonitor_dataflow-test-geocode-07020834-qmrj-harness-3k2l_default_5648e9815f2ca5beea8b0eb945e12d1f_0
2890fa415af5 664bd8972b23 "/opt/google/dataflo…" 6 minutes ago Up 6 minutes k8s_shuffle_dataflow-test-geocode-07020834-qmrj-harness-3k2l_default_5648e9815f2ca5beea8b0eb945e12d1f_0
eea757bf6be7 gcr.io/cloud-dataflow/v1beta3/beam-java11-batch "/opt/google/dataflo…" 6 minutes ago Up 6 minutes k8s_java-batch_dataflow-test-geocode-07020834-qmrj-harness-3k2l_default_5648e9815f2ca5beea8b0eb945e12d1f_0
b636784118f5 k8s.gcr.io/pause:3.1 "/pause" 6 minutes ago Up 6 minutes k8s_POD_dataflow-test-geocode-07020834-qmrj-harness-3k2l_default_5648e9815f2ca5beea8b0eb945e12d1f_0
lucas#test-geocode-07020834-qmrj-harness-3k2l ~ $ docker exec -it eea /bin/sh
# ping maps.googleapis.com
PING maps.googleapis.com (172.217.214.95) 56(84) bytes of data.
64 bytes from 172.217.214.95: icmp_seq=1 ttl=115 time=1.08 ms
64 bytes from 172.217.214.95: icmp_seq=2 ttl=115 time=1.28 ms
64 bytes from 172.217.214.95: icmp_seq=3 ttl=115 time=1.15 ms
64 bytes from 172.217.214.95: icmp_seq=4 ttl=115 time=1.41 ms
^C
--- maps.googleapis.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3004ms
rtt min/avg/max/mdev = 1.089/1.235/1.414/0.131 ms
#
Regarding versions, I'm using the latest beam version (2.22.0) and the latest google maps version (0.14.0).
No idea what else to look at, and any help is appreciated.
UPDATE
The problem seems to be the fact that the request is done with an ipv6 address. However, GCE machines seems to have no support for ipv6 and the call simply fails without falling back to ipv4.
Considering that, there doesn't seem to be any way out of this problem:
Configuring the JVM to prefer ipv4 address can't be done with Dataflow (JVM flags are ignored)
There's also no way to customize the GCE machine (since a base Dataflow image is used)
The library doesn't seem to open any options to configure ipv4 or ipv6
Thanks
I had this exact same issue come up after upgrading from 2.17 to 2.24 and changing from Java 8 to Java 11. After trying to fix this on 2.24 and Java 11 I gave up and went back to 8 and it's working now.
I couldn't find it documented anywhere but it looks like the userAgent used is based on that -
When I build the self executable with Java 8, Dataflow shows the userAgent as
Apache_Beam_SDK_for_Java/2.24.0(JRE_8_environment)
and with Java 11 it shows Apache_Beam_SDK_for_Java/2.24.0(JDK_11_environment)

Minecraft coding error with fabric: Exception while loading entries for entrypoint 'main' provided by 'myfirstmod'

package net.my.first.mod;
import net.fabricmc.api.ModInitializer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemGroup;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
import net.minecraft.block.Block;
public class MyFirstMod implements ModInitializer {
public static final Item FABRIC_ITEM = new FabricItem(new Item.Settings().group(ItemGroup.MISC), null);
public static final Block FABRIC_BLOCK = new FabricBlock();
#Override
public void onInitialize() {
Registry.register(Registry.ITEM, new Identifier("myfirstmod", "fabric_item"), FABRIC_ITEM);
Registry.register(Registry.BLOCK, new Identifier("myfirstmod", "fabric_block"), FABRIC_BLOCK);
}
}
package net.my.first.mod;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.TypedActionResult;
import net.minecraft.world.World;
public class FabricItem extends Item {
public FabricItem(Settings settings, Settings item$Settings_1) {
super(item$Settings_1);
}
#Override
public TypedActionResult<ItemStack> use(World world, PlayerEntity playerEntity, Hand hand) {
return new TypedActionResult<ItemStack>(ActionResult.SUCCESS, playerEntity.getStackInHand(hand));
}
}
I keep running into a crash whenever I try to run my code. I am using visual studio code and I don't understand why this is happening I have even tried re-coding the whole thing. Here's the error I get:
---- Minecraft Crash Report ----
// You should try our sister game, Minceraft!
Time: 27/04/20 18:57
Description: Initializing game
net.fabricmc.loader.api.EntrypointException: Exception while loading entries for entrypoint 'main' provided by 'myfirstmod'
at net.fabricmc.loader.EntrypointStorage.getEntrypointContainers(EntrypointStorage.java:193)
at net.fabricmc.loader.FabricLoader.getEntrypointContainers(FabricLoader.java:228)
at net.fabricmc.loader.entrypoint.minecraft.hooks.EntrypointUtils.invoke0(EntrypointUtils.java:44)
at net.fabricmc.loader.entrypoint.minecraft.hooks.EntrypointUtils.invoke(EntrypointUtils.java:36)
at net.fabricmc.loader.entrypoint.minecraft.hooks.EntrypointClient.start(EntrypointClient.java:32)
at net.minecraft.client.MinecraftClient.<init>(MinecraftClient.java:362)
at net.minecraft.client.main.Main.main(Main.java:140)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at net.fabricmc.loader.game.MinecraftGameProvider.launch(MinecraftGameProvider.java:192)
at net.fabricmc.loader.launch.knot.Knot.init(Knot.java:140)
at net.fabricmc.loader.launch.knot.KnotClient.main(KnotClient.java:26)
at net.fabricmc.devlaunchinjector.Main.main(Main.java:86)
Caused by: java.lang.ExceptionInInitializerError
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at net.fabricmc.loader.util.DefaultLanguageAdapter.create(DefaultLanguageAdapter.java:45)
at net.fabricmc.loader.EntrypointStorage$NewEntry.create(EntrypointStorage.java:114)
at net.fabricmc.loader.EntrypointStorage$NewEntry.getOrCreate(EntrypointStorage.java:101)
at net.fabricmc.loader.EntrypointStorage.getEntrypointContainers(EntrypointStorage.java:186)
... 14 more
Caused by: java.lang.NullPointerException
at net.minecraft.item.Item$Settings.method_7897(Item.java:369)
at net.minecraft.item.Item.<init>(Item.java:92)
at net.my.first.mod.FabricItem.<init>(FabricItem.java:14)
at net.my.first.mod.MyFirstMod.<clinit>(MyFirstMod.java:12)
... 20 more
A detailed walkthrough of the error, its code path and all known details is as follows:
---------------------------------------------------------------------------------------
-- Head --
Thread: Render thread
Stacktrace:
at net.fabricmc.loader.EntrypointStorage.getEntrypointContainers(EntrypointStorage.java:193)
at net.fabricmc.loader.FabricLoader.getEntrypointContainers(FabricLoader.java:228)
at net.fabricmc.loader.entrypoint.minecraft.hooks.EntrypointUtils.invoke0(EntrypointUtils.java:44)
at net.fabricmc.loader.entrypoint.minecraft.hooks.EntrypointUtils.invoke(EntrypointUtils.java:36)
at net.fabricmc.loader.entrypoint.minecraft.hooks.EntrypointClient.start(EntrypointClient.java:32)
at net.minecraft.client.MinecraftClient.<init>(MinecraftClient.java:362)
-- Initialization --
Details:
Stacktrace:
at net.minecraft.client.main.Main.main(Main.java:140)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at net.fabricmc.loader.game.MinecraftGameProvider.launch(MinecraftGameProvider.java:192)
at net.fabricmc.loader.launch.knot.Knot.init(Knot.java:140)
at net.fabricmc.loader.launch.knot.KnotClient.main(KnotClient.java:26)
at net.fabricmc.devlaunchinjector.Main.main(Main.java:86)
-- System Details --
Details:
Minecraft Version: 1.15.2
Minecraft Version ID: 1.15.2
Operating System: Windows 10 (amd64) version 10.0
Java Version: 1.8.0_251, Oracle Corporation
Java VM Version: Java HotSpot(TM) 64-Bit Server VM (mixed mode), Oracle Corporation
Memory: 354621680 bytes (338 MB) / 570425344 bytes (544 MB) up to 1895825408 bytes (1808 MB)
CPUs: 2
JVM Flags: 3 total; -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=localhost:65427,server=n,suspend=y
Fabric Mods:
fabric: Fabric API 0.5.1+build.294-1.15
fabric-api-base: Fabric API Base 0.1.2+b7f9825d0c
fabric-biomes-v1: Fabric Biomes (v1) 0.1.5+3b05f68e0c
fabric-blockrenderlayer-v1: Fabric BlockRenderLayer Registration (v1) 1.1.4+c6a8ea890c
fabric-commands-v0: Fabric Commands (v0) 0.1.2+b7f9825d0c
fabric-containers-v0: Fabric Containers (v0) 0.1.3+b7f9825d0c
fabric-content-registries-v0: Fabric Content Registries (v0) 0.1.3+b7f9825d0c
fabric-crash-report-info-v1: Fabric Crash Report Info (v1) 0.1.2+b7f9825d0c
fabric-dimensions-v1: fabric-dimensions-v1 0.3.0+2ad156310c
fabric-events-interaction-v0: Fabric Events Interaction (v0) 0.3.0+fac69e320c
fabric-events-lifecycle-v0: Fabric Events Lifecycle (v0) 0.1.2+b7f9825d0c
fabric-item-groups-v0: Fabric Item Groups (v0) 0.1.6+ec40b2e10c
fabric-keybindings-v0: Fabric Key Bindings (v0) 0.1.1+dfdb52d60c
fabric-loot-tables-v1: Fabric Loot Tables (v1) 0.1.5+e08a73050c
fabric-mining-levels-v0: Fabric Mining Levels (v0) 0.1.1+b7f9825d0c
fabric-models-v0: Fabric Models (v0) 0.1.0+dfdb52d60c
fabric-networking-blockentity-v0: Fabric Networking Block Entity (v0) 0.2.3+e08a73050c
fabric-networking-v0: Fabric Networking (v0) 0.1.7+12515ed90c
fabric-object-builders-v0: Fabric Object Builders (v0) 0.1.3+e4c9a9c30c
fabric-particles-v1: fabric-particles-v1 0.1.1+dfdb52d60c
fabric-registry-sync-v0: Fabric Registry Sync (v0) 0.2.6+f3d8141b0c
fabric-renderer-api-v1: Fabric Renderer API (v1) 0.2.10+f08b61330c
fabric-renderer-indigo: Fabric Renderer - Indigo 0.2.23+9290e2ed0c
fabric-renderer-registries-v1: Fabric Renderer Registries (v1) 2.0.1+5a0f9a600c
fabric-rendering-data-attachment-v1: Fabric Rendering Data Attachment (v1) 0.1.3+b7f9825d0c
fabric-rendering-fluids-v1: Fabric Rendering Fluids (v1) 0.1.6+12515ed90c
fabric-rendering-v0: Fabric Rendering (v0) 1.1.0+534104900c
fabric-rendering-v1: Fabric Rendering (v1) 0.1.0+534104900c
fabric-resource-loader-v0: Fabric Resource Loader (v0) 0.1.10+06c939b30c
fabric-tag-extensions-v0: Fabric Tag Extensions (v0) 0.1.3+abd915800c
fabric-textures-v0: Fabric Textures (v0) 1.0.4+821cdba70c
fabricloader: Fabric Loader 0.8.2+build.194
minecraft: Minecraft 1.15.2
myfirstmod: My First Mod ${version}
Launched Version: Fabric
Backend library: LWJGL version 3.2.2 build 10
Backend API: NO CONTEXT
GL Caps:
Using VBOs: Yes
Is Modded: Definitely; Client brand changed to 'fabric'
Type: Client (map_client.txt)
CPU: <unknown>
You're throwing away the real Settings you have and passing null instead! Change this:
public FabricItem(Settings settings, Settings item$Settings_1) {
super(item$Settings_1);
}
To this:
public FabricItem(Settings settings, Settings item$Settings_1) {
super(settings);
}
You can also get rid of the second parameter both from that definition and from where you call it in MyFirstMod, now that you're not using it for anything.

JRocket : Thread Stuck at jrockit/vm/Locks.park0

Seeing very strange behaviour. My code is executing well but not sure what happen, method is calling to other method but other method doesnt get called ( i cant see logs which is there in the first line of other method )
"jaxws-engine-1-thread-2" id=447 idx=0x73c tid=4031 prio=5 alive, parked, native_blocked, daemon
at jrockit/vm/Locks.park0(J)V(Native Method)
at jrockit/vm/Locks.park(Locks.java:2230)
at sun/misc/Unsafe.park(ZJ)V(Native Method)
at java/util/concurrent/locks/LockSupport.parkNanos(LockSupport.java:196)
at java/util/concurrent/SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:424)
at java/util/concurrent/SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:323)
at java/util/concurrent/SynchronousQueue.poll(SynchronousQueue.java:874)
at java/util/concurrent/ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:955)
at java/util/concurrent/ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:917)
at java/lang/Thread.run(Thread.java:682)
at jrockit/vm/RNI.c2java(JJJJJ)V(Native Method)
-- end of trace
Code -
public static void startMicroSessionTimer(TimerName timerName, Data Data) {
logger.debug("Starting a micro-timer for timer name: " + timerName);
//Start a micro timer to process the soap response in worker thread
SipApplicationSession applicationSession = Util.getAppSession((String)Data.get(DataAttribute.ID));
Util. AbcTimer (applicationSession, 1L, timerName.getTimerName());
}
public static void AbcTimer(SipApplicationSession appSession,
long timeInMillies, String timerName) {
logger.debug("Inside AbcTimer”);
//Some Logic
}
Logs -
16 May 2018 09:13:07,506 [jaxws-engine-1-thread-12] DEBUG -----SOME LOGS…..
16 May 2018 09:13:07,506 [jaxws-engine-1-thread-12] DEBUG [AbcUtils] [ODhlNjQ0ZjAzMTMzN2U5MGNhMTE2MTgxOTg2MTdmYjA.] Starting a micro-timer for timer name: HAHAHA
Not able to see any log after above line for Thread jaxws-engine-1-thread-12. As per log this log Inside AbcTimer should come as it is in the starting of called method ie AbcTimer. There is no Exception occured.
I have taken ThreadDump as well which I have posted above.
Not Sure but think that it is a machine specific issue. Also google it and saw that this type of issue occurred to other people as well but i didnt get the solution.
Using below JRocket Version
java version "1.6.0_141"
Java(TM) SE Runtime Environment (build 1.6.0_141-b12)
Oracle JRockit(R) (build R28.3.13-15-173128-1.6.0_141-20161219-1845-linux-x86_64, compiled mode)

How do I trigger the default signal handling behavior?

In my Java application I want to capture SIGINTs, do some pre-processing, and then let the default behavior (process termination) run. I would think I could do something like this:
Signal.handle(new Signal("INT"), new SignalHandler() {
#Override
public void handle(Signal signal) {
// preprocessing
// ...
// now do default behavior
SignalHandler.SIG_DFL.handle(signal);
}
});
However when I send at SIGINT to this application, I get a SEGV:
#
# A fatal error has been detected by the Java Runtime Environment:
#
# SIGSEGV (0xb) at pc=0x0000000000000000, pid=10261, tid=21507
#
# JRE version: Java(TM) SE Runtime Environment (8.0_51-b16) (build 1.8.0_51-b16)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.51-b03 mixed mode bsd-amd64 compressed oops)
# Problematic frame:
# C 0x0000000000000000
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /private/tmp/hs_err_pid10261.log
#
# If you would like to submit a bug report, please visit:
# http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#
Abort trap: 6
It seems SignalHandler.SIG_DFL is not meant to be called directly (even from other signal handling code). So how can I manually trigger it?
Alternatively, how can I manually replicate the behavior of SIG_DFL? It appears to be equivalent to:
System.exit(signal.getNumber() + 128)
but I don't see any documentation to that effect.
Another way to phrase my question:
In practice* is there a difference between these two code blocks?
A)
Signal.handle(new Signal("INT"), SignalHandler.SIG_DFL);
B)
Signal.handle(new Signal("INT"), new SignalHandler() {
#Override
public void handle(Signal signal) {
System.exit(signal.getNumber() + 128)
}});
*I know undocumented behavior could change at any time, but it's unlikely that the JVM's exit behavior will change mid-version. An answer that simply details what happens now is acceptable, in practice.
I think the key to the mystery here is that SIG_DFL is not the original handler for SIGINT.
The following code worked for me:
Signal sigInt = new Signal("INT");
// First register with SIG_DFL, just to get the old handler.
final SignalHandler oldHandler = Signal.handle(sigInt, SignalHandler.SIG_DFL );
// Now register the actual handler
Signal.handle(sigInt, new SignalHandler(){
#Override
public void handle(Signal signal) {
System.err.println("Sigint is being handled");
oldHandler.handle(signal);
}
});
This does not cause the segmentation violation, and instead terminates the program as expected (after printing the sample text).
Credit for originally noticing this goes to RealSkeptic, but I wanted to expand on it in an answer.
The default behavior for SIGINT, SIGTERM, and SIGHUP is not, in fact, SignalHandler.SIG_DFL. Instead, the java.lang.Terminator class registers a SignalHandler that simply calls Shutdown.exit():
SignalHandler sh = new SignalHandler() {
public void handle(Signal sig) {
Shutdown.exit(sig.getNumber() + 0200);
}
};
You can capture this SignalHandler by calling Signal.handle() (since it returns the old handler), or you can simply define your own handler that calls System.exit() which will do the same thing.
Note that Terminator's call to Shutdown.exit() is not exactly the same as System.exit(). The former is package-private, meaning you can't call it directly. If a security manager prevents you from calling System.exit(), you'll have to capture the original handler and reuse it.
Warning: this is undocumented behavior. It's unlikely but entirely possible that future releases of Java could change this behavior.
Exiting with 128+signal number seems to be typical on Unix/Linux.
Are there any standard exit status codes in Linux?
For more evidence, see also:
http://journal.thobe.org/2013/02/jvms-and-kill-signals.html
Browsing the source code on OpenJDK suggests that the default behaviour is to allow the underlying C Runtime or OS default action to proceed.
In any case this is only typical behaviour, and as you point out is not documented. Exit codes are not standardized - generally there is a convention that zero means success, and nonzero failure, but even the first part is not always adhered to. Therefore it is for you to define your own exit codes.

Play 2.3.8 - Why a TimeoutException on Ubuntu 14.04 but not on Mac OS X 10.9.5?

The controller code below contains a Play WS GET call that works just fine on my Mac OS X 10.9.5 (Mavericks) but times out (TimeoutException) when deployed/run on Ubuntu 14.04 (Trusty). I'm stumped as to why??
public class MzXXSimilarity implements MzYYSimilarity {
#Override
public Map<String, List<Double>> yScores(String question,
List<MzXXDocument> docs) {
// Output
final Map<String, List<Double>> scores = new HashMap<String, List<Double>>();
// Map of Score
final Multimap<String, Promise<MzXXScore>> scoreMap = HashMultimap.create();
// POST data
for (MzXXDocument doc : docs) {
WSRequestHolder holder = WS.url(MzXXConstants.XX_URL);
holder.setHeader("Authorization", MzXXConstants.XX_APIKEY);
holder.setTimeout(10000);
final ObjectNode json = Json.newObject();
json.put("text_1", doc.getData().get(MzXXFields.XX.getField()));
json.put("text_2", question);
// Fetch
Promise<MzXXScore> jsonPromise = holder.post(json).map(
new Function<WSResponse, MzXXScore>() {
public MzXXScore apply(WSResponse response) {
String text = json.get("text_1").asText();
JsonNode jsonScore = response.asJson();
double score = jsonScore.get("score").asDouble();
return new MzXXScore(text, score);
}
}
);
// Store
scoreMap.put(doc.getData().get(MzXXFields.XX_ANSWER.getField()), jsonPromise);
}
// Get the Results
Multimap<String, MzXXScore> results = HashMultimap.create();
for (Entry<String, Promise<MzXXScore>> scoreEntry : scoreMap.entries()) {
MzXXScore semScore = scoreEntry.getValue().get(30, TimeUnit.SECONDS);
results.put(scoreEntry.getKey(), semScore);
}
// Final Scores
for (String resultKey : results.keySet()) {
scores.put(resultKey, new ArrayList<Double>(results.get(resultKey)));
}
return scores;
}
On OS X Mavericks, this code runs fine in about 1- 2 seconds. On Ubuntu 14.04 I get the following TimeoutException:
[error] play - Cannot invoke the action, eventually got an error: java.util.concurrent.TimeoutException: Futures timed out after [30 seconds] [error] application -
! #6m2a9ldhn - Internal server error, for (POST) [/message] ->
play.api.Application$$anon$1: Execution exception[[TimeoutException: Futures timed out after [30 seconds]]]
at play.api.Application$class.handleError(Application.scala:296) ~[com.typesafe.play.play_2.11-2.3.7.jar:2.3.7]
at play.api.DefaultApplication.handleError(Application.scala:402) [com.typesafe.play.play_2.11-2.3.7.jar:2.3.7]
at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$3$$anonfun$applyOrElse$4.apply(PlayDefaultUpstreamHandler.scala:320) [com.typesafe.play.play_2.11-2.3.7.jar:2.3.7]
at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$3$$anonfun$applyOrElse$4.apply(PlayDefaultUpstreamHandler.scala:320) [com.typesafe.play.play_2.11-2.3.7.jar:2.3.7]
at scala.Option.map(Option.scala:145) [org.scala-lang.scala-library-2.11.1.jar:na]
Caused by: java.util.concurrent.TimeoutException: Futures timed out after [30 seconds]
at scala.concurrent.impl.Promise$DefaultPromise.ready(Promise.scala:219) [org.scala-lang.scala-library-2.11.1.jar:na]
at scala.concurrent.impl.Promise$DefaultPromise.result(Promise.scala:223) [org.scala-lang.scala-library-2.11.1.jar:na]
at scala.concurrent.Await$$anonfun$result$1.apply(package.scala:111) ~[org.scala-lang.scala-library-2.11.1.jar:na]
at akka.dispatch.MonitorableThreadFactory$AkkaForkJoinWorkerThread$$anon$3.block(ThreadPoolBuilder.scala:169) ~[com.typesafe.akka.akka-actor_2.11-2.3.4.jar:na]
at scala.concurrent.forkjoin.ForkJoinPool.managedBlock(ForkJoinPool.java:3640) [org.scala-lang.scala-library-2.11.1.jar:na]
The TimeoutException is caused by this for-loop:
// Get the Results
Multimap<String, MzXXScore> results = HashMultimap.create();
for (Entry<String, Promise<MzXXScore>> scoreEntry : scoreMap.entries()) {
MzXXScore semScore = scoreEntry.getValue().get(30, TimeUnit.SECONDS);
results.put(scoreEntry.getKey(), semScore);
}
OS X Mavericks environment:
Processors: 2, Memory: 8GB
Play version: 2.3.7
Scala version: 2.11
Java version: java version "1.8.0_25" (Java 8)
Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)
Ubuntu 14.04 environment:
Processors: 2, Memory: 4GB
Play version: 2.3.8
Scala version: 2.11
Java version: java version "1.8.0_45" (Java 8)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)
So far I tried the following:
run both the ubuntu and mavericks instances in both dev and prod mode but I still get the timeout exception only on ubuntu
increase the timeout up to 100 seconds on ubuntu but still get the timeout exception
change fork in run := false in build.sbt on ubuntu instance and still get the timeout exception
htop shows 290/3829 MB memory usage on the ubuntu machine so RAM doesn't seem to be an issue?
No, I'm not using a proxy in either case.
Using curl on the command line on the ubuntu machine with the same URL that play WS "gets" works fine so it doesn't look like a network/firewall issue
See build.sbt below:
name := """YYHost"""
version := "1.0-SNAPSHOT"
lazy val root = (project in file(".")).enablePlugins(PlayJava)
scalaVersion := "2.11.1"
fork in run := false
libraryDependencies ++= Seq(
javaJdbc,
javaEbean,
cache,
javaWs,
"mysql" % "mysql-connector-java" % "5.1.35"
)
My question is what could possibly cause this discrepancy? Why would this code work on Mavericks and not on Ubuntu?? Thanks for your help

Categories

Resources