Not able us Virtual Threads using Project Loom - java

I was exploring the Virtual Threads in Project Loom. The Documents say it as straight forward with simple lines of code as below:
Thread.startVirtualThread(() -> {
System.out.println("Hello, Loom!");
});
Or
Thread t = Thread.builder().virtual().task(() -> { ... }).start();
I have tried both of them, For the first one, I receive an error
The method startVirtualThread(() -> {}) is undefined for the type Thread
And for the second one
- The method builder() is undefined for the type Thread
One browsing, found that lombok is required, Installed lombok as well. However it doesn't show up in Eclipse About section, I am able to use lombok, But still my issue is not resolved.
Below link show the documentation, I am referring to.
enter link description here
Sample Code:
public class threads {
public void simpleThread() {
Thread start = Thread.builder().virtual().task(() -> {
System.out.println("Hello World");
}).start();
Thread.startVirtualThread(() -> {
System.out.println("Hello, Loom!");
});
}
public static void main(String[] args) {
// TODO Auto-generated method stub
threads trd = new threads();
trd.simpleThread();
}
}

It looks like older versions of Eclipse is giving a compilation error when calling the new Thread methods related to Loom.
Please try to use the latest Eclipse (currently 2020-09) with an OpenJDK Project Loom Early-Access Build.
You can make sure that this is an Eclipse related issue by compiling and running your program directly from the command line (using javac and java commands).

For ubuntu system:
Set the java 16 path in .bashrc file. Make sure only have java 16 path present in the file. If any other java path is mentioned then following command may not work.
If you want to confirm if the java version is set to 16 then execute java -version.
Then you can try directly compile your loom class through following command.
javac className.java
java className
It worked for me.

Even when you get the compilation problems go away, this might or might not print anything.
A virtual thread needs a carrier (a native thread to be executed on); and if the native thread finishes earlier then the virtual one starts, there is no such carrier; thus you get no printing. There are a couple of ways to work around that.
The simplest (just to see that this works), is to make the carrier threads sleep for a short while:
Thread.startVirtualThread(() -> {
while (true) {
System.out.println("trying " + Thread.currentThread().getName());
}
});
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
On my machine this gives enough time for some output to be generated.
Another way would be join on the carrier:
Thread t = Thread.startVirtualThread(() -> {
System.out.println("trying " + Thread.currentThread().getName());
});
t.join();
This works for demo purposes, but in real life you probably need an executor. One way to supply it would be via :
Thread.builder()
.virtual(Executors.newFixedThreadPool(1))
.task(() -> {
System.out.println("started");
})
.build()
.start();
System.out.println("done");
You can even use Executors::newVirtualThreadExecutor where the current documentation states:
Creates an Executor that starts a new virtual thread for each task
So what you could do, is something like:
ExecutorService service = Executors.newVirtualThreadExecutor();
service.execute(() -> {
System.out.println(Thread.currentThread().getId());
});
service.execute(() -> {
System.out.println(Thread.currentThread().getId());
});
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));

Related

How to stop a maven project started in Netbeans

I have a project in NetBeans that starts with a main function, that takes arguments. When I hit the "Stop" Button, the project continues running, but there is no output anymore.
Currently I have to remember to manually stop the process from the console.
How can I modify my project, maven setup or NetBeans configuration to make the process halt when I hit stop.
I can live with the process not having its finalizers or ShutdownHooks called.
Consider this class:
public class Main {
public static void main(String[] args) {
System.out.println("args: " + Arrays.asList(args));
new Main().action();
}
private void action() {
Date start = new Date();
long endTime = start.getTime() + 600000;
Date end;
do {
synchronized (Thread.currentThread()) {
try {
Thread.currentThread().wait(1000);
System.out.println("PING");
} catch (InterruptedException iex) {
return;
}
}
end = new Date();
} while (end.getTime() < endTime);
}
}
I want it to die using only NetBeans Stop button.
When you hit "Stop" in the NetBeans output, NB stops the maven process, but maven had spawned the actual program output, so the stop command is not handed over to your program.
NetBeans calls the exec-maven-plugin with the 'exec' goal by default. If you change it to the 'java' goal there is no new process. After the change below, the 'Run' section in your projects 'Properties' will be empty and of no use. I did not test what happens if you call 'System.exit' or similar in this scenario.
Also note, that you have to take care that you modify the version number here by yourself from now on.
You have to go to Projects window, right click your project, go to the Properties and select the Actions element and the the Run project entry. It will look like this:
You have to modify
Execute Goals: to process-classes org.codehaus.mojo:exec-maven-plugin:1.2.1:java (change the exec in the end to java).
Set Properties: to
exec.mainClass=de.steamnet.stopfromnetbeans.Main
exec.classpath=%classpath
exec.args=First Second 'Third Space'
So that it looks like this:
From now on, Maven will not fork a new process, so when you hit "Stop" it will actually Stop the process.

Could not load JIntellitype.dll from local file system or from inside JAR

I am trying to use JIntellitype to listen to global hotkeys but I get this error:
Exception in thread "main"
com.melloware.jintellitype.JIntellitypeException: Could not load
JIntellitype.dll from local file system or from inside JAR at
com.melloware.jintellitype.JIntellitype.(JIntellitype.java:114)
at
com.melloware.jintellitype.JIntellitype.getInstance(JIntellitype.java:177)
at utils.HotKey.(HotKey.java:19) at
ui.Main.Catch_Hotkeys(Main.java:78) at ui.Main.(Main.java:20)
at ui.Main.main(Main.java:15) Caused by: java.io.IOException:
FromJarToFileSystem could not load DLL:
com/melloware/jintellitype/JIntellitype.dll at
com.melloware.jintellitype.JIntellitype.fromJarToFs(JIntellitype.java:150)
at
com.melloware.jintellitype.JIntellitype.(JIntellitype.java:105)
... 5 more Caused by: java.lang.NullPointerException at
com.melloware.jintellitype.JIntellitype.fromJarToFs(JIntellitype.java:146)
... 6 more
I have loaded the jar file and I also pointed to the folder where the dlls are located through Referenced Libraries.
Here is the code I am trying to run:
import com.melloware.jintellitype.HotkeyListener;
import com.melloware.jintellitype.IntellitypeListener;
import com.melloware.jintellitype.JIntellitype;
public class HotKey extends Thread implements HotkeyListener, IntellitypeListener {
private final int CTRL_C_SHIFT = 10;
public HotKey()
{
JIntellitype.getInstance().unregisterHotKey(CTRL_C_SHIFT);
JIntellitype.getInstance().registerHotKey(CTRL_C_SHIFT, JIntellitype.MOD_CONTROL + (int)'C', JIntellitype.MOD_SHIFT);
if (!JIntellitype.isJIntellitypeSupported())
{
System.exit(1);
}
}
#Override
public void onIntellitype(int arg0)
{
}
#Override
public void onHotKey(int key)
{
if (key == CTRL_C_SHIFT)
{
System.out.println("smg");
}
}
}
Any idea how to fix this?
Your problem will occur because of a version problem between that OS version and the JRE version.
You should check:
Whether an appropriate dll file is installed in your OS system folder.
JIntellitype package has two dll files, one is for 32bit OSs and the other is for 64bit OSs, they have different names.
Check your Java Platform version in the properties of the projects.
You can try to change the Java Platform, if there are more than one types of JDKs.
Make sure about which one is for 64bit or 32bit version.
Have good luck!
I recommend you do something like this:
try
{
JIntellitype.getInstance().unregisterHotKey(CTRL_C_SHIFT);
MyHotKeyListener hotKeyListener = new MyHotKeyListener();
hotKeyListener.addObserver(new MyEventListener());
JIntellitype.getInstance().addHotKeyListener(hotKeyListener);
JIntellitype.getInstance().registerHotKey(CTRL_C_SHIFT, JIntellitype.MOD_CONTROL + (int)'C', JIntellitype.MOD_SHIFT);
}
catch (JIntellitypeException je)
{
logger.warn("JIntellitype initialization failed.");
// DO WHATEVER (NOTIFY USERS?)
}
I can point to other threads, including one where the creator of this library himself denies problems with the library. However, many users such as myself encounter these sort of problems from time to time where JIntellitype fails to initialize and the only solution is to reboot the computer. Because of this, you should catch the JIntellitype exception (the only exception thrown by the library) and warn users (via dialog window) that the hotkey failed to register. You should give them the option to continue without them, or to reboot the computer and trying again.
Trust me.... unless this is a constant problem (which means you configured it incorrectly), it is your best alternative. This WILL happen from time to time at random.

How can I track the number of calls to a method in JDK? [duplicate]

Consider the two simple Java classes below:
First Example
class Computer {
Computer() {
System.out.println("Constructor of Computer class.");
}
void On() {
System.out.println("PC turning on...");
}
void working() {
System.out.println("PC working...");
}
void Off() {
System.out.println("PC shuting down...");
}
public static void main(String[] args) {
Computer my = new Computer();
Laptop your = new Laptop();
my.On();
my.working();
your.On();
your.working();
my.Off();
your.Off();
}
}
Second Example
class Laptop {
Laptop() {
System.out.println("Constructor of Laptop class.");
}
void On() {
System.out.println("Laptop turning on...");
}
void working() {
System.out.println("Laptop working...");
}
void Off() {
System.out.println("Laptop shuting down...");
}
}
After the program run, how do I trace (1) which object call which method (2) and how many times?
Just a little precision, I might have 100 classes and 1000s of objects each of them calling 100s of methods. I want to be able to trace (after I run the program), which object called which method and how many times.
Thanks for any suggestion.
This prints a line for each method call of all objects in all threads:
Runtime.traceMethodCalls() (deprecated / no-op in Java 9)
And
Runtime.traceInstructions (deprecated / no-op in Java 9)
You can use a call tracer like housemd or btrace or inTrace
For more involved analysis, you can use a call graph utility like one of these:
javashot
java-callgraph
(here is an article on the subject)
The deprecated methods above are slated for removal, because there are now JVM-specific alternatives:
Java Flight Recorder Part of JDK 7 as of build 56. Requires commercial license for use in production
VisualVM Free/popular 3rd party
Both of those tools pretty easy to setup and start collecting information and have nice GUI interfaces. They attach to a running JVM process and allow for thread snapshots and various other kinds of diagnosis (Visual VM has a lot of available plugins but that can take awhile to sort through to configure and understand, if you want to go beyond default behavior, whereas JFR is instrumented with more by default).
Also, don't underestimate the usefulness of JVM distributed command line utilities ($JAVA_HOME/bin), for performing some easily accessible diagnostics.
jstack stack trace
jmap memory map
jstat JVM statistics monitoring
jhat heap analysis tool
jdb debugger
jinfo java process or core file config info
$ jdb -classpath ... -sourcepath ... my.App
jdb> stop on my.App.main
jdb> run
jdb> step <... repeat until get to interesting line...>
jdb> threads
jdb> trace go methods 0x1 <... 0x1 is our main thread ID ...>
jdb> step
<...HERE you get full methods calls trace...>
jdb> quit

How to create a process which can execute concurrently with respect to java process [duplicate]

I am working on a program written in Java which, for some actions, launches external programs using user-configured command lines. Currently it uses Runtime.exec() and does not retain the Process reference (the launched programs are either a text editor or archive utility, so no need for the system in/out/err streams).
There is a minor problem with this though, in that when the Java program exits, it doesn't really quit until all the launched programs are exited.
I would greatly prefer it if the launched programs were completely independent of the JVM which launched them.
The target operating system is multiple, with Windows, Linux and Mac being the minimum, but any GUI system with a JVM is really what is desired (hence the user configurability of the actual command lines).
Does anyone know how to make the launched program execute completely independently of the JVM?
Edit in response to a comment
The launch code is as follows. The code may launch an editor positioned at a specific line and column, or it may launch an archive viewer. Quoted values in the configured command line are treated as ECMA-262 encoded, and are decoded and the quotes stripped to form the desired exec parameter.
The launch occurs on the EDT.
static Throwable launch(String cmd, File fil, int lin, int col) throws Throwable {
String frs[][]={
{ "$FILE$" ,fil.getAbsolutePath().replace('\\','/') },
{ "$LINE$" ,(lin>0 ? Integer.toString(lin) : "") },
{ "$COLUMN$",(col>0 ? Integer.toString(col) : "") },
};
String[] arr; // array of parsed tokens (exec(cmd) does not handle quoted values)
cmd=TextUtil.replace(cmd,frs,true,"$$","$");
arr=(String[])ArrayUtil.removeNulls(TextUtil.stringComponents(cmd,' ',-1,true,true,true));
for(int xa=0; xa<arr.length; xa++) {
if(TextUtil.isQuoted(arr[xa],true)) {
arr[xa]=TextDecode.ecma262(TextUtil.stripQuotes(arr[xa]));
}
}
log.println("Launching: "+cmd);
Runtime.getRuntime().exec(arr);
return null;
}
This appears to be happening only when the program is launched from my IDE. I am closing this question since the problem exists only in my development environment; it is not a problem in production. From the test program in one of the answers, and further testing I have conducted I am satisfied that it is not a problem that will be seen by any user of the program on any platform.
There is a parent child relation between your processes and you have to break that.
For Windows you can try:
Runtime.getRuntime().exec("cmd /c start editor.exe");
For Linux the process seem to run detached anyway, no nohup necessary.
I tried it with gvim, midori and acroread.
import java.io.IOException;
public class Exec {
public static void main(String[] args) {
try {
Runtime.getRuntime().exec("/usr/bin/acroread");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Finished");
}
}
I think it is not possible to to it with Runtime.exec in a platform independent way.
for POSIX-Compatible system:
Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", "your command"}).waitFor();
I have some observations that may help other people facing similar issue.
When you use Runtime.getRuntime().exec() and then you ignore the java.lang.Process handle you get back (like in the code from original poster), there is a chance that the launched process may hang.
I have faced this issue in Windows environment and traced the problem to the stdout and stderr streams. If the launched application is writing to these streams, and the buffer for these stream fills up then the launched application may appear to hang when it tries to write to the streams. The solutions are:
Capture the Process handle and empty out the streams continually - but if you want to terminate the java application right after launching the process then this is not a feasible solution
Execute the process call as cmd /c <<process>> (this is only for Windows environment).
Suffix the process command and redirect the stdout and stderr streams to nul using 'command > nul 2>&1'
It may help if you post a test section of minimal code needed to reproduce the problem. I tested the following code on Windows and a Linux system.
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
Runtime.getRuntime().exec(args[0]);
}
}
And tested with the following on Linux:
java -jar JustForTesting.jar /home/monceaux/Desktop/__TMP/test.sh
where test.sh looks like:
#!/bin/bash
ping -i 20 localhost
as well as this on Linux:
java -jar JustForTesting.jar gedit
And tested this on Windows:
java -jar JustForTesting.jar notepad.exe
All of these launched their intended programs, but the Java application had no problems exiting. I have the following versions of Sun's JVM as reported by java -version :
Windows: 1.6.0_13-b03
Linux: 1.6.0_10-b33
I have not had a chance to test on my Mac yet. Perhaps there is some interaction occuring with other code in your project that may not be clear. You may want to try this test app and see what the results are.
You want to launch the program in the background, and separate it from the parent. I'd consider nohup(1).
I suspect this would require a actual process fork. Basically, the C equivalent of what you want is:
pid_t id = fork();
if(id == 0)
system(command_line);
The problem is you can't do a fork() in pure Java. What I would do is:
Thread t = new Thread(new Runnable()
{
public void run()
{
try
{
Runtime.getRuntime().exec(command);
}
catch(IOException e)
{
// Handle error.
e.printStackTrace();
}
}
});
t.start();
That way the JVM still won't exit, but no GUI and only a limited memory footprint will remain.
I tried everything mentioned here but without success. Main parent Java process can't quit until the quit of subthread even with cmd /c start and redirecting streams tu nul.
Only one reliable solution for me is this:
try {
Runtime.getRuntime().exec("psexec -i cmd /c start cmd.cmd");
}
catch (Exception e) {
// handle it
}
I know that this is not clear, but this small utility from SysInternals is very helpful and proven. Here is the link.
One way I can think of is to use Runtime.addShutdownHook to register a thread that kills off all the processes (you'd need to retain the process objects somewhere of course).
The shutdown hook is only called when the JVM exits so it should work fine.
A little bit of a hack but effective.

Disabling the Keyboard and mouse

I am a newbie to JNA and I have this code which is supposed to block the input by calling the dll file in win7. But when I run this code, nothing happen. There is no compilation error and I can't figure out why it doesn't block my keyboard and mouse. Please guide me.
public class BlockInput {
public static void main(String[] args) {
NativeLibrary lib = NativeLibrary.getInstance("user32");
Function fun = lib.getFunction("BlockInput");
System.out.println("Lib :" + lib + ".\nFun " + fun + ".");
fun.invoke(new Object[]{Boolean.TRUE});
try {
Thread.sleep(10000);
} catch(InterruptedException ie) {}
lib.dispose();
}
}
EDIT : With Native.getLastError(); I came to know that whicle accessing the dll file I recieve the error 5 (Access denied).Is there any possible way to gain access,so that I can make it work?
If you are running on Windows Vista or Windows 7, you might need to run the program as administrator. Make a batch file that runs your Java class to make things easier.
Try This - A Native Global keyboard and mouse listeners for Java.
JNativeHook

Categories