Core java interview Questions You'll Most Likely Be Asked (Second Edition)


Suppose you are working on a multi–threaded application


Download 1.52 Mb.
Pdf ko'rish
bet114/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   110   111   112   113   114   115   116   117   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

Suppose you are working on a multi–threaded application.
A new requirement comes in where you need to store
key–value pairs. Which is the most appropriate Collection
to be used in such a scenario?
Answer:


289.
The java.util.Map interface supports storing data as key–
value pairs. The mostly commonly used implementation of the
Map interface is HashMap. However, the problem with HashMap
is that is it not thread safe and so not appropriate to be used in a
multi–threaded application. There is a utility method on the
Collections class called synchronisedMap(). It accepts a Map
as an input and returns a thread–safe map corresponding to the
Map object passed in. So, such a synchronized map can be used
in a multi–threaded environment. There is also another Map
implementation called ConcurrentHashMap. This is a thread–
safe implementation of the Map interface and so suitable for use
in a multi–threaded environment. ConcurrentHashMap has a
slightly better performance than a synchronized Map. A
synchronized Map synchronizes the complete Map object, so
even a read operation is not allowed while some other thread is
using the Map. The ConcurrentHashMap on the other hand
does not synchronize the whole map, so it allows read operations
while some other thread is writing to the Map. So, while both
synchronized Map and ConcurrentHashMap are suitable in a
multi–threaded environment, ConcurrentHashMap should be
used if performance is a consideration.
Suppose you need to create some utility methods in your
application. What is the best practice for creating such
methods? Where would you place them?
Answer:
Most of the time, developers place utility methods in a separate
util class. However, you should try and place utility code in the
class that it is related to. So, for example if you have a class
called Car and you need to create a utility method called
createCar, it can be a static method in the Car class itself


290.
rather than having a separate CarUtil class. However, there
are often programming situations where you may need to club
together some unrelated utility methods. In such a case, you can
create a separate class and create static utility methods in this
class. Starting Java 8, you can also have static methods in an
interface. Static interface methods help to group together utility
methods without having to create an object of a class.

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   110   111   112   113   114   115   116   117   ...   171




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling