Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Java single-threaded or multi-threaded by default? [closed]

I am not using any threading concept in my application - by default is it single or multi-threaded?

like image 250
user3814659 Avatar asked Aug 29 '14 20:08

user3814659


People also ask

Is Java single threaded by default?

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.

Is Java always multithreaded?

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.

Does Java use multiple cores?

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.

What is multithreading name the default thread in Java?

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.


2 Answers

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.

like image 88
biziclop Avatar answered Oct 04 '22 10:10

biziclop


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.

like image 24
Elliott Frisch Avatar answered Oct 04 '22 10:10

Elliott Frisch