UTP Flashcards

utopitca (210 cards)

1
Q

What defines a program as concurrent?

A

A program is concurrent if it manages multiple tasks that start; run; and complete in overlapping time periods.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What represents a flow of control in a concurrent Java program?

A

A Thread.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Which thread is always present when a Java application starts?

A

The main thread.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the purpose of extending the Thread class?

A

To create a specialized thread type by overriding the run() method with specific task logic.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

When using the Runnable interface; how is execution started?

A

By passing the Runnable object to a Thread constructor and calling thread.start().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What problem does mutual exclusion solve?

A

It prevents multiple threads from accessing shared resources simultaneously; avoiding data corruption.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is a critical section?

A

A part of the code that accesses a shared resource and must not be executed by more than one thread at a time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

In the statement synchronized(lock); what is lock?

A

An object whose “intrinsic lock” (monitor) is used to control access to the synchronized block.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What happens when a method is declared synchronized?

A

The thread must acquire the lock for the object (or the class; if static) before executing the method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What does the wait method do?

A

It causes the current thread to wait until another thread invokes notify() or notifyAll() on the same monitor.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Which methods can release a waiting thread?

A

notify() and notifyAll().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Why is wait usually called in a loop?

A

To guard against “spurious wakeups” and ensure the condition being waited for is actually met.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What happens if a thread calls wait outside a synchronized block?

A

It throws an IllegalMonitorStateException.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Which statement about notify is correct?

A

It wakes up a single random thread waiting on the object’s monitor.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the role of ExecutorService?

A

To manage a pool of threads and handle asynchronous task execution without manual thread creation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What does Executors.newSingleThreadExecutor() provide?

A

An executor that uses a single worker thread to execute tasks sequentially.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What does submit do in an ExecutorService?

A

It submits a task for execution and returns a Future representing the pending results.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What happens if you call start() twice on the same Thread instance?

A

It throws an IllegalThreadStateException.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is a potential issue when forgetting mutual exclusion in shared data access?

A

Race conditions; where the final state depends on the unpredictable timing of thread execution.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What must be true before calling wait; notify; or notifyAll?

A

The thread must own the object’s monitor (be inside a synchronized block).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What does the volatile keyword guarantee?

A

Visibility: any write to a volatile variable is immediately visible to all other threads.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Which variables can be declared as volatile?

A

Instance variables; static variables; and array elements.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is NOT provided by volatile?

A

Atomicity: it does not prevent race conditions during compound operations like i++.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Why might a thread read a stale value without volatile?

A

Because threads may cache variables in local CPU registers or memory for performance.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
What optimization permitted by the Java Memory Model can break multithreaded code?
Instruction reordering and local caching.
26
What does a write to a volatile variable establish?
A "happens-before" relationship with subsequent reads of that same variable.
27
Why might a reader thread loop never exit without volatile?
The thread might cache the loop condition variable and never check its updated value in main memory.
28
How does volatile affect memory access?
It forces the thread to read/write directly from/to main memory rather than a local cache.
29
What is a correct description of instruction reordering?
The compiler or CPU rearranges the execution order of instructions to optimize performance.
30
What behavior is guaranteed by reading a volatile variable?
The thread sees the most recent write to that variable by any thread.
31
Compared to synchronized; what does volatile NOT provide?
Mutual exclusion (locking).
32
When is volatile an appropriate choice?
For simple status flags or variables where visibility is the only concern.
33
What advantage does volatile have over synchronized?
It is "lighter" and has much less performance overhead.
34
What is a limitation of volatile?
It cannot safely handle operations that depend on the current value (e.g.; increments).
35
Which class type is designed to provide both atomicity and visibility?
Atomic classes (e.g.; AtomicInteger).
36
Why might a compiler reorder instructions?
To improve execution efficiency and utilize CPU pipelines better.
37
What can happen if volatile is omitted in a read-spin loop?
The loop might become infinite because the thread never sees the variable change.
38
What does volatile prevent in the Java Memory Model?
It prevents certain types of instruction reordering around the volatile access.
39
How do Atomic classes differ from volatile?
They provide atomic methods (like getAndIncrement) that are thread-safe compound operations.
40
What is a recommended best practice when using volatile?
Assess if visibility is truly the only concern; otherwise; use Atomic classes or synchronized.
41
What does reflection fundamentally allow a program to do?
Inspect and modify its own structure (classes; methods; fields) at runtime.
42
Which Java package provides the core reflection capabilities?
java.lang.reflect.
43
What is the central object for reflection in Java?
The Class object.
44
Which statement describes introspection in reflection?
Stopping to "look in the mirror" to see what code exists as if it were data.
45
What does manipulation in reflection enable?
Creating new objects; calling methods; and setting field values without knowing names at compile-time.
46
What does Method.invoke() allow you to do?
Call a specific method on an object dynamically at runtime.
47
What is true about reflective field access?
It can bypass standard Java access rules (like private) using setAccessible(true).
48
When does reflection validate method existence?
At runtime; when the code is executed; rather than at compile-time.
49
In static programming; what is required for calling person.sayHello()?
The method sayHello() must be defined and accessible at compile-time.
50
In dynamic reflection-based programming; what determines which method is called?
The string name of the method and its parameter types provided at runtime.
51
Which of the following is a common use case of reflection?
Dependency Injection (Spring); ORMs (Hibernate); and Unit Testing (JUnit).
52
Which technology heavily relies on reflection for ORM mapping?
Hibernate/JPA.
53
What risk comes from using reflection?
Violation of encapsulation and performance overhead.
54
Which disadvantage of reflection affects performance?
The runtime overhead required to resolve names and check permissions.
55
What is one reason reflective code may be harder to maintain?
It lacks compile-time safety; errors only appear when the program runs.
56
Why can reflection create security risks?
It can expose and modify private internal data that was meant to be hidden.
57
What happens if reflection tries to access a non-existent method?
It throws a NoSuchMethodException.
58
Which part of Java reflection allows discovering fields of a class?
getDeclaredFields().
59
What is a major conceptual difference between static programming and reflective programming?
Static relies on compile-time types; reflective treats the program structure as runtime data.
60
What is an example of manipulation in Java reflection?
Using Constructor.newInstance() to create an object.
61
What is an annotation in Java?
A form of syntactic metadata (tags) added to program elements.
62
When were annotations introduced in Java?
Java 5 (JDK 1.5).
63
Which statement about annotation metadata is correct?
It can be processed at compile-time; runtime; or strictly in the source.
64
Which symbol is used to apply an annotation?
The @ symbol.
65
What does the @Override annotation indicate?
That a method is intended to override a method from a superclass/interface.
66
What is the purpose of @Deprecated?
To mark a class or method as obsolete and discourage its use.
67
Which annotation can suppress compiler messages?
@SuppressWarnings.
68
What does @FunctionalInterface enforce?
That an interface has exactly one abstract method.
69
What is the role of meta-annotations?
They are "annotations on annotations" that define how other annotations behave.
70
Which meta-annotation specifies where an annotation can be applied?
@Target.
71
What does @Retention determine?
How long the annotation is kept (source; class; or runtime).
72
Which retention policy keeps annotations only in source code?
RetentionPolicy.SOURCE.
73
Which retention policy allows runtime reflection to read an annotation?
RetentionPolicy.RUNTIME.
74
What does @Documented achieve?
Includes the annotation in the generated JavaDoc documentation.
75
What does @Inherited enable?
Subclasses to automatically inherit the annotation from a parent class.
76
What does @Repeatable allow?
Applying the same annotation multiple times to the same element.
77
Which element type allows applying annotations to type usages such as casts or generics?
ElementType.TYPE_USE.
78
Which element type targets class declarations?
ElementType.TYPE.
79
What is a recommended best practice when designing custom annotations?
Provide sensible default values and use meaningful names.
80
Why should annotations be kept simple?
To avoid complex logic in element definitions that should just be metadata.
81
What is the primary role of a build tool like Maven or Gradle?
To automate dependency management and the project build lifecycle.
82
What does Maven's philosophy of "Convention over Configuration" imply?
It provides sensible defaults so developers only need to specify unusual parts.
83
Which Maven file defines project structure and dependencies?
pom.xml.
84
What does Maven primarily use to manage dependencies?
Standard XML configurations in the POM file.
85
Which Maven lifecycle phase compiles the source code?
compile.
86
Which feature is NOT part of Maven's standard capabilities?
Requires search for "Maven vs Gradle capabilities" (Usually manual script flexibility).
87
In Maven; where are plugins typically declared?
Inside the section of the POM.
88
What is Gradle's default build file format?
Groovy or Kotlin DSL (build.gradle.kts).
89
Which Gradle feature improves performance by only rebuilding changed components?
Incremental builds and build caching.
90
Gradle's dependency notation uses which format?
String-based: "group:name:version".
91
What repository is commonly used by both Maven and Gradle?
Maven Central.
92
Which tool is considered more flexible for custom logic inside the build file?
Gradle (due to script-based nature).
93
What is a key advantage of Gradle over Maven?
Faster build times and more flexible; script-based configuration.
94
Which tool introduced Android build support through an official plugin?
Gradle.
95
How does Gradle specify Java version compatibility?
Using JavaVersion.VERSION_XX in the java block.
96
In Maven; what does scope test indicate for a dependency?
It is only available for compiling and running tests.
97
Which statement describes the main difference between Maven and Gradle build scripts?
Maven is XML-based (declarative); Gradle is code-based (Groovy/Kotlin).
98
What is stored in a Project Object Model (POM)?
Metadata; dependencies; and build plugins for a Maven project.
99
Which key feature of Gradle helps manage multiple interdependent modules?
Multi-project builds.
100
Which tool is generally considered more verbose?
Maven (due to XML structure).
101
What is the primary purpose of a unit test?
To verify the smallest functional parts of a program in isolation.
102
What distinguishes unit testing from integration testing?
Unit testing tests components alone; integration testing tests how they work together.
103
What does the @Test annotation indicate?
That a method is a test case.
104
In JUnit; what is required of a method annotated with @Test?
It must return void and generally takes no parameters.
105
What is the main purpose of @ParameterizedTest?
To run the same test multiple times with different input values.
106
What does @ValueSource provide for a parameterized test?
A literal array of values (strings; ints; etc.) to use as test arguments.
107
What does @RepeatedTest(5) accomplish?
It executes the test exactly five times.
108
What is the purpose of a @TestFactory method?
To generate dynamic tests at runtime.
109
What does @TestTemplate define?
A template for tests that can be registered by providers.
110
What does @BeforeEach do?
Runs a setup method before each individual test method in the class.
111
Which annotation runs after each test method?
@AfterEach.
112
Which annotation runs exactly once after all tests in the class?
@AfterAll.
113
What requirement exists for methods annotated with @AfterAll?
They must be static.
114
What does @DisplayName provide?
A human-readable name for tests in reporting tools.
115
What does @Disabled do?
Prevents a test class or method from running.
116
What does @Timeout enforce?
Fails a test if its execution duration exceeds a specified limit.
117
What is regression testing used for?
To ensure that new changes haven't broken existing; previously working functionality.
118
Which testing level validates that components work together?
Integration Testing.
119
Which testing type checks the entire fully integrated system?
System Testing.
120
What is the purpose of smoke testing?
A quick check to see if the most vital core functions of an application work.
121
What happens when a ServerSocket calls accept()?
It blocks until a client connects to the specified port.
122
Which class represents a TCP client connection in Java?
java.net.Socket.
123
Which statement about TCP vs UDP in Java is correct?
TCP is connection-oriented and reliable; UDP is connectionless and faster.
124
What causes a SocketTimeoutException?
The socket waits for data for a specified time and receives nothing.
125
What is the purpose of setReuseAddress(true) on a ServerSocket?
Allows the server to bind to a port that is in a timeout state.
126
What is a typical consequence of not closing socket streams properly?
Resource leaks and occupied ports.
127
What does shutdownOutput() do on a Socket?
Signals the end of data for the output stream without closing the entire socket.
128
Which option correctly describes Nagle's algorithm (TCP_NODELAY)?
Disabling it reduces latency by sending small packets immediately.
129
What is the purpose of an InetSocketAddress?
It represents an IP address and a port number.
130
Which statement about blocking vs non-blocking sockets is correct?
Blocking waits for I/O; non-blocking (NIO) allows a thread to do other work while waiting.
131
What does a stream represent in Java?
A continuous flow of data from a source to a destination.
132
Which class is used to read bytes from a file?
FileInputStream.
133
What is the purpose of the BufferedReader class?
To efficiently read text by buffering characters for better performance.
134
Which method is used to close a stream and release resources?
close().
135
Which class reads text line by line?
BufferedReader.
136
What does the flush method do in output streams?
Forces any buffered output bytes to be written out.
137
What is the difference between FileInputStream and FileReader?
FileInputStream reads raw bytes; FileReader reads characters (text).
138
What does try-with-resources guarantee?
That any resources declared in the block are automatically closed.
139
Which class allows writing objects to a file in binary form?
ObjectOutputStream.
140
What is required to read an object written by ObjectOutputStream?
The object's class must implement Serializable.
141
What is a key difference between Java I/O and Java NIO?
Java I/O is stream-oriented and blocking; NIO is buffer-oriented and can be non-blocking.
142
What does a Buffer represent in Java NIO?
A container for a fixed amount of data of a specific primitive type.
143
Which Buffer method prepares it for reading after writing data into it?
flip().
144
What does the clear() method of a Buffer do?
Resets the buffer's position and limit to prepare it for new writing.
145
What does a Channel represent in NIO?
A "pipe" for reading and writing data to/from a buffer.
146
Which Channel is commonly used for reading files in NIO?
FileChannel.
147
What is the purpose of a Selector in NIO?
It allows a single thread to manage multiple non-blocking channels.
148
What mode does NIO enable that allows a thread to continue executing even if I/O is not ready?
Non-blocking mode.
149
What is required to use a Channel with a Selector?
The channel must be in non-blocking mode.
150
Which of the following is true about Path (NIO.2)?
It is a modern replacement for the File class.
151
What fundamental challenge does distributed computing aim to solve?
Making code on one computer execute on another.
152
What does RMI allow?
A Java object on one JVM to invoke methods on an object in another JVM.
153
Which protocol does Java RMI primarily use?
JRMP (Java Remote Method Protocol).
154
Why is RMI considered tightly coupled?
It requires both ends to be Java and share the same class definitions.
155
What is a key limitation of RMI that led to newer technologies?
Language specificity and difficulty crossing firewalls. RMI is language-specific (Java-only), which prevents it from connecting to systems written in other languages like .NET or Python. Additionally, it is not firewall-friendly because it uses dynamic ports.
156
What was SOAP originally designed to solve?
Cross-language distributed computing using XML over HTTP.
157
Which technology defines SOAP contracts?
WSDL (Web Services Description Language).
158
What is a major drawback of SOAP?
Extreme verbosity and complexity of the XML messages.
159
What motivated the shift from SOAP to REST?
The need for a simpler; lightweight; and web-friendly alternative. The shift was motivated by a desire for simplicity. Developers wanted to use the web's existing infrastructure (HTTP) without inventing a complex new protocol.
160
What does REST primarily leverage?
Standard HTTP methods/leverage (GET; POST; etc.) and simple data formats (JSON).
161
What is a common limitation of REST for internal high-performance systems?
HTTP/1.1 has significant overhead, and text-based JSON is less efficient for data transfer than binary formats.
162
Why can REST endpoints be ambiguous?
There is no single enforced contract (unlike WSDL or Proto).
163
What problem does gRPC aim to solve in microservices?
High-latency; bulky JSON communication. It aims to solve the high overhead of REST in microservices architectures where hundreds of internal services need to communicate constantly with high reliability and performance.
164
What does gRPC use to define service contracts?
Protocol Buffers (.proto files).
165
Which transport protocol does gRPC rely on for high performance?
HTTP/2.
166
What serialization format does gRPC use?
t uses Protocol Buffers (protobuf), a fast and compact binary serialization format.
167
Which feature is natively supported in gRPC but not in REST?
Bidirectional streaming.
168
What is a major advantage of gRPC over REST?
It is much faster; has strict contracts; and smaller payloads. gRPC offers much higher performance due to binary serialization and HTTP/2, and it provides strict, machine-readable contracts that generate client/server code automatically.
169
Which statement best describes the evolution from RPC → RMI → SOAP → REST → gRPC?
A shift toward language neutrality; then back toward high-performance binary contracts.
170
In the gRPC development process; what is generated by the protoc compiler?
The protoc compiler generates the necessary Java classes (stubs and abstract service classes) from the .proto file.
171
What is the primary goal of JDBC in Java applications?
To provide a uniform way to interact with any relational database.
172
Which core JDBC interfaces were present in the initial 1.0 release?
DriverManager; Connection; Statement; and ResultSet.
173
Why did JDBC 4.0 reduce the need for Class.forName("...Driver") calls?
It introduced service provider discovery; which automatically loads the driver.
174
Which JDBC driver type is considered the standard choice in modern applications?
Type 4 (pure Java; connects directly to DB). Type 4 is considered the standard4. It is written entirely in Java and communicates directly with the database server over the network via $TCP/IP$5.+1
175
Why are Type 4 JDBC drivers preferred in containerized or cloud deployments?
They require no client-side native libraries and are easy to package. They are preferred because they are "Pure Java" JAR files requiring zero client configuration. They do not require native C++ libraries or middleware, making them platform-independent and ideal for self-contained environments like Docker. +4
176
How does a Type 3 JDBC driver typically operate?
It uses a middleware server to translate JDBC calls into the database protocol.
177
Which statement best describes DriverManager compared to DataSource?
DriverManager is the legacy approach; DataSource is the modern; more flexible alternative. DriverManager is used for simple standalone applications or prototyping, while DataSource is for modern, enterprise, or web applications that require scalability. +1
178
Why is DataSource preferred in modern enterprise applications?
It supports connection pooling and distributed transactions out of the box.
179
What is the main performance benefit of connection pooling?
It avoids the "heavy" overhead of opening a new physical connection for every request.
180
In a connection pool; what typically happens when application code calls connection.close()?
The connection is returned to the pool for reuse rather than actually being closed.
181
What was a major problem with manual try-catch-finally resource management in pre-Java 7 JDBC code?
It was extremely verbose and prone to "swallowing" exceptions during cleanup. It was "actively dangerous," causing silent resource leaks, losing original exceptions if a secondary error occurred during closing, and often having the wrong closing order. +3
182
How does try-with-resources improve JDBC code safety?
It ensures all database resources are closed in the reverse order they were opened.
183
What is a primary security risk of using Statement with string concatenation for SQL queries?
SQL Injection.
184
Which property of PreparedStatement makes it resistant to SQL injection?
It uses placeholders (?)
185
How can PreparedStatement improve performance compared to Statement for repeated queries?
The database can pre-compile the SQL plan and reuse it.
186
In JDBC 4.2 and later; which Java type is recommended for representing a pure date without time or zone?
LocalDate.
187
Which mapping is generally safest for a TIMESTAMP column representing an absolute point in time?
Instant or OffsetDateTime. Mapping to Instant is the safest choice because it forces everything to UTC and avoids time zone surprises. +1
188
What subtle problem can occur when mapping dates using legacy java.sql.Date on servers in different time zones?
The date can "shift" by one day due to local timezone differences. t can store different millisecond values for the same date depending on the server's local time zone, leading to silent data corruption .
189
Which JDBC API pattern is recommended to read modern date/time values?
rs.getObject(index; Instant.class).
190
Which of the following best describes the current status of JDBC specifications since 4.0?
The core API has remained remarkably stable since 2006, with most new database features being handled by individual drivers rather than the JDBC specification itself
191
What major problem existed before JPA that made persistence difficult?
The manual mapping of table rows to Java objects was tedious and error-prone.
192
What was one major issue with JDBC based persistence?
The "impedance mismatch" between objects and rows. It required manual mapping between database rows and Java objects, which was "painful," error-prone, and tedious.
193
Why were EJB 2.x Entity Beans disliked by developers?
They were "heavy;" required complex configurations; and were hard to test.
194
Which feature made Hibernate more popular than earlier persistence solutions?
Its lightweight; POJO-centric design.
195
What major influence did Hibernate have on JPA 1.0?
JPA 1.0 was heavily modeled after Hibernate's successful patterns. POJO-based entities, annotations (@Entity, @Id), EntityManager API, and JPQL
196
What is one key feature introduced with JPA 1.0?
Standardized annotations and the EntityManager API. POJO-based entities, annotations (@Entity, @Id), EntityManager API, and JPQL
197
Which feature was introduced in JPA 2.0?
Criteria API and support for collections of basic types.
198
What improvement appeared in JPA 2.1?
Support for AttributeConverters and stored procedure calls.
199
What was the most visible change in Jakarta Persistence 3.0?
Changing the package namespace from javax.persistence to jakarta.persistence.
200
What does POJO centric development in JPA imply?
Entities are simple Java classes that don't need to extend complex framework classes.
201
What does annotation driven configuration allow in JPA?
Defining database mapping directly inside the Java source code. It allows developers to describe the mapping between Java classes and database tables using annotations (like @Entity or @Id) directly on the classes and fields.
202
What is transparent persistence?
The feeling that objects are saved automatically without writing SQL. Once an entity is managed (inside an EntityManager), JPA automatically tracks changes and flushes them to the database, a process known as dirty checking.
203
What role does the persistence context play?
It acts as a "first-level cache" and tracks all managed entities. It acts as a first-level cache where entities loaded in one EntityManager are cached for the lifetime of that context.
204
What is the write behind mechanism?
Delaying SQL execution until the end of a transaction to optimize performance.
205
What does vendor neutrality mean in JPA?
You can switch from Hibernate to EclipseLink by just changing a setting in persistence.xml.
206
What is one trade off of using JPA?
Convenience comes with performance trade-offs such as the overhead of dirty checking, proxy objects for lazy loading, and the risk of $N+1$ queries.
207
What requirement must every JPA entity meet?
It must be a class annotated with @Entity and have a primary key (@Id). Every entity must have a unique identifier marked with the @Id annotation.
208
Which identity generation strategy uses a database sequence?
GenerationType.SEQUENCE.
209
What is the primary purpose of EntityManager?
It serves as the central API for performing database operations such as persist (Create), find (Read), and remove (Delete).
210
What is the default fetch type for @OneToMany associations?
LAZY (it only loads the data when you actually access it).