I have a pretty short question in relation to AspectJ.
Do aspects execute from a separate thread or do they execute on the existing thread (i.e. the one your main method executes from)?
They execute in the same thread where the advised code was executing. AspectJ is not concerned about threading in any way. Of course, nothing stops you from developing an aspect that, when triggered, would go on and create new threads, or schedule work to an executor service, or whatever else you might come to think of.
It executes on the same thread that your code was initially run from. Aspects are exactly the same as normal code, it is just code that is abstracted away behind some sort of handler. You would need to inspect the code of the actual aspect to determine whether or not it is using multiple threads behind the scenes. But no, by default annotations and aspects will not be run in different threads.
Related
How can JVM allow this? I don't understand it.
My hypothesis is that the all threads that we create are actually behind one single Java thread that manage which and how the behind thread actually executes in the processor. But this way it's like you don't have parallel execution, which I don't think is what happens I guess.
Otherwise, if it's not that(and so the threads are not behind one Java thread, but they are independent), how can two created threads that are for example in that moment at the same time both inside two CPUs and want to access the same method, be aware of it and not access the method? I think there must be something that controls that. How is this synchronization done?
Lately, I have been told by Senior Developers not to use Thread.join() to wait for another Thread to finish. I've also seen several such questions on SO asking alternates to join.
In my research, I couldn't find anything wrong with join(). In fact it is widely used.
So I would like to know why not use join()? What is wrong with it? Does it promotes poor programming or architecture?
There's nothing wrong with join(). It is as good as it gets.
However, here's why you shouldn't architect your application to rely on joins. In Java, the primary abstraction for running tasks isn't Thread anymore. It is Executor. That is you wrap the concurrent tasks as Callable and simply submit it to an Executor without worrying about the execution details. This is how Executors work. You submit or execute a Callable or Runnable respectively and no need to specify Thread.
So I would like to know why not use join()?
Then here's your reason: Since you don't create or manipulate Threads in the Executor world, there's no point in using join. Almost every join could be replaced with something else (Future.get, CountDownLatch, Locks, etc.).
Note: I'm not saying that you don't need to manipulate Threads when using Executors. In some cases, it's better to create own Thread subclass and then have Executor use them via ThreadFactory.
There's nothing wrong with using Thread.join in general, however you need to be very careful and know where the thread comes from. If it comes from a thread pool - then you're in a trouble indeed, because such threads are running until the pool is terminated and shared between several workers.
A Fork/Join framework was introduced in Java 7. Consider using it instead of Thread.join(). In general you should use classes from package java.util.concurrent.* where possible, minimizing usage of original synchronization techniques like synchronized blocks, wait/notify and join. java.util.concurrent gives much more flexibility.
IMO there is nothing wrong with join. You just need to take care to ensure that the thread you are waiting on terminates in all circumstances. Since if it does not then the execution may halt forever.
So if you are making the main thread wait on some thread using join and the thread does not terminate it may cause your entire application to freeze.
In a highly concurrent program with lots of shutdown operations, wondering how to set the exit code without prematurely calling System.exit()? Possible to set an "execute this code when everything else is done" method? but I'd really just like to prematurely set the exit code.
If I understand correctly what you want is to somehow keep the exit code, run some methods and then call System.exit with the pre-decided exit code.
IMO what you should do is use Shutdown hooks instead. I.e. your code will run before the JVM shuts down and (if I got your requirement correctly) will have the same result with a straightforward coding implementation (i.e. instead of using using state variable and unusual coding logic to achieve what you are trying to do etc)
Have a master thread spawn off all other threads such that it only shuts down when all other threads are complete.
In a highly concurrent program with lots of shutdown operations
This is a code smell to me.
I can understand how multiple threads might want to shut down, but they shouldn't be allowed to do so.
Instead, I would create a global method called initiateShutdown(int code). This method would contain logic to determine when it's appropriate to actually shut down. Since you may not want a thread returning from this method, you could implement some sort of never-returning lock, and consign the thread to waiting on this lock.
Just store the result somewhere and use any suitable synchronization tool to tell that you are done. When you are done, just read the stored result and exit using System.exit(result).
I'm curious, if several threads set the result, which should you use?
I am not understanding this concept in any manner.
public class SomeName {
public static void main(String args[]) {
}
}
This is my class SomeName. Now what is thread here.
Do we call the class as a thread.
Do we call this class as thread when some other object is trying to access its method or members?
Do we call this class as thread when some other object is trying to access this object?
What does it mean when we call something in java as thread-safe ?
Being thread-safe means avoiding several problems. The most common and probably the worst is called threadlock. The old analogy is the story of the dining philosophers. They are very polite and will never reach out their chopsticks to take food when someone else is doing the same. If they all reach out at the same time, then they all stop at the same time, and wait...and nothing ever happens, because they're all too polite to go first.
As someone else pointed out, if your app never creates additional threads, but merely runs from a main method, then there is only one thread, or one "dining philosopher," so threadlock can't occur. When you have multiple threads, the simplest way to avoid threadlock is to use a "monitor", which is just an object that's set aside. In effect, your methods have to obtain a "lock" on this monitor before accessing threads, so there are no collisions. However, you can still have threadlock, because there might be two objects trying to access two different threads, each with its own monitor. Object A has to wait for Object B to release its lock on monitor object 1; Object B has to wait for Object A to release its lock on monitor object 2. So now you're back to threadlock.
In short, thread safety is not terribly difficult to understand, but it does take time, practice and experience. The first time you write a multi-threaded app, you will run into threadlock. Then you will learn, and it soon becomes pretty intuitive. The biggest caveat is that you need to keep the multi-threaded parts of an app as simple as possible. If you have lots of threads, with lots of monitors and locks, it becomes exponentially more difficult to ensure that your dining philosophers never freeze.
The Java tutorial goes over threading extremely well; it was the only resource I ever needed.
You might want to think of thread as CPU executing the code that you wrote.
What is thread?
A thread is a single sequential flow of control within a program.
From Java concurrency in practice:
Thread-safe classes encapsulate any needed synchronization so that
clients need not provide their own.
At any time you have "execution points" where the JVM is running your code stepping through methods and doing what your program tells it to do.
For simple programs you only have one. For more complex programs you can have several, usually invoked with a new Thread().run or an Executor.
"Thread-safe" refers to that your code is written in such a way that one execution point cannot change what another execution point sees. This is usually very desirable as these changes can be very hard to debug, but as you only have one, there is not another so this does not apply.
Threads is an advanced subject which you will come back to later, but for now just think that if you do not do anything special with Threads or Swing this will not apply to you. It will later, but not now.
Well, in your specific example, when your program runs, it has just 1 thread.
The main thread.
A class is thread safe when an object of that class can be accessed in parallel from multiple threads (and hence from multiple CPUs) without any of the guarantees that it would provide in a single threaded way to be broken.
You should read first about what exactly threads are, for instance on Wikipedia, which might make it then easier to understand the relation between classes and threads and the notion of threadsafety.
Every piece of code in Java is executed on some thread. By default, there is a "main" thread that calls your main method. All code in your program executes on the main thread unless you create another thread and start it. Threads start when you explicitly call the Thread.start() method; they can also start implicitly when you call an API that indirectly calls Thread.start(). (API calls that start a thread are generally documented to do so.) When Thread.start() is called, it creates a new thread of execution and calls the Thread object's run() method. The thread exits when its run() method returns.
There are other ways to affect threads, but that's the basics. You can read more details in the Java concurrency tutorial.
I tried to make a event dispatcher in Java that will dispatch events as threads. So all the EventListener classes are essentially implemented the Runnable class. Like how firing of events work traditionally, a method in the event dispatcher class loops through a list of EventListeners and then invoke their handler method, except that this time, I invoke these handler as threads by putting the listeners into new Thread(handlerObject).start(). The actual handling is done in the run() method in the EventListener.
So it looks something like:
for(EventListener listener : listenerList) {
if(listener instanceof Runnable)
new Thread(listener).start();
}
So all instructions to handle the event in the listener are put inside the run() method, which will be executed when the thread.start().
But the problem is the threads often go into a situation where one of the threads got stuck somewhere and didn't manage to continue. Sometimes, several threads may also get stuck while some managed to run through all instructions in the run() method in the listener. I looked up and this sounds like what it is called a deadlock.
I tried to put the "synchronized" modifier to all my methods but it still has this problem. I thought the synchronized keyword would simply just queue any threads trying to run a similar method until a current thread running the method has finished. But this doesn't solve the problem still. Why doesn't synchronized solve the problem especially when I already have it on all my methods and it should queue any concurrent access that may potentially cause a deadlock? I didn't use any wait() or notify() methods. Just a simple event dispatcher that attempts to run its event listener as a thread.
I am pretty new to threads but have found it very difficult to even debug it because I don't know where has gone wrong.
Thanks for any help.
Deadlock is something along the lines of this:
A needs iron to make tools, asks B for
iron
B needs tools to make iron,
asks A for tools
Neither will complete. Just because you've put the syncronized key word around them does not guarantee that you're going to run into a logical impossibility. You have to judge when one thing will be able to move forward and when it won't.
Never just add synchronized to all methods, this solves nothing - you will effectively make your program single-threaded.
When you think you have a deadlock, you can take a thread dump and analyze the output to understand what each thread is executing, which locks (if any) they are holding, what locks they are waiting for, etc.
Unfortunately without specific code or understanding the actual synchronization going on in your application, the only advice that can be given is general like this.
I don't know what you mean by 'deadlock despite synchronized keyword'. The `synchronized' keyword doesn't prevent deadlocks. It can cause them, if you have two threads that acquire locks in different orders. Solution: don't.
Your real problem is that you don't understand concurrency well enough to understand why your program is not working, let alone how to solve this. (FWIW - adding synchronized to all of your methods is only making the problem worse.)
I think that your best plan is take time out to do some reading on concurrency in Java. Here are a couple of good references:
The Java Concurrency Tutorial Stream.
Java Concurrency in Practice by Brian Goetz et al.
#wheaties has a micro-explanation of what a deadlock is, and #matt_b offers useful advice on how to diagnose a deadlock. However, these won't help a lot unless you know the right way to design and write your multi-threaded code.