Flyweight Design Pattern

A class that has only one instance for each unique state.
Flyweight is an assurance that no more than one instance of a class have identical state.
1. Achieved by caching identical instances of objects to reduce object construction.
2. similar to singleton, but has many instances , one for each unique – state object.
3. useful for cases when there are many instances of a type but many are same.
4.Can be used in conjunction with Factory pattern to create very efficient object-builder.
Examples in java :- String, Image/Toolkit, Formatter.

class pseudo-code sketch:
public class Flyweighted {
static map or table of instances
private constructor
static method to get an instance
if we have created this type of instance before, get it from map and return it
otherwise, make the new instance, store and return it
}

===========

A class that has been flyweighted!

public class Point {
private static Map instances = new HashMap();

public static Point getInstance(int x, int y) {
String key = x + “, ” + y;
if (instances.containsKey(key)) // re-use existing pt
return (Point)instances.get(key);

Point p = new Point(x, y);
instances.put(key, p);
return p;
}

private final int x, y; // immutable

private Point(int x, int y) {

Categories: Agnihotris Notes | Leave a comment

IOC and DI

IOC :- Inversion of control
DI :- Dependency Injection

IOC :-
coding to interface (one component should dependent on other component’s interface and not on impl), and e.g

interface iComp_2 {…}

class Comp_1 {
iComp_2 c2 = ….;
}
removing the component implementation specific code e.g

Comp_1 {
iComp_2 c2 = getComp_2_Impl(); // not new Comp_2_Impl();
}
IOC can be achieved by either of the following:

1. DI (Dependency Injection)

3 types of DI

1.1 Constructor Injection

1.2 Setter Injection

1.3 Interface Injection
2. Service Locator

DI (Dependency Injection) container

Runtime impl determination and not compile time: determines at runtime which concrete implementation of an interface to be used based on some config file (so at compile time we don’t know which impl is going to be used and thus increases configurability of the application). It is an implementation where the concrete relation between different modules is decided at “run time”.

Instantiation of impl after dependency injection: after determining the impl, it instantiates that impl by first creating all of its dependencies (specified in config file) and then injecting those dependencies into that impl

Instance Life-cycle management: DI containers usually only keep a reference to objects it needs to manage life cycles for, or that are reused for future injections, like singletons or flyweights. When configured to create new instances of some components for each call to the container, the container usually just forgets about the created object. Otherwise the garbage collector would have a hard time collecting all these objects when no longer used.

Categories: Agnihotris Notes | Leave a comment

Remove duplicate rows from table

Using “Delete Top( )” clause:

If you want to delete duplicate rows for a pirticular empid then use “Top()” command in delete query as shown below
delete top(2) From EmpDup where empid=2
OR:
delete top(select count(*)-1 From EmpDup x where x.empid=2) From EmpDup where empid=2

=
Delete all the rows that is bigger then the smallest rowid value given for a key.

SQL> DELETE FROM table_name A WHERE ROWID > (
2 SELECT min(rowid) FROM table_name B
3 WHERE A.key_values = B.key_values);
==

If you want to delete all the rows if the selected columns repeated more than 1 time then use following query,
Query to delete these 3 duplicated rows or repeated more than 1 time,
delete from EmpDup where
EmpID in(select EmpID from EmpDup group by EmpId having count(*) >1)

=

Below method is usually faster. Remember to recreate all indexes , constraints, triggers etc. on the table when done.

SQL> create table table_name2 as select distinct * from table_name1;
SQL> drop table table_name1;
SQL> rename table_name2 to table_name1;

==
Insert the distinct rows from the duplicate rows table to new temporary table.
Delete data from table which has duplicate rows then insert the distinct rows from the temporary table as shown below.
select distinct * into #tmp From EmpDup
delete from EmpDup
insert into EmpDup select * from #tmp

drop table #tmp

Categories: Agnihotris Notes | Leave a comment

Multithreading, mutex, semaphore

http://www.linuxdocs.org/HOWTOs/C++Programming-HOWTO-24.html – Nice class

Click to access lect04.pdf

Mutex is a locking mechanism used to synchronize access to a resource. Only one task (either a thread or a process based on OS abstraction) can acquire mutex. There will be ownership associated with mutex, and only owner can release lock.

Semaphore is signaling mechanism.

http://webcache.googleusercontent.com/search?q=cache:http://www.geeksforgeeks.org/mutex-vs-semaphore/

The Producer-consumer problem :-

Note that the content is generalized explanation. Practical details will vary from implementation.

Consider the standard producer-consumer problem. Assume, we have a buffer of 4096 byte length. A producer thread will collect the data and writes it to the buffer. A consumer thread will process the collected data from the buffer. Objective is, both the threads should not run at the same time.

Using Mutex:

A mutex provides mutual exclusion, either producer or consumer can have the key (mutex) and proceed with their work. As long as the buffer is filled by producer, the consumer needs to wait, and vice versa.

At any point of time, only one thread can work with the entire buffer. The concept can be generalized using semaphore.

Using Semaphore:

A semaphore is a generalized mutex. In lieu of single buffer, we can split the 4 KB buffer into four 1 KB buffers (identical resources). A semaphore can be associated with these four buffers. The consumer and producer can work on different buffers at the same time.

Misconception:

There is an ambiguity between binary semaphore and mutex. We might have come across that a mutex is binary semaphore. But they are not! The purpose of mutex and semaphore are different. May be, due to similarity in their implementation a mutex would be referred as binary semaphore.

Strictly speaking, a mutex is locking mechanism used to synchronize access to a resource. Only one task (can be a thread or process based on OS abstraction) can acquire the mutex. It means there will be ownership associated with mutex, and only the owner can release the lock (mutex).

Semaphore is signaling mechanism (“I am done, you can carry on” kind of signal). For example, if you are listening songs (assume it as one task) on your mobile and at the same time your friend called you, an interrupt will be triggered upon which an interrupt service routine (ISR) will signal the call processing task to wakeup.

General Questions:

1. Can a thread acquire more than one lock (Mutex)?

Yes, it is possible that a thread will be in need of more than one resource, hence the locks. If any lock is not available the thread will wait (block) on the lock.

2. Can a mutex be locked more than once?

A mutex is a lock. Only one state (locked/unlocked) is associated with it. However, a recursive mutex can be locked more than once (POSIX complaint systems), in which a count is associated with it, yet retains only one state (locked/unlocked). The programmer must unlock the mutex as many number times as it was locked.

3. What will happen if a non-recursive mutex is locked more than once.

Deadlock. If a thread which had already locked a mutex, tries to lock the mutex again, it will enter into the waiting list of that mutex, which results in deadlock. It is because no other thread can unlock the mutex. An operating system implementer can exercise care in identifying the owner of mutex and return if it is already locked by same thread to prevent deadlocks.

4. Are binary semaphore and mutex same?

No. We will suggest to treat them separately, as it was explained signalling vs locking mechanisms. But a binary semaphore may experience the same critical issues (e.g. priority inversion) associated with mutex. We will cover these later article.

A programmer can prefer mutex rather than creating a semaphore with count 1.

5. What is a mutex and critical section?

Some operating systems use the same word critical section in the API. Usually a mutex is costly operation due to protection protocols associated with it. At last, the objective of mutex is atomic access. There are other ways to achieve atomic access like disabling interrupts which can be much faster but ruins responsiveness. The alternate API makes use of disabling interrupts.

6. What are events?

The semantics of mutex, semaphore, event, critical section, etc… are same. All are synchronization primitives. Based on their cost in using them they are different. We should consult the OS documentation for exact details.

7. Can we acquire mutex/semaphore in an Interrupt Service Routine?

An ISR will run asynchronously in the context of current running thread. It is not recommended to query (blocking call) the availability of synchronization primitives in an ISR. The ISR are meant be short, the call to mutex/semaphore may block the current running thread. However, an ISR can signal a semaphore or unlock a mutex.

8. What we mean by “thread blocking on mutex/semaphore” when they are not available?

Every synchronization primitive will have waiting list associated with it. When the resource is not available, the requesting thread will be moved from the running list of processor to the waiting list of the synchronization primitive. When the resource is available, the higher priority thread on the waiting list will get resource (more precisely, it depends on the scheduling policies).

9. Is it necessary that a thread must block always when resource is not available?

Not necessarily. If the design is sure ‘what has to be done when resource is not available‘, the thread can take up that work (a different code branch). To support application requirements the OS provides non-blocking API.

For example POSIX pthread_mutex_trylock() API. When the mutex is not available the function will return immediately where as the API pthread_mutex_lock() will block the thread till resource is available.

==========================================================================================================
\\\\\\\\\\\\\\\\\\\\\\\\\
/////////////////////////
==========================================================================================================
Mutex can be released only by thread that had acquired it, while you can signal semaphore from any other thread (or process), so semaphores are more suitable for some synchronization problems like producer-consumer.

On Windows, binary semaphores are more like event objects than mutexes.

A mutex is a semaphore with value 1.

—————————–

1. http://blog.feabhas.com/2009/09/mutex-vs-semaphores-%e2%80%93-part-1-semaphores/
2. http://blog.feabhas.com/2009/09/mutex-vs-semaphores-%e2%80%93-part-2-the-mutex/
3. http://blog.feabhas.com/2009/10/mutex-vs-semaphores-%e2%80%93-part-3-final-part-mutual-exclusion-problems/

Categories: Agnihotris Notes | Leave a comment

Non Functional Requirement

1. http://www.csee.umbc.edu/courses/undergraduate/345/spring04/mitchell/nfr.html
2. http://www.cs.toronto.edu/~sme/CSC340F/slides/16-NFRs.pdf
3. http://www.utdallas.edu/~chung/SYSM6309/NFR-18.pdf

Categories: Agnihotris Notes | Leave a comment

SQL Glitches

1. What is index and how it is used :-Index basically contains the memory location range ( starting memory location where first value is stored to end memory location where last value is stored).
Index is like pointers, which points to memory location where data resides.
In book index can take you to the page where you have data.

2. UPDATE statements that modify indexed columns and INSERT and DELETE statements that modify indexed tables take longer than if there were no index. Such SQL statements must modify data in indexes and data in tables. They also create additional undo and redo. Altering a column having index is have overhead.

3. Primary and unique keys automatically have indexes, but you might want to create an index on a foreign key.
Diff between delete , truncate, drop :-
The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. Note that this operation will cause all DELETE triggers on the table to fire.

TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such, TRUNCATE is faster and doesn’t use as much undo space as a DELETE.

The DROP command removes a table from the database. All the tables’ rows, indexes and privileges will also be removed. No DML triggers will be fired. The operation cannot be rolled back.

Categories: Agnihotris Notes | Leave a comment

Agnihotri_2_Const

Agnihotri_2_Const.

Categories: Agnihotris Notes | Leave a comment

Blog at WordPress.com.