I am not using any threading concept in my application - by default is it single or multi-threaded?
3.1. A Java program runs in its own process and by default in one thread. Java supports threads as part of the Java language via the Thread code. The Java application can create new threads via this class. Java 1.5 also provides improved support for concurrency with the java.
Java supports single-thread as well as multi-thread operations. A single-thread program has a single entry point (the main() method) and a single exit point.
You can make use of multiple cores using multiple threads. But using a higher number of threads than the number of cores present in a machine can simply be a waste of resources. You can use availableProcessors() to get the number of cores. In Java 7 there is fork/join framework to make use of multiple cores.
Multithreading in Java is a process of executing multiple threads simultaneously. A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.
Technically every Java application has quite a few threads (you can check with jvisualvm) but from a developer's point of view a command line application is single-threaded unless you explicitly create more threads or use an API call that specifies that it may run in a different thread. (e.g. Runtime.addShutdownHook)
A special mention of those calls should go to the Object.finalize()
method, which states:
The Java programming language does not guarantee which thread will invoke the finalize method for any given object. It is guaranteed, however, that the thread that invokes finalize will not be holding any user-visible synchronization locks when finalize is invoked. If an uncaught exception is thrown by the finalize method, the exception is ignored and finalization of that object terminates.
This is probably the easiest way to accidentally create a multi-threaded application. It is also one of the reasons why the use of finalize()
is strongly discouraged in general and should be limited to very specific cases, like freeing up native resources used by an object.
AWT and Swing applications however will almost always end up multi-threaded and therefore extra care should be taken with them.
Every Java application has a minimum of two threads (and there could be more). There is always the main or application thread and the garbage collector thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With