LWJGL: pass OpenGL context between threads - java

I have two threads running in my program. When I try to use OpenGL functions in the thread that is not my main, it throws an IllegalStateException:No OpenGL context is current in the current thread. So my question is, how do I pass the context from the main thread to a different thread? I am using LWJGL 3.

I think I solved it but I'm not 100% sure it's the best way to do it. You have to call GLFW.glfwMakeContextCurrent(MemoryUtil.NULL); in the thread you want to depart from, then call GLFW.glfwMakeContextCurrent(window); GLContext.createFromCurrent(); from the thread you want to switch to.

Take a look at this example. It uses a Drawable that you can use in your two Java Threads. I'm not entirely sure if it still works since a lot of this class is associated with LWJGL 2. I'll test it soon and let you know if this or your method is more efficient (Gonna create a tiny micro-benchmark :) .

Related

Is it a good practice to writing to a file should be done in Background Thread? If yes, in what circumstances it is recommended?

I am developing a Java Desktop Application and I am creating a file and writing small content to it 10-50 lines.
I am doing this in Main Thread, shall I do this File I/O on a Background Thread?
I understand the fact that any intensive operation blocks the Main Thread so Background Thread is recommended but I dont observe any lag/hang in my Application while doing this File I/O.
So What is the best way or its ok to do small File I/O on main Thread.
The key thing is: you should write your code so that it is easy for you to make a change.
You see, the question "should it happen on a background" thread might result in different answers over time. Maybe today, when you do that once in a special situation, it is fine. But what if you start doing it more often in future versions of your program? Then it might become a problem.
In that sense: simply expect that this is one corner of your code that requires updates in the future. So design it in a way to quickly change that.
Having said that, in "general": prefer the background thread. Threads are pretty cheap on modern hardware. And java provides you a lot of reasonable abstractions that make it pretty easy to use background threads (think of a pool-based central ExecutorService for example). On the other hand: response times to users are always critical.
Thus I would heavily lean towards a background-thread based solution. Because in 2017 that is the almost a natural thing to do.
You are just writing few lines in file, so why to go for background? it will be better to keep it in main thread so that you can get proper exception handling in case of failure.

Other ways to perform tasks without loops?

I'm fairly new to java and I was creating a program which would run indefinitely. Currently, the way I have the program set up is calling a certain method which would perform a task then call another method in the same class, this method would perform a task then call the initial method. This process would repeat indefinitely until I stop the compiler.
My problem is when I try to create a GUI to make my program more user friendly, once I press the initial start button this infinite loop will not allow me to perform any other actions -- including stopping the program.
There has to be another way to do this?
I apologize if this method is extremely sloppy, I sort of taught myself java from videos and looking at other programs and don't entirely understand it yet.
You'll need to run your task in a new thread, and have your GUI stuff in another thread.
Actually, if you keep working on this problem, you'll eventually invent event driven programming. Lots of GUI based software, like Android, use this paradigm.
There are several solutions. The first that comes to mind is that you could put whatever method needs to run forever in its own thread, and have a different thread listen for user input. This might introduce difficulties in getting the threads to interact with each other, but it would allow you to do this.
Alternatively, add a method that checks for user input and handles it inside the infinite loop of your program. something like below
while(true){
//do stuff
checkForUserInput();
//do other stuff
}
To solve this problem, you need to run your UI in another thread.
Many programs are based on an infinite loop (servers that keep waiting for a new user to connect for example) and your problem isn't there.
Managing the CPU time (or the core) allocated to your infinite loop and the one allocated to take care of your UI interactions is the job of the operating system, not yours : that's why your UI should run in a separate thread than your actual code.
Depending on the GUI library (Swing, ...) you're using there may be different ways to do it and the way to implement it is well answered on Stack Overflow

How to drive JOGL animation from my own thread

I'm using JOGL (jogamp) and want to drive the animation from my own thread. The tutorial I ran into shows using Animator or FPSAnimator, but those have their own threads and I want to avoid that.
This is because I'm doing various other thread management and such and so I already have a thread that knows when computation results are ready to push the next frame to the GPU.
Is this possible? Or is it just a really bad idea?
It appears the answer is to directly call display on the GLWindow:
http://jogamp.org/deployment/v2.1.2/javadoc/jogl/javadoc/com/jogamp/newt/opengl/GLWindow.html#display()

Is there a function in Android analogous to "int main" in C/C++ which contains the program's main loop?

Normally in a C or C++ program there's a main loop/function, usually int main (). Is there a similar function that I can use in android Java development?
As far as an Android program is concerned there is no main().
There is a UI loop that the OS runs that makes calls to methods you define or override in your program. These methods are likely called from/defined in onCreate(), onStart(), onResume(), onReStart(), onPause(), onStop(), or onDestroy(). All these methods may be overriden in your program.
The fundamental issue is that the OS is designed to run in a resource constrained environment. Your program needs to be prepared to be halted and even completely stopped whenever the OS needs more memory (this is a multitasking OS). In order to handle that your program needs to have some of all of the functions listed above.
The Activity lifecycle describes this best (your program is one or more Activities, think of an Activity as a screen).
Bottom line: Your program 'starts' at onCreate() through onResume() but the OS is running the loop. Your program provides callbacks to the OS to handle whatever the OS sends to it. If you put a long loop at any point in your program it will appear to freeze because the OS (specifically the UI thread) is unable to get a slice of time. Use a thread for long loops.
In Android environment, there is no main(). The OS relies on the manifest file to find out the entry point, an activity in most case, into your application.
You should read http://developer.android.com/guide/topics/fundamentals.html for more detail.
According to:
http://developer.android.com/guide/tutorials/hello-world.html
The application class must support a method for each activity that the Application
supports. In the general case, the onCreate is probably equivalent to the main/top
function for your needs.
Maybe it's possible by creating a timer and execute custom functions at every tick, reset the timer when it's at a specific time
The above answers provide a "why" as to there's no "main loop" on Android (which is important to understand). I'll offer a solution to the implied question, instead, as many visitors here will be looking for exactly that.
I believe the appropriate thing to do, here, would be to create an AsyncTask which operates as your "main loop". Or better yet, design your main loop to run as a java.util.concurrent future, which can be started and ended during lifecycle events (like rotation!), using signaling (keep your data separate). The AsyncTask API is deprecated, because it was complex, and handling it properly amounted to writing code that would, effectively, operate as an AsyncTask which cleaned up when the next problematic lifecycle event transpired.
Keep in mind that this will be a separate thread from the UI, and, as such, will be required to respond in short order to UI thread events, like "onPause" and "onDestroy". If your app does not respond within a certain period of time (~5 secs, iirc) to these events, or user input events, it will be killed by the OS. It's really prudent, for a real-time app, to be able to fully respond to these events in under 1 sec, even on the lowest-end device. You can use synchronization primitives to notify other threads that their response is pending, and they can use them to signal when they are finished (or simply end, in the case of a future).

Monitoring Java from within Java

I want to write a simple visualization of a Java program by displaying the program's method calls as branches of a tree. This could be done quite simply by having the program itself tell the visualization what it is doing, but I want to be able to do this with any Java method/class and not just the ones I modify to do so.
What I need is the ability to watch the methods a program calls and what methods are called within that method and so on. Obviously, stack traces provide exactly this functionality:
java.lang.NullPointerException
at MyClass.mash(MyClass.java:9)
at MyClass.crunch(MyClass.java:6)
at MyClass.main(MyClass.java:3)
So I thought about having the program I want to monitor run in a thread and then just look at that thread's stack. However, the thread class does not really support this. It only supports printing the current stack.
Now I, of course, thought of simply changing the PrintStream of the System class so the thread would print its stack into my PrintStream, but this feels kind of wrong.
Is there a better way to do this? Are there any pre-existing classes/methods I can use?
Also, I'm currently downloading the Java source code, to check how exactly the thread class prints its stack so I could maybe subclass thread and imitate the dumpStack() method with my own getStack() method.
Look also at VisualVM, shipped with latest Java releases.
Oh shoot, looking through the source code I noticed the thread class has a method public StackTraceElement[] getStackTrace(), it just wasn't in the documentation I was reading. Now I feel dumb.
So yeah, that seems to be the solution.
One approach might be to use something like BCEL to preprocess the target bytecode to insert calls to your own code on every method entry and exit (probably best to do exit by wrapping the whole method in a try/finally block, to catch exception exits). From this, you can deduce the call tree exactly as it happens.
You could use AspectJ for that. Have a look at this description of exactly your use case.
Have a look at the ThreadMXBean class -- it my provide what you need. Essentially, you:
call ManagementFactory.getThreadMXBean() to get an instance of ThreadMXBean;
call getAllThreadIds() on the resulting ThreadMXBean to enumerate current threads;
call getThreadInfo() to get the top n stack trace elements from a given list of threads.

Categories