midturm Flashcards

1
Q

How many thread objects execute at once per CPU

A

At any moment, at most one thread object is executing per CPU

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

what are the behaviours of thread

A

Thread: defines actual behaviour

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

What is the thread state lifecycle

A
  • new
  • ready
  • running
  • waiting
  • sleeping
  • blocked
  • dead
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

what are the behaviours of interface

A

Interface: defines desired behaviour

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

How can you put a thread on hold

A
  • yield ()
  • sleep ()
  • join ()
  • wait ()
  • suspend ()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Thread.yield()

A

Static method

Causes the thread executing the method to allow another thread of the same priority to run

Should be used for non-timesliced systems

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

When does a thread die?

A

Threads die when run() method returns

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

how to check if the thread is still viable

A

isAlive()

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

what arguments does join() take?

A

Join ([timeout])

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

join()

A

Join method causes current thread to wait until the thread of the threadObject on which the join method is called terminates (threadObject.join();)

Join lets another thread finish or gives it a limited amount of time to finish

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

Thread.sleep()

A

Static method

Causes thread to pause for a fixed period of time

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

what arguments does thread.sleep() take?

A

Thread.sleep (long milis, [int nanos])

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

thread.interrupt()

A

allows another object to interrupt the sleep period

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

What exceptions does thread.interrupt() throw?

A

interruptedException – if another thread has interrupted the current thread

IllegalArgumentException – millis is negative or value of nanos is not in the range 0-999999

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

Blocked

A

All java I/O methods step out of the running state while paused for response, said to be blocked

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

ThreadGroup

A

Can be dealt with as a unit

Hierarchical relationships – parent/child

Method calls sent to a parent group also sent to all its children

Construct your threads with the ThreadGroupName in the constructor

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

What does the RMI client do?

A

Obtains a remote reference to one or more remote objects

Invokes methods on those objects

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

Synchronization problems

A

Arises when multiple threads access shared data (producer/consumer problem)

Producer fills the buffer/Consumer empties the buffer

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

RMI interface support layers:

A

client/server
Stub/skeleton layer
remote reference layer
transport layer

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

Object monitor lock

A

Every object has a flag associated with it – called monitor lock

Used with the synchronized key word

All methods accessing shared data should synchronize on the same lock object

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

Stub/skeleton layer

A

responsible for managing the remote object interface between the client and server

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

How many synchronized methods can be active on an object at once?

A

Only 1 synchronized method may be active on an object at once

All other threads trying to acquire the monitor lock will block

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

what does RMI involve

A

RMI involve client and server sides

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

Remote reference layer

A

responsible for managing the “liveliness” of the remote objects. Manages the communication between the client/server and virtual machines

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
how to RUN the rmiregistry (2 ways)
1 – CMD – run the rmiregistry command on the server | 2 – server calls LocateRegistry.createRegistry(portNum)
26
how are RMI object parameters passed?
Object parameters are passed by value (object not the reference)
27
what does the RMI server do?
Create some remote objects (local to server) Make references to those objects available on the network Wait for clients to invoke methods on those objects
28
how are RMI objects sent?
Object serialization is used to send parameters | Object de-serialization is used to reconstitute the parameters in the destination JVM
29
Transport layer
actual network/communication layer that is used to send the information between the client and server over the wire. Currently TCP/IP based. Uses serialization.
30
what is the RMI registry
RMI Registry runs on each machine that hosts remote service objects and accepts queries for services, by default on port 1099 (Registry can be run on a non-default port if desired)
31
how to start the RMI registry (2 ways)
1 – rmiregistry is a program in the JSDK bin directory, just run it on the server 2 –LocateRegistry.createRegistry(portNum) can be called in the server THEN: Start the RMI server Start the RMI client
32
is multithreading platform dependent or system dependent?
Multithreading is platform dependent (windows etc.)
33
Synchronized as a block modifier syntax:
Synchronized(someObject){…}
34
multithreading
you can specify that applications contain threads of execution. Each thread designates a portion of a program that may execute concurrently with other threads.
35
Synchronized as a method modifier syntax:
Public synchronized push (char c)
36
Thread synchronization: How many threads does monitor allow to execute at a time?
Monitor allows 1 thread at a time to execute a synchronized method on the object
37
Synchronized as a method modifier: Public synchronized push (char c)
Only 1 thread can be active in the objects synchronized methods Other threads will block until active thread returns from method When 1 thread is executing in a synchronized method, ALL other threads are locked out of ALL synchronized methods of that object
38
How do you code remote, runnable and thread?
Extends Remote Implements Runnable Extends Thread
39
Thread synchronization: what happens to the other threads while they wait for the thread to finish executing?
All other threads block as the try to invoke the objects synchronized methods
40
Daemon threads:
Threads that run for the benefit of other threads Run in the background Do not prevent a program from terminating
41
Synchronized as a block modifier Synchronized(someObject){…}:
Any thread trying to execute the code “…” in that block must obtain the monitor lock of someObject Only 1 thread at a time can hold the monitor lock of an object Other threads will block until monitor lock has released when the current thread leaves the block
42
3 ways to create a thread
1. pass object that implements Runnable to the Thread class constructor and start a new thread: start method 2. extend the Thread class: in a new class MyThread, override run, instantiate a new MyThread object, start it. ONLY use 2 when you need to override other Thread methods besides run. 3. use an executor service: java concurrent package
43
threadObject.start() method:
places thread into runnable state, viable for scheduling for execution by the JVM thread scheduler. Now the thread is runnable, ELIGIBLE to run. Start() method returns to its caller then continues to run concurrently with the newly launched thread.
44
Thread synchronization: When synchronized method finishes:
lock on object is released, monitor lets the highest-priority ready thread attempting to invoke a synchronized method proceed
45
can executors reuse existing threads or do they create new threads for each call?
Executors can reuse existing threads and can improve performance by optimizing the number of threads.
46
Create a daemon thread:
setDaemon(true) method, when only daemonds thread exist in program – program exits.
47
Executor framework:
Used to manage many Runnable’s. creates and manages a group of threads called a thread pool to execute Runnable’s.
48
ExecutorService Methods:
Execute(runnableInstance) Submit(runnableInstance or callableInstance) invokeAny(collection_of_Callables, [long timeout, TimeUnit unit]) invokeAll(collection_of_callables, [long timeout, TimeUnit unit]) Shutdown() shutdownNow() awaitTermination(long timeout, TimeUnit unit)
49
CORBA definition
Common object request broker architecture
50
ExecutorService interface:
ExecutorService interface extends executor and declares methods for managing the life cycle of executor
51
What is CORBA
CORBA (Common object request broker architecture): enables software components written in multiple computer languages and running on multiple computers work together
52
When do you set a Daemon thread?
If thread is daemon it must be set as such before the start method is called
53
what does newCachedThreadPool do and return?
Executors method newCachedThreadPool returns an executorService that creates new threads as they’re needed by the application.
54
what type of thread is the garbage collector?
Garbage collector is a daemon thread (setDaemon(true);) – false argument means that the thread is not a daemon thread
55
ExecutorService.shutdown()
ExecutorService method shutdown notified the executorService to stop accepting new tasks but continues executing tasks that have already been submitted.
56
Java RMI:
Java only, interfaces specified in Java, distributed garbage collection integrated with local collectors, generally simpler
57
Executors factory methods:
newCachedThreadPool newFixedThreadPool(nThreads) newScheduledThreadPool(nThreads) newWorkStealingPool([nThreads])
58
Echo client java step 3 explained:
3 – perform the processing: get string from user, send string to server, read string object from server, display string to user
59
Execute(runnableInstance)
returns void so you cannot process any results; best for fire and forget tasks
60
Echo server java step 1 explained:
1 - Creating a server socket: ServerSocket server = new ServerSocket(portNumber, backlog); - port is the port or application number, backlog is the number of clients that can wait to connect ( default backlog is 50)
61
invokeAll(collection_of_callables, [long timeout, TimeUnit unit])
returns List of Future<>’s representing results of all tasks after all finish (or times out if timeout given)
62
Echo client in Java Steps:
1 – create a socket 2 – get the socket’s IO streams 3 – perform the processing 4 – close the connection
63
Echo server java step 3 explained:
3 – get the Socket’s I/O streams: inputstream outputstream enable the server to send and receive bytes to/from client. To be able to send strings(serializable object) we use ObjectInputStream / ObjectOutputStream
64
Submit(runnableInstance or callableInstance)
Returns Future<> object; access result using get() (blocking) or isDone() (non-blocking); if work causes exception, not thrown on submit(), thrown on get(); can cancel() work
65
Shutdown()
service will not accept new work, but existing tasks continue to run
66
Echo client java step 1 explained:
1 – create a socket: Socket connection = new Socket (ServerAddress, port); There must be a server at that address already listening for connections at that port
67
Echo server java step 5 explained:
5 – close the connection: output.close() , input.close() , connection.close()
68
newWorkStealingPool([nThreads])
based on ‘work-stealing’ algorithm designed to maximise parallelism
69
how does a client call a method using RMI?
Client uses remote reference to call method
70
Echo server java step 2 explained:
2 – wait for a connection: ServerSocket accept() returns a Socket. Server listens indefinitely for a connection by client
71
newScheduledThreadPool(nThreads)
pool of fixed size, at most nThreads threads in pool; work runs after some predefined delay and/or periodically
72
Echo server java step 4 explained:
4 – perform the processing: server receives objects (strings) from client. Server transmits objects (Strings) to client
73
shutdownNow()
performs shutdown() and will interrupt existing tasks possible for tasks to ignore interrupt so could be same as just shutdown()
74
Echo client java step 4 explained:
4 – close the connection:inputStream.read() returns value of -1 when it reads EOF. Output.close() input.close() connection.close()
75
newFixedThreadPool(nThreads)
pool of fixed size, at most nThreads threads in pool; new work will be blocked if all threads not idle; failed threads terminated and removed from pool, new one added to pool
76
JVM executes threads until:
exit() method of class runtime has been called and the security manager has permitted the exit operation OR all non-daemon threads have died (either by returning the call to the run() method or throwing an exception that propagates beyond the run() method).
77
Echo client java step 2 explained:
2 – get the socket’s IO streams: client uses socket’s methods getInputStream() and getOutputStream(). (ObjectInputStream input = new ObjectInputStream(connection.getInputStream());)
78
invokeAny(collection_of_Callables, [long timeout, TimeUnit unit])
does not return Future<>, instead result of first task to complete (or times out if timeout given)
79
Echo server in Java Steps:
``` 1 - Creating a server socket 2 – wait for a connection 3 – get the Socket’s I/O streams 4 – perform the processing 5 – close the connection ```
80
Wait()
puts thread into a waiting state. Threads that invoke wait() can only be processed when notified or interrupted by another thread. Threads must eventually be awakened or the thread will wait forever (deadlock).
81
Marshalling of data:
Parameters and return values, both primitive and object are transmitted between client and server Class ObjectOutputStream converts Serializable object into stream of bytes Transmits across network Class ObjectInputStream reconstructs object
82
newCachedThreadPool
pool of no particular size, new work causes more threads to be created; existing threads can be re-used if idle; if idle > 60s thread terminated and removed from pool
83
General RMI Architecture 4 steps:
1 - Server must first bind a remote object to a service name in the registry 2- Client looks up the service in the server’s registry to establish remote references 3 - Stub serialized the parameters to skeleton 4 - Skeleton invokes the remote method and serialized the result back to the stub
84
awaitTermination(long timeout, TimeUnit unit)
wait until all tasks finished, but not forever
85
What is the Stub responsible for?
The stub is responsible for sending the remote call over to the server-side skeleton
86
What does the client recieve when looking up object in RMI?
Client can look up object and receive a remote reference
87
When a client invokes a remote method, where is the call forwarded?
the call is first forwarded to the stub
88
Who registers an RMI object ?
Server registers object as remotely accessible
89
What does the Stub layer do?
The stub opens a socket to the remote server, marshaling the object parameters and forwarding the resulting data stream to the skeleton.
90
What interface does thread implement? what is the behavior?
thread implements runnable interface – behavior of thread is to “run”. We implement a run method so our code runs in a thread
91
Steps for an object becoming a remote object:
1 - Remote interface extends the interface java.rmi.Remote 2 - Each method of the interface declares java.rmi.RemoteException in its throw clause in addition to any application-specific exceptions. 3 - RMI passes a remote stub for a remote object to its caller 4 - Stub implements the same remote interfaces as the remote object itself 5 - This stub acts as a proxy for the remote object: it’s a remote reference 6 - Client invokes a method on the stub, which is responsible for carry out the call to that method on the remote object
92
What is the Skeleton layer responsible for?
The skeleton is responsible for dispatching the call to the actual remote object implementation
93
How are RMI primitive data types passed?
Primitive data types are passed by value. Copy of the primitive date type is sent to another JVM (Standard machine-independent format is used)
94
What does the Skeleton layer do?
A skeleton contains a method that receives the remote calls, unmarshals the parameters and invokes the actual method implementation on the remote object.
95
Client RMI is concerned with?
Client concerned with definitions
96
RMI server side installation:
Listed classes must be available to its class loader: remote service interface definition, remote service implementations, all other server business code
97
What does stub hide?
Stub hides serialization of parameters and the network-level communication in order to present a simple invocation mechanism to the caller
98
Server RMI is concerned with?
Server concerned with implementation
99
How does an object become remote?
Object becomes a remote object by implementing a remote interface
100
Hibernate is
Hibernate is a persistence framework
101
3 states that entities handled by a persistence framework can exist
Transient Persistent Detached
102
ORM definition
(object-relational mapping)
103
RMI client side installation:
listed classes must be available to its class loader: remote service interface definitions, server classes for objects used by client (return values), all other client business code
104
Naming method lookup
a client to query a registry Lookup accepts a URL that specifies the host name and name of the desired service, method returns a remote reference to the service object
105
Purpose of hibernate
allow you to treat your database as if it stores java objects directly
106
ORM
ORM (object-relational mapping) – mapping the objects in java to the relational entities in a database ``` entity(class) - table column - property or attribute of class row - instance of a class(an object) ```
107
How is the RMI registry accessed?
The RMI registry is accessed through a static method of Naming
108
Session factory
created once at application startup from a configuration instance
109
Client side callbacks:
server needs to call client: client acts as RMI server and exports remote object ( UnicastRemoteObject.export Object(,0)
110
Relational databases:
table, attribute of entity – column, instance of entity – row.
111
Detached
object was persistent but session is closed. Still lives on in application.
112
Session
non-threadsafe object that is used once and discarded for: single request, interaction or single unit of work
113
where are Notify() and notifyAll() called?
called in some other thread, returns waiting threads to the ready state.
114
Unit of work: session-per-request:
Is a single hibernate transaction. unit of work will span multiple physical database interactions. OpenSession(), getCurrentSession()
115
what code can Wait(), Notify() and NotifyAll() be called in?
These methods may only be called in synchronized code
116
Persistent:
objects that have representation in the database, associated to a session, changes will persist when unit of work completes.
117
POJO definition:
plain old java object
118
where are Wait(), Notify() and NotifyAll() implemented?
Implemented in Object class rather than Thread
119
Need to tell hibernate:
ipAddress, port, userid, password, database name
120
2 ways to specify how POJOs* map to database tables:
1 – Maintaining the mapping info as external XML files. Allows the mapping information to be changed to reflect business changes or schema alterations without rebuilding application 2 – annotations-based mapping – they are immediately in the source code along with the properties that they are associated with
121
Transient:
objects are created by the application (new Person();)
122
what is RMI garbage collection called
DGC (distributed garbage collector) system
123
Notify() –
signals a single, arbitrarily chosen by the implementation, waiting thread. Acts as a signal to a waiting thread that the locked object is now available.
124
Security manager:
determines a programs security policy. Sets by constructing a SecurityManager object and calls setSecurityManager method of the system class. Is no manager unless specified.
125
Java class becomes an entity by:
1 - @Entity before the class definition in the java class source file 2 - @Id right before: instance of variable for the primary key OR the getter method for the primary key
126
Persistent objects –
objects that exist permanently, independently of whether or not our programs are running
127
DGC (distributed garbage collector) system:
when client makes a reference, marks object as “dirty”, when client drops reference it notifies server. Interface to DGC is hidden in stubs and skeletons layer.
128
Security policy:
each program has a security policy, can be obtained by calling Policy.getPolicy, set by using Policy.setPolicy
129
Client/server in java steps (8):
1 – server creates a ServerSocket ( ServerSocket server = new ServerSocket(8080);) 2 – 1)server begins listening for connections on that ServerSocket (at that port). 2)the server.accept() call blocks until a client connects. (Socket connection = server.accept();) 3 – elsewhere, someone runs a client (client is separate program running on separate machine) 4 – client attempts to connect to server. 1)the client uses the socket constructor that takes a String hostname and an integer destination port. 2)source port is the port chosen by TCP/IP stack at runtime (Socket connection = new Socket(“100.121.121.100”, 8080);) 5 – the accept() method on the server now returns and the server is no longer blocked 6 – client and server both get the inputStream and outputStream of the Socket connection (output = connection.getOutputStream(); , input = connection.getInputStream(); ) 7 – another client is run on another machine, that client blocks (50 clients will block, 51st will get “connection refused”) 8 – with multithreading the server can accept() (Socket secondConn = server.accept();)
130
NotifyAll() -
signals all waiting threads to enter their runnable state.
131
How can a detached object become persistent?
Reattached to a session(persistent again) with update() or merge()
132
What exceptions are thrown with notify() and notifyAll()?
IllegalMonitorStateException will be thrown if a thread issues wait, notify or notifyall on an object without its lock InterruptedException is thrown if the waiting thread is interrupted by another
133
RMI programming steps (7):
1 - create the remote interfaces for the remote objects to implement 2 – create classes to implement the remote interfaces ( instances will be the remote objects) 3 – create the server ( instantiates and bind remote objects) – remote objects become remote by: 1: implementing a remote interface and 2: extending UnicastRemoteObject OR being exported by servers call to UnicastRemoveObject.exportObject 4 – create the client (looks up service name to get initial remote object reference) – if needed the first remote object should have methods that can return more remote references if needed 5 – compute the interfaces, server, client (javac) 6 – generate stubs and skeletons (rmic) 7 – make class files available through FTP/HTTP for client and server (for our purposes we simply have classes in classpath of client and server machines)
134
What can delete() do to a persistent object?
Delete() can make a persistent object transient
135
Use Hibernate session factory to create session objects that manage:
connection data, caching, and mappings. Your application is responsible for managing the one session factory
136
can RMI download the definitions of objects classes?
RMI provides ability to download the definition of an objects class when the class is not defined in the receiver’s java virtual machine
137
how many session factory should you have?
You should only have one session factory (exception: using hibernate to connect 2+ databases, then 1 session per database instance)
138
RMI server side 4 steps:
1 - On host machine, server program creates a remote service by first creating a local object that implements that remote interface (service) 2 – exports that object to RMI one of two ways: 1 – either the object itself extends java.rmi.server.UnicastRemoteObject 2 – server calls static method UnicastRemoteObject.export Object(remObj,portNum) – portNum can be 0 (rmi will use arbitrary port) or it can be the same as the one used for the registry 3 – server registers the object in the RMI registry under a public name, using the static method Naming.rebind 4 – this creates a listening service that waits for the clients to connect and request the service.
139
Multithreading: states of a thread (listed)
``` New Runnable Waiting Times waiting state Blocked state Terminated state ```
140
Quantum or timeslice
each thread is given a small amount of processor time called Quantum or timeslice
141
what does the operating system handle?
The operating system handles the transitions from ready and running.
142
Thread state: New:
Thread begins it life in the New and will remain in until the program starts the thread.
143
What happens to the thread when Quantum or timeslice expires?
the thread switches back to the ready state and thus loses the processors If more tasks need to be completed the operating system then assigns another thread to the processor
144
Thread state: Terminated State
Runnable thread enters the terminated state when it successfully completes its task or otherwise terminates (perhaps due to an error)
145
The operating systems sees a runnable thread in two states:
Ready and running A runnable thread in ready is a thread that has just been turned into a runnable thread and is currently waiting to be assigned to a processor A running thread is a thread that’s been a given a processor and is running its task
146
What does timeslicing allow threads to do?
Timeslicing allows for each thread that shares an equal-priority to share a processor.
147
Thread state: Timed Waiting State
A runnable thread can enter the timed waiting state for a specified interval of time(sleep). Thread will transition back to runnable when the time interval expires or when the event is waiting for occurs. Can’t use a processor
148
What priority is given to threads created by other threads?
Each new thread inherits the priority of the thread that created it.
149
Thread state: Waiting
A runnable thread transitions to the waiting state while it waits for another thread to perform a task. A waiting thread transitions back to the runnable state only when another thread notifies it to continue executing Can’t use a processor
150
What causes Indefinite postponement to occur?
Indefinite postponement occurs when a higher-priority thread enters the ready state and then the operating system preempts the current low-priority thread.
151
Thread state: Blocked State
Runnable thread transitions to the blocked state when it attempts to perform a task that cannot be completed immediately and must temporarily wait until that task completes.
152
What causes deadlock to occur?
It occurs when two threads are waiting for the other to finish before they can proceed. This would mean theses threads would forever fail to execute.
153
Thread state: Runnable
When a program starts in switches the threads state from New to Runnable. A thread in the runnable state is considered to be executing its task
154
RMI registry client use
The registry allows the client to look up a remote service (object) by name Client uses it to find references to remote objects that they want to invoke
155
RMI registry server use
Server uses it advertise their availability
156
Why does hibernate benefit programmers
Productivity - gets rid of writing complex SQL statements Maintainability - Reduces lines of code, makes system more understandable and emphasizes on business logic Portability - abstracts our application away form the underlying SQL database and dialect