Sunday, 11 September 2016

JSON Serialization in Liferay

Many times we have requirement to convert Liferay service response or any list into JSON object. Most of the time we are doing this manually.

JSONArray jsonArr = JSONFactoryUtil.createJSONArray();
for (User user : userList)
{
JSONObject json = JSONFactoryUtil.createJSONObject();
json.put("name", user.getFullName());
json.put("id", user.getUserId());
jsonArr.put(json);
}
return jsonArr.toString();



There are other ways as well by which we can convert List into JSON string.
Service builder has support for JSON  serialization,too. The json-enabled attribute of entity tag specifies whether or not the entity should be annotated for JSONserialization.
By default, if the remote-service value is true, then thejson-enabled value is true.
Column tag has the same attribute, json-enabled.
It specifies whether or not the column should be annotated for JSON serialization. By default, if the json-enabled value in the entity element is true, then the json-enabled value in the column element is true.


<entity name="TestJSON" table="json_test" local-service="true" remote-service="false" json-enabled="true">
<!-- PK fields -->
<column name="keyId" type="long" primary="true" />
<!-- Audit fields -->
<column name="companyId" type="long" />
<column name="groupId" type="long" />
<!-- Other fields -->
<column name="firstName" type="String" json-enabled="true" />
<column name="lastName" type="String" json-enabled="true"/>
<column name="email" type="String" json-enabled="false"/>
<!-- Finder methods -->
</entity>

json enabled is true for enttity TestJson so all the column tags will have by default json-enabled as true.
In case if you want to exclude any property to not to appear when you serialize then you can set json-enabled as false. For email column json-enabled is set to false.



Now you can easily convert your list returned using Liferay services into JSON format.

JSONSerializer jsonSerializer = JSONFactoryUtil.createJSONSerializer();
String json = jsonSerializer.serialize(list);



Same way you can use serialize OOB data as well like user.

 List<User> userList = UserLocalServiceUtil.getUsers(-1, -1);
 String json = JSONFactoryUtil.looseSerialize(userList);

 By default collections are excluded from serialization . You can include them using below way.
 String json  = JSONFactoryUtil.looseSerialize(userList,"organizations")

 Covert List to JSONArray:-

Might be you won't be aware that you can't use existing portal *JsonSerializer.java class in Liferay plugin portlets. So if you want to get JsonArray response of existing liferay service then you can use below code :


import net.sf.json.JSONArray;

List myList = UserLocalserviceUtil.getUsers();
JSONArray jsonArray = JSONArray.fromObject(MyList);



Monday, 11 July 2016

New Liferay Interview Questions

1) What are the various ways in which you can customize the default behavior of Liferay that ships to you?
2) What is the difference between a Liferay Hook and Liferay EXT?
3) Suppose I want to customize the behavior of Calendar portal that comes out of the box with Liferay, how can I do that?
4) How will you configure Liferay to authenticate users from LDAP?
5) What is inter portlet communication and how can that be achieved?
6) What is the difference between view and edit modes of a portlet?
7) What is service.xml and how will you use Liferay service builder?
8 ) Suppose I have a portlet written for Liferay 5.2.3 and I want to run it on Liferay 6, how can I do that? What if I get some spring and hibernate related exceptions with Liferay 6?
9) There is a requirement from the client that out of 4 portlets that you have written only 2 should be visible to a particular category of users. How will you achieve that? What if some fields in the remaining 2 portlets have also to be controlled based on user role?
10) What is the purpose of portal-ext.properties?
11) What steps will you follow to change the layout and theme of the portal pages?
12) Suppose I want to change the background color of the footer in Liferay, what steps should I follow?
13) Which JSR is being implemented by Liferay?
14) What improvements would you like to see in Liferay 6 portal?
15) There are 1000 users using the portlet developed by you, how will you take care of transaction management.
16) A client has two different portal applications for Sales and HR department. The client wants to run these portal applications on same server but with separate URL’s like http://:/sales and http://:/hr. How will you achieve that?
17) What are the minimum Java methods one needs to override in order to write a portlet?
18) How will you make the user to go from one JSP to another JSP page in a portlet?
19) While building a service using service builder, what is the purpose of specifying remoteservice=true in service.xml?
20) How to control the category in which the liferay portlet created by me will be displayed?
21) What is hot deployment feature of Liferay? Where will you place your portlets for them to be deployed without server restart?
22) Does Liferay support email notifications out of the box for portlets involving workflow?
23) What is the purpose of mode and persistence packages which are created by the Liferay service builder?
24) If there are 3 portlets and all of them need to talk to different database systems (say MysSQL, Oracle and SQL Server) because of some legacy appliation requirements. How will you make them connect to different databases?
25) Can you configure the database connection pool created by Liferay?
26) Can you list down various tools and frameworks used by Liferay? e.g. It uses Lucene for search
27) Suppose a client is pursuing a Liferay based solution to their requirements, what non-functional clarifications will you ask from the customer?
28) Is there a build number associated to a portlet assigned by the service builder? Where can we find the current build number?
29) Have you tried the Liferay 6 Eclipse plugin? What all limitations have you found?
30) How do you log events in a portlet? Do I need to configure Log4J for every portlet or is there a common place where one can configure Log4J so that all Liferay portlets can use logging API?
31) Do you know how to update your setup of Liferay 5.2.3 to Liferay 6?
32) Can I run my Struts 1.3 based legacy application as a portlet application? How?
33) Is it a good design to meet the customer requirements by creating a single portlet or splitting them into multiple portlets? What criteria will you use to split the functionality into multiple portlets?
34) What advantages do you see in running the Liferay portal application on a application server like JBoss than running it on a web server like Tomcat?

35) What all other portals have you heard of? How do you compare them to Liferay?
36) How will you implement i18 in a portal application? What if you want the user to choose his language preference?
37) There is a portlet application for managing images similar to Flickr. The user wants to see the images in full screen. Will Liferay allow you to do that?
38) I have a war file of the portlet which is created using service builder, what is the difference between pasting this war file in the deploy folder of Liferay and application folder of server (like webapps in case of Tomcat)?
39) How will you setup a clustered Liferay portal on 5 servers available to you?
40) How much user base can Liferay support without affecting performance?
41) There is a JRE shipped with Liferay package, do we not need a JDK and what is the purpose of bundled JRE?
42) Suppose there is a requirement from client to implement search functionality in Liferay portlet, does Liferay provides any API out of the box to support search?
43) What are the various ways in which one can override the default behaviour of Liferay?
44) The service builder can also build WSDL for you. What is the benefit of this feature provided by Liferay?
45) How will you build a portlet that can be added only single or multiple times in to the portal application?
46) Is it possible to set a session time out for a portlet which is different from other portlets and the Liferay portal?
47) What is the flow of HTTP request in Liferay?
48) The JSPPortlet.java extends  the MVCPortlet.java class. What purpose does MVCPortlet.java fulfill?
49) How do you perform Junit tests on your portlet? How do tackle the dependency on the MVCPortlet.java?
50) Is it mandatory to have the view logic in view.jsp? Can one configure some other JSP (say MyJSP.jsp) to be default view page than view.jsp?

Wednesday, 15 June 2016

Liferay Maven Introduction & Install Maven

Q-What is maven?
ans-"maven is a softwae management and comprehension tool based on the concept of project object model.
Maven do many things for us like resolving dependencies, create project structure, build  a project, creating war/jar etc. By using Maven you can also create portlet, theme, services without any need of sdk. - 

(pom) which can manage project build , reporting and  documentation from centre piece of information."

All build system are essentials the same
there are some step for build projet
1-compile source code.
2-copy resource
3-compile and run test.
4-packge project.
5-deploy project
6-clean up code.

Development of maven wanted:-
Advantege of maven:- maven wanted standard way to build the project they wanted clean definition what the project consist of easy way to publish project information and way to share jar across several the project.
they wanted easy way to build the project and share your project with the colleagues or with the client
so they come up with the tool which is called maven.. which is for building and managing  any java project
maven is intended to make day to day java developer work easier

POM(project object model)
Maven uses the concept of pom..
Q-what is pom?
ans- pom is fundamental unit of work in maven you can say.
"pom is xml file that contain information about the project and configuration details used by maven
to build the project "
note-xml file contail some information
1-describe a project
2- this information contain name, version and artifact, source code location,Dependences of project
3-it also retail the plugin information and profile.
4-it uses xml by default
5- but not the way ant uses xml.

MAVEN Advantag and objective:-

1:-Making the build process easy.
2-provide the uniform a information
3:-provide quality project information
4:-provide guildlines for best practice evelopment
5:-allowing transprant migration for a new feature.

Create first maven project simple

step1-first set class path  with maven
step2-copy that maven project path and pased on command line.
step3-mvn archetype: generate  (this command is used for generate  project from existeing template ) maven project( this command will  help you to create a perfect diretory structure for you)
( when you entre for this command we need internate for download plugin)
note :- generally what happend is  if yu are not using maven than you need to make project structural  by your self


How to create maven project with eclipse:-
ans:-
step:-goto file-new- choose project-search maven-select maven project-next-next-we need to give group id, artifact id,version,package  and leave everything is default
and finish
after  eclipse it will create maven project for us
How maven work internally? 
1--suppose you need any dependencies jar file maven it provide automatically download required  dependencies for that we need to dependency on jar.

example:-if you want unite testing with maven project for that we need to make one java class
inside java class we take one simple method test and write     some dummy code and let say we are returing test

2- we need to right click on test class -goto new-select unit testing we need to give junit test case class name testApp and -finish-ok
3--testApps class you will sea some some error so it required jar file so here maven allow dependencies pom.xml file so that dependenies automatically downloaded jar

for that we need to go pom.xml and add dependencies indise dependencies we need to add dependencies for jnuit project equired junit jar file to compile  maven has online repository from where it can download all the dependencies so just goto google and type maven junit dependencies copy and pased inside dependences after all junit error wiil be remove.

How to install Maven on Windows:-

1. JDK and JAVA_HOME

Make sure JDK is installed, and “JAVA_HOME” variable is added as Windows environment variable.
  • For installing Maven first we need to download maven from here and extract in C drive .

install-maven-on-windows-1

2. Download Apache Maven

Visit Maven official website, download the Maven zip file, for example : apache-maven-3.2.2-bin.zip. Unzip it to the folder you want to install Maven.
Assume you unzip to this folder – C:\Program Files\Apache\maven

3. Add M2_HOME and MAVEN_HOME

Add both M2_HOME and MAVEN_HOME variables in the Windows environment, and point it to your Maven folder.

install-maven-on-windows-3

4. Add To PATH

Update PATH variable, append Maven bin folder – %M2_HOME%\bin, so that you can run the Maven’s command everywhere.

install-maven-on-windows-4

5. Verification

Done, to verify it, run mvn –version in the command prompt.
C:\Users\mkyong>mvn -version
Apache Maven 3.2.2 (45f7c06d68e745d05611f7fd14efb6594181933e; 2014-06-17T21:51:42+08:00)
Maven home: C:\Program Files\Apache\maven
Java version: 1.7.0_65, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.7.0_65\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 8.1", version: "6.3", arch: "amd64", family: "windows"
C:\Users\mkyong>
If you see a similar message, means the Apache Maven is installed successfully on Windows.

Maven Eclipse plugin installation step by step:
  1. Open Eclipse IDE
  2. Click Help -> Install New Software...
  3. Click Add button at top right corner
  4. Now click OK
After that installation would be started.
Another way to install Maven plug-in for Eclipse:
  1. Open Eclipse
  2. Go to Help -> Eclipse Marketplace
  3. Search by Maven
  4. Click "Install" button at "Maven Integration for Eclipse" section
  5. Follow the instruction step by step
After successful installation do the followings in Eclipse:
  1. Go to Window --> Preferences
  2. Observe, Maven is enlisted at left panel
Finally,

  1. Click on an existing project
  2. Select Configure -> Convert to Maven Project




Saturday, 19 March 2016

Java List Collection Examples

1. Overview of List collection

Basically, a list collection stores elements by insertion order (either at the end or at a specific position in the list). A list maintains indices of its elements so it allows adding, retrieving, modifying, removing elements by an integer index (zero-based index; the first element is at 0-index, the second at 1-index, the third at 2-index, and so on). The following picture illustrates a list that stores some String elements:
List Collections
A list can store objects of any types. Primitive types are automatically converted to corresponding wrapper types, e.g. integer numbers are converted to Integer objects. It allows null and duplicate elements, and orders them by their insertion order (index).
The following class diagram depicts the primary methods defined in the java.util.List interface:
List Collections API
The List is the base interface for all list types, and the ArrayList and LinkedList classes are two common List’s implementations.
    • ArrayList: An implementation that stores elements in a backing array. The array’s size will be automatically expanded if there isn’t enough room when adding new elements into the list. It’s possible to set the default size by specifying an initial capacity when creating a new ArrayList. Basically, an ArrayList offers constant time for the following operations: sizeisEmptygetsetiteratorand listIterator; amortized constant time for the add operation; and linear time for other operations. Therefore, this implementation can be considered if we want fast, random access of the elements.
    • LinkedList: An implementation that stores elements in a doubly-linked list data structure. It offers constant time for adding and removing elements at the end of the list; and linear time for operations at other positions in the list. Therefore, we can consider using a LinkedList if fast adding and removing elements at the end of the list is required.
Besides ArrayList and LinkedList, Vector class is a legacy collection and later was retrofitted to implement the Listinterface. Vector is thread-safe, but ArrayList and LinkedList are not. The following class diagram depicts the inheritance tree of the List collections:
List Collections class diagram
The following is a quick example of creating a new ArrayList and LinkedList which hold String objects; add some elements to them; and then print out the collections:
  • ArrayList  quick example:
    1
    2
    3
    4
    5
    6
    7
    List<String> listStrings = new ArrayList<String>();
    listStrings.add("One");
    listStrings.add("Two");
    listStrings.add("Three");
    listStrings.add("Four");
     
    System.out.println(listStrings);
     
  • LinkedList  quick example:
    1
    2
    3
    4
    5
    6
    7
    List<String> listStrings = new LinkedList<String>();
    listStrings.add("Five");
    listStrings.add("Six");
    listStrings.add("Seven");
    listStrings.add("Eight");
     
    System.out.println(listStrings);

The code examples in this tutorial revolve on the two common implementations: ArrayList and LinkedList.


2. Creating a new list

It’s a good practice to declare a list instance with a generic type parameter, for example:
1
2
3
4
List<Object> listAnything = new ArrayList<Object>();
List<String> listWords = new ArrayList<String>();
List<Integer> listNumbers = new ArrayList<Integer>();
List<String> linkedWords = new LinkedList<String>();
Since Java 7, we can remove the type parameter on the right side as follows:
1
2
List<Integer> listNumbers = new ArrayList<>();
List<String> linkedWords = new LinkedList<>();
The compiler is able to infer the actual type parameter from the declaration on the left side.
When creating a new ArrayList using the empty constructor, the list is constructed with an initial capacity of ten. If you are sure how many elements will be added to the list, it’s recommended to specify a capacity which is large enough. Let’s say, if we know that a list contains around 1000 elements, declare the list as follows:
1
List<Integer> listNumbers = new ArrayList<>(1000);
It’s also possible to construct a list that takes elements from an existing collection, for example:
1
2
3
List<Integer> listNumberOne;  // existing collection
 
List<Integer> listNumberTwo = new ArrayList<>(listNumberOne);
The listNumberTwo constructed with copies of all elements from the listNumberOne.


3. Basic operations: adding, retrieving, updating, removing elements

Adding elements
The methods add(Object)add(index, Object) and addAll() are used to add elements to the list. It requires to add elements of the same type (or sub type) as the type parameter declared by the list. For example:
1
2
3
4
5
6
7
8
9
List<String> listStrings = new ArrayList<String>();
 
// OK to add Strings:
listStrings.add("One");
listStrings.add("Two");
listStrings.add("Three");
 
// But this will cause compile error
listStrings.add(123);
Adding elements of sub types of the declared type:
1
2
3
4
5
6
List<Number> linkedNumbers = new LinkedList<>();
 
linkedNumbers.add(new Integer(123));
linkedNumbers.add(new Float(3.1415));
linkedNumbers.add(new Double(299.988));
linkedNumbers.add(new Long(67000));
We can insert an element into the list at a specified index, for example:
1
listStrings.add(1"Four");
That inserts the String “Four” at the 2nd position in the list.
We can also add all elements of an existing collection to the end of the list:
1
listStrings.addAll(listWords);
Or add the elements to the list at a specified position:
1
listStrings.addAll(2, listWords);
That inserts all elements of the listWords collection at 3rd position of the listStrings collection.

Retrieving elements
The get() method is used to retrieve an element from the list at a specified index. For example, the following code gets an element at 2nd position in the array list and an element at 4th position in the linked list:
1
2
String element = listStrings.get(1);
Number number = linkedNumbers.get(3);
For a LinkedList implementation, we can get the first and the last elements like this:
1
2
3
4
5
6
LinkedList<Number> numbers = new LinkedList<Number>();
// add elements to the list...
 
// get the first and the last elements:
Number first = numbers.getFirst();
Number last = numbers.getLast();
Note that the getFirst() and getLast() methods are specific to the LinkedList class.

Updating elements
Use the set(index, element) method to replace the element at the specified index by the specified element. For example:
1
listStrings.set(2"Hi");
That replaces the 3rd element in the list by the new String “Hi”.

Removing elements
To remove an element from the list, use the remove(index) or remove(Object) method which removes the element at the specified index or by object reference. For example:
    • Remove the element at the 3rd position in the list:
      1
      listStrings.remove(2);
      If the specified index is out of range (index < 0 or index >= list size), a java.lang.IndexOutOfBoundsException is thrown.
    • Remove the String element “Two” in the list:
      1
      listStrings.remove("Two");
Notes about the remove(Object) method:
    • It compares the specified object with the elements in the list using their equals() method, so if you use your own defined object type, make sure it implements the equals() method correctly.
    • It only removes the first occurrence of the specified element in the list (i.e. if a list contains duplicate elements, only the first element is removed).
    • It returns true if the list contained the specified element, or falseotherwise. Thus it’s recommended to check return value of this method, for example:
      1
      2
      3
      4
      5
      if (listStrings.remove("Ten")) {
          System.out.println("Removed");
      else {
          System.out.println("There is no such element");
      }
       
To remove all elements in the list, use the clear() method:
1
listStrings.clear();


4. Iterating over a list

Basically, we can use the enhanced for loop to iterate through all elements in the list, as follows:
1
2
3
for (String element : listStrings) {
    System.out.println(element);
}
Or use an iterator like this:
1
2
3
4
5
Iterator<String> iterator = listStrings.iterator();
 
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}
For more list-specific, use a list iterator as shown below:
1
2
3
4
5
Iterator<Number> iterator = linkedNumbers.listIterator();
 
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}
Since Java 8, we can use the forEach()method like this:

1
listStrings.forEach(s -> System.out.println(s));



For more details and examples, see the tutorial: Java Collections Looping Example
For more about the forEach iteration method, see the tutorial: The 4 Methods for Iterating Collections in Java


5. Searching for an element in a list

To search for position of a specific element in the list or to know if the list contains the specified element, the following methods can be used:
    • boolean contains(Object): returns true if the list contains the specified element.
    • int indexOf(Object): returns the index of the first occurrence of the specified element in the list, or -1 if the element is not found.
    • int lastIndexOf(Object): returns the index of the last occurrence of the specified element in the list, or -1 if the element is not found.
Examples:
1
2
3
4
5
6
7
8
9
if (listStrings.contains("Hello")) {
    System.out.println("Found the element");
else {
    System.out.println("There is no such element");
}
 
 
int firstIndex = linkedNumbers.indexOf(1234);
int lastIndex = listStrings.indexOf("Hello");
Note that the above methods compare the elements using their equals() method, so if you define your own type, make sure it implements the equals() method correctly.


6. Sorting a list

The simplest way to sort out elements in a list is using the Collections.sort() static method which sorts the specified list into ascending order, based on the natural ordering of its elements. Here’s an example:
1
2
3
4
5
6
7
8
9
10
11
12
List<String> listStrings = new ArrayList<String>();
listStrings.add("D");
listStrings.add("C");
listStrings.add("E");
listStrings.add("A");
listStrings.add("B");
 
System.out.println("listStrings before sorting: " + listStrings);
 
Collections.sort(listStrings);
 
System.out.println("listStrings after sorting: " + listStrings);
Output:
1
2
listStrings before sorting: [D, C, E, A, B]
listStrings after sorting: [A, B, C, D, E]
Note that all elements in the list must implement the Comparable interface, so if you define your own type, make sure it implements that interface and its compareTo() method.
For more details and examples, see the article: Sorting List Collections Examples


7. Copying one list into another

The Collections.copyList(dest, src) static method allows us to copy all elements from the source list into the destination one. Note that the destination list must be large enough to contain the entire source list. Here’s an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
List<String> sourceList = new ArrayList<String>();
sourceList.add("A");
sourceList.add("B");
sourceList.add("C");
sourceList.add("D");
 
List<String> destList = new ArrayList<String>();
destList.add("V");
destList.add("W");
destList.add("X");
destList.add("Y");
destList.add("Z");
 
System.out.println("destList before copy: " + destList);
 
Collections.copy(destList, sourceList);
 
System.out.println("destList after copy: " + destList);
The output would be:
1
2
destList before copy: [V, W, X, Y, Z]
destList after copy: [A, B, C, D, Z]


8. Shuffling elements in a list

To randomly permute elements in a list, use the Collections.shuffle() static method. Here’s a quick example:
1
2
3
4
5
6
7
8
List<Integer> numbers = new ArrayList<Integer>();
for (int i = 0; i <= 10; i++) numbers.add(i);
 
System.out.println("List before shuffling: " + numbers);
 
Collections.shuffle(numbers);
 
System.out.println("List after shuffling: " + numbers);
The output would be:
1
2
List before shuffling: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
List after shuffling: [6, 4, 5, 0, 1, 3, 9, 7, 2, 10, 8]

 


9. Reversing elements in a list

To reverse order of elements in a list, use the Collections.reverse() static method. Here’s a quick example:
1
2
3
4
5
6
7
8
List<Integer> numbers = new ArrayList<Integer>();
for (int i = 0; i <= 10; i++) numbers.add(i);
 
System.out.println("List before reversing: " + numbers);
 
Collections.reverse(numbers);
 
System.out.println("List after reversing: " + numbers);
The output would be:
1
2
List before reversing: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
List after reversing: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

 

10. Extracting a portion of a list

The subList(fromIndextoIndex) allows us to get a portion of the list between the specified fromIndex (inclusive) andtoIndex (exclusive). Here’s an example:
1
2
3
4
5
List<String> listNames = Arrays.asList("Tom""John""Mary""Peter""David""Alice");
System.out.println("Original list: " + listNames);
 
List<String> subList = listNames.subList(25);
System.out.println("Sub list: " + subList);
Output:
1
2
Original list: [Tom, John, Mary, Peter, David, Alice]
Sub list: [Mary, Peter, David]
Note that the sub list is just a view of the original list, so any modifications made on the original list will reflect in the sub list.

11. Converting between Lists and arrays

The Java Collection Framework allows us to easily convert between lists and arrays.
The Arrays.asList(T… a) method converts an array of type T to a list of type T. Here’s an example:
1
2
3
4
5
6
List<String> listNames = Arrays.asList("John""Peter""Tom""Mary""David""Sam");
 
List<Integer> listNumbers = Arrays.asList(135792468);
 
System.out.println(listNames);
System.out.println(listNumbers);
Output:
1
2
[John, Peter, Tom, Mary, David, Sam]
[1, 3, 5, 7, 9, 2, 4, 6, 8]
And the List interface provides the toArray() method that returns an array of Objects containing all of the elements in the list in proper sequence (from first to last element). Here’s an example:
1
2
3
4
List<String> listWords = new ArrayList<String>();
// add elements to the list
 
Object[] arrayWords = listWords.toArray();
And the toArray(T[] a) method returns an array of type T, for example:
1
2
String[] words = listWords.toArray(new String[0]);
Integer[] numbers = listNumbers.toArray(new Integer[0]);
Note that the returned array contains copies of elements in the list, which that means we can safely modify the array without affecting the list.


12. Concurrent lists

By default, ArrayList and LinkedList are not thread-safe, so if you want to use them in concurrent context, you have to synchronize them externally using the Collections.synchronizedList() static method which returns a synchronized list that wraps the specified list. For example:
1
2
List<Object> unsafeList = new ArrayList<Object>();
List<Object> safeList = Collections.synchronizedList(unsafeList);
Note that you must manually synchronize the returned list when iterating over it, for example:
1
2
3
4
5
6
synchronized (safeList) {
    Iterator<Object> it = safeList.iterator();
    while (it.hasNext()) {
        System.out.println(it.next());
    }
}