View Javadoc
1   /*
2   
3       dsh-color-scheme  Color schemes.
4       Copyright (c) 2009-2016 held jointly by the individual authors.
5   
6       This library is free software; you can redistribute it and/or modify it
7       under the terms of the GNU Lesser General Public License as published
8       by the Free Software Foundation; either version 3 of the License, or (at
9       your option) any later version.
10  
11      This library is distributed in the hope that it will be useful, but WITHOUT
12      ANY WARRANTY; with out even the implied warranty of MERCHANTABILITY or
13      FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
14      License for more details.
15  
16      You should have received a copy of the GNU Lesser General Public License
17      along with this library;  if not, write to the Free Software Foundation,
18      Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA.
19  
20      > http://www.fsf.org/licensing/licenses/lgpl.html
21      > http://www.opensource.org/licenses/lgpl-license.php
22  
23  */
24  package org.dishevelled.color.scheme.factory;
25  
26  import java.awt.Color;
27  
28  import java.util.concurrent.Callable;
29  import java.util.concurrent.ExecutionException;
30  
31  import com.google.common.cache.Cache;
32  import com.google.common.cache.CacheBuilder;
33  
34  import org.dishevelled.color.scheme.ColorFactory;
35  
36  /**
37   * Caching color factory.
38   *
39   * @author  Michael Heuer
40   */
41  public final class CachingColorFactory
42      implements ColorFactory
43  {
44      /** Cache of colors keyed by integer ARGB value. */
45      private final Cache<Integer, Color> colors = CacheBuilder.newBuilder()
46          .maximumSize(100000L)
47          .build();
48  
49      @Override
50      public Color createColor(final int red, final int green, final int blue, final float alpha)
51      {
52          final int a = Math.min(255, Math.round(alpha * 255));
53          final int key = (a & 0xFF) << 24 | (red & 0xFF) << 16 | (green & 0xFF) << 8  | (blue & 0xFF) << 0;
54  
55          try
56          {
57              return colors.get(key, new Callable<Color>()
58                  {
59                      @Override
60                      public Color call()
61                      {
62                          return new Color(red, green, blue, a);
63                      }
64                  });
65          }
66          catch (ExecutionException e)
67          {
68              // shouldn't happen, no checked exceptions are thrown above
69              return Color.WHITE;
70          }
71      }
72  }